VB.NET form filling value isn't visible - vb.net

I'm trying to fill a PDF Form File with iTextSharp (version 5.5.13).
My code doesn't work, the fields in the PdfFile are empty:
Dim pdfreader As PdfReader = New PdfReader(My.Resources.Dienstnachweis_BRK_Bereitschaft_Münchberg)
Dim pdfStamper As PdfStamper = New PdfStamper(pdfreader, New FileStream(newFile, FileMode.Create, FileAccess.ReadWrite), "\0", True)
pdfreader.RemoveUsageRights()
Dim pdfformfields As AcroFields = pdfStamper.AcroFields
pdfStamper.AcroFields.SetField("Datum", txtdatum.Text)
pdfStamper.AcroFields.SetField("Veranstaltung", txtdatum.Text)
pdfStamper.AcroFields.SetField("Dienstverantwortlicher", txtel.Text)
pdfformfields.SetField("Datum", txtdatum.Text, txtdatum.Text, True)
pdfformfields.SetField("Veranstaltung", txtdienstname.Text, txtdienstname.Text, True)
pdfformfields.SetField("Ort", txtdienstname.Text, txtdienstname.Text, True)
pdfformfields.SetField("Dienstverantworlicher", txtel.Text, txtel.Text, True)
pdfStamper.FormFlattening = False
pdfStamper.Close()
pdfreader.Close()
Process.Start(folderPath & "Dienstnachweis vom " & Now.ToShortDateString & ".pdf")
My PDF file.
This is a screenshot from my PdfFile:

Your issue cannot be reproduced.
Tested code
Obviously I could not test with your code as is because I don't have your variable values at hand, in particular not all those test fields. Thus, I used fixed strings instead:
Dim pdfreader As PdfReader = New PdfReader("Dienstnachweis BRK Bereitschaft Münchberg.pdf")
Dim pdfStamper As PdfStamper = New PdfStamper(pdfreader, New FileStream("Dienstnachweis BRK Bereitschaft Münchberg-filled.pdf", FileMode.Create, FileAccess.ReadWrite), "\0", True)
pdfreader.RemoveUsageRights()
Dim pdfformfields As AcroFields = pdfStamper.AcroFields
pdfStamper.AcroFields.SetField("Datum", "txtdatum.Text")
pdfStamper.AcroFields.SetField("Veranstaltung", "txtdatum.Text")
pdfStamper.AcroFields.SetField("Dienstverantwortlicher", "txtel.Text")
pdfformfields.SetField("Datum", "txtdatum.Text", "txtdatum.Text", True)
pdfformfields.SetField("Veranstaltung", "txtdienstname.Text", "txtdienstname.Text", True)
pdfformfields.SetField("Ort", "txtdienstname.Text", "txtdienstname.Text", True)
pdfformfields.SetField("Dienstverantworlicher", "txtel.Text", "txtel.Text", True)
pdfStamper.FormFlattening = False
pdfStamper.Close()
pdfreader.Close()
The result
Running the code above with your example PDF in the current work directory I get a result PDF which is displayed like this in a current PDF Acrobat Reader:
Thus, the fields are properly filled. I also checked the PDF internally, e.g. the field "Datum":
As you can see, the text "txtdatum.Text" is also present as value of the abstract field (the V value), not only in the appearance.

Related

I have to get a pdf mainstream using itexsharp after have add a password

I am writing code for add a password in a pdf (I have an array of byte, not a file in a dir) but i have problem with outputStream (I need another array but protect from password): it is 15 bite and not contains the start pdf. I use a itexsharp 5.5 version, is not young but not very old, how is the error?
thi is my code:
Dim PasswordUser As String = ""
Dim UserPassByte = Encoding.Unicode.GetBytes(PasswordUser)
Dim ownerPassword As String = "1"
Dim ownerPassByte = Encoding.Unicode.GetBytes(ownerPassword)
Dim reader As New PdfReader("c:\tmp\pdfx.pdf")
Dim array As Byte()
Using outputStream As New MemoryStream
Dim PdfStamper As New PdfStamper(reader, outputStream)
PdfStamper.SetEncryption(UserPassByte, ownerPassByte, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128)
PdfStamper.FormFlattening = True
array = outputStream.ToArray()
End Using

ITextSharp exported PDF is not supported or damaged visual basic

