iTextSharp VB.NET change the font of a Paragraph - vb.net

I'm learning iTextsharp and is hard without good documentation.
I want to change the font of one paragraph
Reading from http://www.mikesdotnetting.com/Article/81/iTextSharp-Working-with-Fonts and trying to move the code to VB.NEt
I have this
Dim pdfDoc As New Document(PageSize.A4, 72.0F, 72.0F, 72.0F, 72.0F)
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("c:\\PDFSample.pdf", FileMode.Create))
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false)
Font times = new Font(bfTimes, 12, Font.ITALIC, Color.RED)
pdfDoc.Open()
pdfDoc.Add(New Paragraph("This is normal text"))
pdfDoc.Add(New Paragraph("Now the text is times", times))
pdfDoc.Close()
but I get the error
'BaseFont' is a class type and cannot be used as expression

Related

VB.NET form filling value isn't visible

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.

Text over image in itextsharp

I need load a pdf, add text and save on a new file.
With this code look work but where i have some images the text in under the image, i can't see it.
What can i do ?
Dim oldFile As String = Application.StartupPath & "\old.pdf"
Dim newFile As String = Application.StartupPath & "\new.pdf"
Dim reader As New PdfReader(oldFile)
Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
Dim document As New Document(size)
Dim wNnumberOfPages As Integer = reader.NumberOfPages
Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
document.Open()
Dim cb As PdfContentByte = writer.DirectContent
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
Dim wPage As Integer
For wPage = 1 To wNnumberOfPages
Dim _text As String = "TEXT"
Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
cb.AddTemplate(Page, 0, 0)
document.NewPage()
Next
document.Close()
fs.Close()
writer.Close()
reader.Close()
You first draw the text and then draw the imported page:
Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
cb.AddTemplate(Page, 0, 0)
Thus, any content in the imported page at the location of your text will cover it.
If instead you first draw the imported page and then the text, your text will be above content from the imported page:
Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.AddTemplate(Page, 0, 0)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
That being said, if you want to merely stamp something onto pages of an existing PDF, you should use the PdfStamper instead of PdfWriter with GetImportedPage. The PdfStamper class explicitly is made for such tasks and copies everything from the source document very faithfully. Your approach, on the other hand, drops all interactive and metadata content from the original PDF.

How to saving PDF files to a folder ? vb.net or itsharptext

I create a table in iTextSharp, all goods, but i want to save in specfific folder;
My code are:
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & so & ".pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim pdfDoc As New Document(PageSize.A4, 0.0F, 0.0F, 10.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
HERE CODE!!!
Here i put my code and create PDF and i finish with:
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
Where i put my location like that:
"\art-fs02\07_ART_ECO\12_Samples\03_Samples_order\01_Samples_BOMs_&_DRW\"
Just use FileStream to save your document.
Dim pdfDoc As New Document(iTextSharp.text.PageSize.A4)
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + "yourPDFdesiredName.pdf", FileMode.Create))
Saving PDF files to desktop [VB .NET]

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.