How to introduce new line characters with iTextSharp - vb.net

I have written following code to write text in PDF and i want to break the line after some text .
Dim document As Document
document = New Document(PageSize.A4, 5.0F, 20.0F, 20.0F, 20.0F)
Try
Dim writer As PdfWriter
writer = PdfWriter.GetInstance(document, New FileStream(filename, FileMode.Create))
document.Open()
Dim spacing As Integer
spacing = 0
Dim curY, lineHeight As Double
curY = document.Top
lineHeight = 0
Const maxPerLine As Integer = 3
For i As Integer = 0 To 5
Dim table As PdfPTable
table = New PdfPTable(4)
table.DefaultCell.Border = Rectangle.NO_BORDER
table.TotalWidth = 200.0F
table.LockedWidth = True
Dim cell As PdfPCell
cell = New PdfPCell(New Phrase("hello \n" + i + "\n" + "wass up ?" ))
cell.Colspan = 4
cell.HorizontalAlignment = 0
cell.Border = Rectangle.NO_BORDER
cell.Padding = 30.0F
table.AddCell(cell)
table.WriteSelectedRows(0, -1, document.Left + spacing, curY, writer.DirectContent)
spacing = spacing + 200
lineHeight = Math.Max(lineHeight, table.TotalHeight)
If 0 = (i + 1) Mod maxPerLine Then
curY = curY - lineHeight
spacing = 0
lineHeight = 0
End If
Next
Catch ex As Exception
Finally
document.Close()
End Try
i have tried with Paragraph but still i am not able to enter texts into new line.
I have read the doc of iTextSharp they have written if you want to break line then use "\n" but it is not working.
How can i break line after some text ?