I'm new to using ITextSharp and I'm trying to export a PDF as an attachment. The code below works fine
Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim newFile As String = "C:\Users\mrogers\Documents\ERCP_CA_Template3.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, New System.IO.FileStream(newFile, System.IO.FileMode.Create))
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True
pdfStamper.Close()
However, when I try to convert this to export an attachment, Adobe Acrobat Reader can't open the file because it's not a supported type or it's been damaged. My Code is below.
Dim ms As MemoryStream = New MemoryStream()
Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, ms)
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=testingPdf2.pdf")
HttpContext.Current.Response.Write(ms.ToArray())
HttpContext.Current.Response.BufferOutput = True
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Close()
pdfStamper.Close()
I've been struggling to find any good examples or documentation on this. Any assistance on where I'm going wrong would be appreciated.
For anyone having a similar issue I figured it out.
Dim output As New MemoryStream()
Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, output)
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True
pdfStamper.Close()
Dim mergedBytes() As Byte = output.GetBuffer()
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=demo4.pdf")
HttpContext.Current.Response.AddHeader("Content-Length", mergedBytes.Length.ToString())
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.BinaryWrite(mergedBytes.ToArray)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()

VB NET 'The process cannot access the file 'C:\ProjectVB\Downloads\' because it is being used by another process.'

I'm having trouble solving a problem about how to create a watermark in pdf using vb net.
Is there anyone here who can help solve my problem?
Dim document As Document = New Document()
' Dim pdfReader As PdfReader = New PdfReader("C:\Users\IT-SMJ\Downloads\Documents\BUKU-ROLLY-YESPUTRA-VBNET.pdf")
Dim pdfReader As PdfReader = New PdfReader("C:\ProjectVB\Uploads\" & System.IO.Path.GetFileName(Tcarifile.Text))
' Dim pdfStamper As PdfStamper = New PdfStamper(PdfReader, New FileStream("C:\Users\IT-SMJ\Downloads\Docs\BUKU-ROLLY-YESPUTRA-VBNET.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
Dim pdfStamper As PdfStamper = New PdfStamper(pdfReader, New FileStream("C:\ProjectVB\Uploads\" & System.IO.Path.GetFileName(Tcarifile.Text), FileMode.Create, FileAccess.Write, FileShare.None))
Dim img As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance("C:\Users\IT-SMJ\Downloads\watermaku.png")
img.SetAbsolutePosition(170, 70)
Dim waterMark As PdfContentByte
For pageIndex As Integer = 1 To pdfReader.NumberOfPages
waterMark = pdfStamper.GetOverContent(pageIndex)
waterMark.AddImage(img)
Next
pdfStamper.FormFlattening = True
pdfStamper.Close()

export arabic data to pdf using itext

I want to export gridview data to PDF, using iTextsharp. The gridview data contains Persian/Arabic data. It results in just a blank PDF file... what could be the reason?
Following is my code:
GridView1.DataSource = Session("dt")
GridView1.AllowPaging = False
GridView1.DataBind()
Dim bf As BaseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") & "\fonts\tahoma.ttf", BaseFont.IDENTITY_H, True)
Dim font As New iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL)
Dim table As New iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count)
Dim widths As Integer() = New Integer(GridView1.Columns.Count - 1) {}
For x As Integer = 0 To GridView1.Columns.Count - 1
widths(x) = CInt(GridView1.Columns(x).ItemStyle.Width.Value)
Dim cellText As String = Server.HtmlDecode(GridView1.HeaderRow.Cells(x).Text)
Dim cell As New iTextSharp.text.pdf.PdfPCell(New Phrase(12, cellText, font))
cell.BackgroundColor = New BaseColor(GridView1.HeaderStyle.BackColor)
'cell.BackgroundColor = New BaseColor(System.Drawing.ColorTranslator.FromHtml("#008000"))
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
table.AddCell(cell)
Next
table.SetWidths(widths)
For i As Integer = 0 To GridView1.Rows.Count - 1
If GridView1.Rows(i).RowType = DataControlRowType.DataRow Then
For j As Integer = 0 To GridView1.Columns.Count - 1
Dim cellText As String = Server.HtmlDecode(GridView1.Rows(i).Cells(j).Text)
Dim cell As New iTextSharp.text.pdf.PdfPCell(New Phrase(12, cellText, font))
'Set Color of Alternating row
If i Mod 2 <> 0 Then
'cell.BackgroundColor = New BaseColor(System.Drawing.ColorTranslator.FromHtml("#C2D69B"))
cell.BackgroundColor = New BaseColor(GridView1.RowStyle.BackColor)
End If
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
table.AddCell(cell)
Next
End If
Next
'Create the PDF Document
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
pdfDoc.Add(table)
pdfDoc.Close()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(pdfDoc)
Response.[End]()
Your question is somewhat misleading because the problem you are experiencing is not caused by the fact that you are using Arabic. If you would write the document to a file, you would notice that the file is OK.
There is a serious error in these lines:
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
...
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(pdfDoc)
Response.[End]()
First you use the Response.OutputStream to write PDF bytes to it, then you use the Response object to set content headers. This is illegal syntax: you should always define your headers before sending any bytes to the output stream.
Furtermore: you should write PDF bytes to the outputstream, not a Document object. The following line is complete non sense:
Response.Write(pdfDoc)
For an example on how to send content bytes to the Response.OutputStream, read the answers to the following question: iTextSharp generated PDF: How to send the pdf to the client and add a prompt?
If you don't know how to create content byte, take a look at this code snippet:
using (MemoryStream myMemoryStream = new MemoryStream()) {
Document document = new Document();
PdfWriter PDFWriter = PdfWriter.GetInstance(document, myMemoryStream);
document.Open();
...
document.Close();
byte[] content = myMemoryStream.ToArray();
...
}
Never write an object such as document to an output stream, always use a byte[].

ITextSharp include all pages from the input file

I used the following code by using itextsharp library to add text to a pdf.(got the code from link ITextSharp insert text to an existing pdf
Dim reader As New PdfReader(oldFile)
Dim size As iTextSharp.text.Rectangle = reader.GetPageSizeWithRotation(1)
Dim document As New iTextSharp.text.Document(size)
' open the writer
Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
' the pdf content
Dim cb As PdfContentByte = writer.DirectContent
' select the font properties
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.ZAPFDINGBATS, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
'cb.SetColorFill(GrayColor.DARK_GRAY)
cb.SetFontAndSize(bf, 8)
cb.BeginText()
Dim Text As String = "l"
' put the alignment and coordinates here
cb.ShowTextAligned(2, Text, 84, 729, 0)
cb.EndText()
Dim bf1 As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
cb.SetFontAndSize(bf1, 8)
cb.BeginText()
Dim text1 As String = "Navaneeth A"
cb.ShowTextAligned(1, text1, 65, 690, 0)
cb.EndText()
' create the new page and add it to the pdf
Dim page As PdfImportedPage = writer.GetImportedPage(reader, 1)
cb.AddTemplate(page, 0, 0)
' close the streams and voilá the file should be changed :)
document.Close()
fs.Close()
writer.Close()
reader.Close()
Now the problem is source pdf has about 5 pages.But the output file generated by this code has only first page. So How can i include all pages of source file in output file?
Source pdf link is http://law.incometaxindia.gov.in/DITTaxmann/IncomeTaxRules/PDF/Ay-2012-2013/SAHAJ2012_14.pdf
Dim reader As New PdfReader(oldFile)
Using ms = New MemoryStream()
Dim stamper As New PdfStamper(reader, ms)
'Using stamper 'As New PdfStamper(reader, ms)
stamper.RotateContents = False
Dim canvas As PdfContentByte = stamper.GetOverContent(1)
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, New Phrase("Hello people!"), 36, 540, 0)
'End Using
Dim result As Byte() = ms.ToArray()
File.WriteAllBytes(newFile, result)
System.Diagnostics.Process.Start(newFile)
End Using
I did the following changes,but its not working.result file was just a 1kb file.
You unfortunately found sample code that should not be used. To manipulate existing PDFs you should use a PdfStamper, not a PdfWriter.
Your code (even after correction to copy all pages) does not copy interactive features (forms, other annotations...). You should instead base your code on the Webified iTextSharp Example StampText.cs explained in chapter 6 of iText in Action — 2nd Edition:
PdfReader reader = new PdfReader(resource);
using (var ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
stamper.RotateContents = false;
PdfContentByte canvas = stamper.GetOverContent(1);
ColumnText.ShowTextAligned(
canvas,
Element.ALIGN_LEFT,
new Phrase("Hello people!"),
36, 540, 0
);
}
byte[] result = ms.ToArray();
}
You can control font and color, too, if you change that code like this:
[...]
Font FONT = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, new GrayColor(0.75f));
PdfContentByte canvas = stamper.GetOverContent(1);
ColumnText.ShowTextAligned(
canvas,
Element.ALIGN_LEFT,
new Phrase("Hello people!", FONT),
36, 540, 0
);
[...]
PS Some details may vary if you for some reasons have to use some old iTextSharp version (other questions from you seem to imply that you use VB6...). Even then, though, you should switch to using PdfStamper.