The easiest way, is to use PdfPCell in composite mode (you're using text mode). Composite mode gets into play when you use AddElement:
Dim cell As PdfPCell
cell = New PdfPCell()
cell.AddElement(New Paragraph("line 1"))
cell.AddElement(New Paragraph("line 2"))
Note that you can't set the alignment at the level of the PdfPCell in this case. When using composite mode, you have to set the alignment at the level of the elements (in this case at the level of the Paragraph).

Related

editing PDF to add page number | VB.net

I am looking to modify the pdf to add the page number and I cannot find why the variable "cb" is empty.
you can see error on the screen below
Error on the screen : "Object reference not set to an instance of an object"
I just found how to edit pdf and add pages number, here is my code for those who need it.
I copy a file, I count the number of pages, in a while loop I display the number of pages (1/3) then I import the page on which I wanted to add the number of pages.
Public Sub ModifPDF(ByVal annee As Integer, ByVal mois As Integer, ByVal nomFichier As String, ByVal sourceFileList As String)
Dim Col1 As PdfPCell
Dim Col2 As PdfPCell
Dim Font1 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 1, iTextSharp.text.Font.NORMAL))
Dim Font8 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL))
Dim Vide As PdfPCell = New PdfPCell(New Phrase("")) With {
.Border = 0
}
Dim reader As New PdfReader(sourceFileList)
Dim sourceFilePageCount As Integer = reader.NumberOfPages
Dim doc As New Document(reader.GetPageSizeWithRotation(1))
My.Computer.FileSystem.CopyFile(sourceFileList, "C:\test")
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("C:\test", FileMode.Open, FileAccess.Write))
doc.Open()
Dim contentByte As PdfContentByte = writer.DirectContent
Dim pageIndex As Integer = 0
While pageIndex < sourceFilePageCount
pageIndex = pageIndex + 1
doc.SetPageSize(reader.GetPageSize(pageIndex))
Dim TableNota As PdfPTable = New PdfPTable(2)
Dim widthsNota As Single() = New Single() {19.7F, 1.5F}
TableNota.WidthPercentage = 97
TableNota.SetWidths(widthsNota)
Col1 = New PdfPCell(New Phrase(" ", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col1)
Col2 = New PdfPCell(New Phrase("page " & pageIndex & "/" & sourceFilePageCount & "", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col2)
TableNota.AddCell(Vide)
doc.Add(TableNota)
Dim page = writer.GetImportedPage(reader, pageIndex)
Dim rotation = reader.GetPageRotation(pageIndex)
If rotation.Equals(90) Then
contentByte.AddTemplate(page, 0, -0.1F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height)
Else
contentByte.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
doc.NewPage()
End While
doc.Close()
End Sub

delete pdf file after merging vb.net using iTextSharp

I'm merging two pdf into one i'm using a function that I found here
Private Sub MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String)
Dim pdfCount As Integer = 0
Dim f As Integer = 0
Dim fileName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing
Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0
Try
pdfCount = pdfFiles.Length
If pdfCount > 1 Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
.Open()
End With
cb = writer.DirectContent
While f < pdfCount
Dim i As Integer = 0
While i < pageCount
i += 1
pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i))
pdfDoc.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
f += 1
If f < pdfCount Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
End If
End While
pdfDoc.Close()
reader.Close()
End If
Catch ex As Exception
'err
End Try
End Sub
Now I need to delete the old files "pdfFiles()" but I'm getting the error "The process cannot access the file 'C:.......pdf' because it is being used by another process." this is only happening with the first file, I have no problem with the other one
OP Here with the function
Thanks
I know this is in C# but this is what i use to merge files together.
var document = new Document();
var outFile = Path.Combine(finishedFilePath, fileName + ".pdf");
var writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
try
{
document.Open();
foreach (var fileName in filesList)
{
var reader = new PdfReader(Path.Combine(StartPath, fileName));
for (var i = 1; i <= reader.NumberOfPages; i++)
{
var page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
reader.Close();
}
writer.Close();
document.Close();
}
catch (Exception ex)
{
//catch error
}
finally
{
writer.Close();
document.Close();
}
Hope this helps in some way.
The code that was marked correct is in C# here is the vb.net version:
Public Sub MergePDFFiles(ByVal outPutPDF As String)
Dim StartPath As String = FileArray(0) ' this is a List Array declared Globally
Dim document = New Document()
Dim outFile = Path.Combine(outPutPDF)' The outPutPDF varable is passed from another sub this is the output path
Dim writer = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
Try
document.Open()
For Each fileName As String In FileArray
Dim reader = New PdfReader(Path.Combine(StartPath, fileName))
For i As Integer = 1 To reader.NumberOfPages
Dim page = writer.GetImportedPage(reader, i)
writer.AddPage(page)
Next i
reader.Close()
Next
writer.Close()
document.Close()
Catch ex As Exception
'catch a Exception if needed
Finally
writer.Close()
document.Close()
End Try
End Sub

ITextSharp Margin

I am working with itexsharp and I have problem because it does not assign the margin of the document
This is the code.
Dim pdfw As PdfWriter
Dim documentoPDF As New Document(iTextSharp.text.PageSize.A4.Rotate(), 20, 20, 20, 20) 'Creamos el objeto documento PDF
documentoPDF.SetMargins(0.0F, 0.0F, 10.0F, 10.0F)
pdfw = PdfWriter.GetInstance(documentoPDF, New FileStream(urlFija & "\" & "Manifiesto-" & Manifiesto & ".pdf", FileMode.Create))
documentoPDF.Open()
documentoPDF.NewPage()
Dim aTable = New iTextSharp.text.pdf.PdfPTable(3)
Dim Ancho0 As Single() = {0.75F, 1.45F, 0.75F}
'aTable.DefaultCell.Border = BorderStyle.None
Dim Imagen As iTextSharp.text.Image
Imagen = iTextSharp.text.Image.GetInstance(path & "Ministerio-3.jpg")
Imagen.ScalePercent(25)
Imagen.SetAbsolutePosition(25.0F, 25.0F)
Dim Img = New PdfPCell
Img.Border = Rectangle.NO_BORDER
Img.AddElement(Imagen)
aTable.AddCell(Img)
Dim C1 = New PdfPCell(New Paragraph("Formato", FontFactory.GetFont(FontFactory.TIMES, 13, iTextSharp.text.Font.BOLD)))
C1.HorizontalAlignment = 1
C1.VerticalAlignment = 2
C1.Border = Rectangle.NO_BORDER
aTable.AddCell(C1)
Dim C2 = New PdfPCell(New Paragraph("Prueba", FontFactory.GetFont(FontFactory.TIMES, 7, iTextSharp.text.Font.NORMAL)))
C2.HorizontalAlignment = 3
C2.Border = Rectangle.NO_BORDER
aTable.AddCell(C2)
aTable.SetWidths(Ancho0)
documentoPDF.Add(aTable)
documentoPDF.AddAuthor(Session("IDUsuario").ToString)
documentoPDF.AddTitle("Manifiesto")
documentoPDF.AddCreationDate()
documentoPDF.Close()
After this I added a table with the information, move me just the top margin
As documented, the width of a PdfPTable takes only 80% of the available width by default when you add it to a page (unless you define an absolute width instead of a relative width). It will be centered, so you will have a left and a right margin of 10% of the available width.
If you want the table to span 100%, you need to add this line:
aTable.WidthPercentage = 100;
Now the table will span the full width.

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: how do i position a table?

I have created a simple table and i need to position. does anyone have experience with tables in itextsharp?
here's my code
Private Sub generate_PDF()
Directory.SetCurrentDirectory("C:\Users\alexluvsdanielle\Desktop\")
Console.WriteLine("Chapter 6 example 1: Adding a Wmf, Gif, Jpeg and Png-file using urls")
Dim document As Document = New Document
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream("Chap1002.pdf", FileMode.Create))
document.Open()
'Dim wmf As Image = Image.GetInstance("harbour.wmf")
'Dim gif As Image = Image.GetInstance("vonnegut.gif")
Dim jpeg As Image = Image.GetInstance("C:\Users\alexluvsdanielle\Desktop\test.jpg")
'Dim png As Image = Image.GetInstance("hitchcock.png")
'document.Add(wmf)
'document.Add(gif)
jpeg.ScalePercent(50)
'jpeg.Alignment = Image.TOP_BORDER
jpeg.SetAbsolutePosition(0, 562)
document.Add(jpeg)
'document.Add(png)
Dim cb As PdfContentByte = writer.DirectContent
cb.BeginText()
Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
cb.SetFontAndSize(bf, 12)
'Dim text As String = "Sample text for alignment"
'cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, 700, 0)
'cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, 650, 0)
'cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, 600, 0)
cb.SetTextMatrix(150, 652)
cb.ShowText(patient_name)
cb.SetTextMatrix(150, 637)
cb.ShowText(doc_name)
cb.SetFontAndSize(bf, 8)
cb.SetTextMatrix(150, 620)
cb.ShowText(lot__no)
cb.SetTextMatrix(150, 611)
cb.ShowText(patient_id)
Dim i As Integer
For i = 1 To 10
cb.SetTextMatrix(150, 600 - (i * 10))
cb.ShowText(DataGridView1.Item(3, i).Value)
Next
cb.EndText()
Dim aTable As Table = New Table(2, 2)
aTable.Offset = 10
aTable.Width = 100
aTable.AddCell("0.0")
aTable.AddCell("0.1")
aTable.AddCell("1.0")
aTable.AddCell("1.1")
document.Add(aTable)
Dim datatable As PdfPTable = New PdfPTable(12)
Dim page As Rectangle = document.PageSize
datatable.TotalWidth = 100
datatable.AddCell("hello")
datatable.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin, writer.DirectContent)
document.Add(datatable)
Catch de As DocumentException
Console.Error.WriteLine(de.Message)
MessageBox.Show(de.Message)
Catch ioe As IOException
Console.Error.WriteLine(ioe.Message)
MessageBox.Show(ioe.Message)
Catch e As Exception
Console.Error.WriteLine(e.Message)
MessageBox.Show(e.Message)
End Try
document.Close()
End Sub
the first table works but the second does not
You can do something like this:
PdfPTable foot = new PdfPTable(2);
foot.TotalWidth = page.Width - document.LeftMargin - document.RightMargin;
foot.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin,
writer.DirectContent);
Make sure your code is closing the document and initializing the PdfWriter.
Example of what I use (output path is a variable passed into the function in C#):
Document document = new Document();
var writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
document.Open();
//write stuff here
document.Close();