ITextSharp Margin - vb.net

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.

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

How to introduce new line characters with iTextSharp

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).

Using itext to get height and width?

I have tried but couldn't get proper output.Code has been placed below.
Dim Height, Width As Double
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim doc As New iTextSharp.text.Document()
reader = New iTextSharp.text.pdf.PdfReader(FILENAME)
iTextSharp.text.pdf.PdfWriter.GetInstance(doc, New FileStream(FILENAME,FileMode.Open))
doc.Open()
Height = doc.PageSize.Height
Width = doc.PageSize.Width
Height = Math.Round(Height)
Width = Math.Round(Width)
doc.Close()

Getting OutOfRange exception when trying to insert values from datagridview into PDFtable

I have a datagridview that I'm trying to export in pdf format. I downloaded and implemented a datagridviewtopdf class, but I needed to modify it to dynamically create the necessary columns (the column count will range from 1-12 for months in a year). I also needed to include an extra column to put the row header text for each row in my datagridview. I have the code, which I will include below. I keep getting an OutOfRange exception at the line that I've starred. Any idea how to fix this and create the pdf to resemble my datagridview table?
Edited to also include screenshots of datagridview. Datagridview will have up to 65 rows and up to 12 columns (not including rowheaders or columnheaders
Private Function GetDataTable() As System.Data.DataTable
Dim dataTable As New Data.DataTable("MyDataTable")
'Create another DataColumn Name
For column As Integer = 1 To DataGridView1.ColumnCount - 1
Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(column).HeaderText.ToString(), GetType(String))
dataTable.Columns.Add(dataColumn_1)
'Now Add some row to newly created dataTable
Dim dataRow As DataRow
For i As Integer = 0 To DataGridView1.Rows.Count - 1
dataRow = dataTable.NewRow()
' Important you have create New row
dataRow(DataGridView1.Columns(column).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(column).Value.ToString()
dataTable.Rows.Add(dataRow)
Next i
Next column
dataTable.AcceptChanges()
Return dataTable
End Function
Private Sub ExportDataToPDFTable()
Dim paragraph As New Paragraph
Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
doc.Open()
Dim font12BoldRed As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.UNDERLINE Or iTextSharp.text.Font.BOLDITALIC, BaseColor.RED)
Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
Dim p1 As New Phrase
p1 = New Phrase(New Chunk("PDF From Datagridview Data", font12BoldRed))
doc.Add(p1)
'Create instance of the pdf table and set the number of column in that table
Dim PdfTable As New PdfPTable(DataGridView1.ColumnCount + 1)
PdfTable.TotalWidth = 490.0F
'fix the absolute width of the table
PdfTable.LockedWidth = True
'relative col widths in proportions - 1,4,1,1 and 1
'Dim widths As Single() = New Single() {1.0F, 1.0F, 1.0F, 1.0F, 1.0F}
' PdfTable.SetWidths(widths)
PdfTable.HorizontalAlignment = 1 ' 0 --> Left, 1 --> Center, 2 --> Right
PdfTable.SpacingBefore = 2.0F
'pdfCell Decleration
Dim PdfPCell As PdfPCell = Nothing
'Assigning values to each cell as phrases
For column As Integer = 0 To (DataGridView1.ColumnCount - 1)
If column = 0 Then
For row As Integer = 0 To (DataGridView1.RowCount - 1)
'Getting out of range exception below for row
PdfPCell = New PdfPCell(New Phrase(New Chunk(DataGridView1.Rows(row).HeaderCell.ToString, font12Bold)))
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
Next row
Else
PdfPCell = New PdfPCell(New Phrase(New Chunk(DataGridView1.Columns(column).HeaderText, font12Bold)))
'Alignment of phrase in the pdfcell
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
End If
Next column
Dim dt = GetDataTable()
If dt IsNot Nothing Then
'Now add the data from datatable to pdf table
For rows As Integer = 0 To dt.Rows.Count - 1
For column As Integer = 0 To dt.Columns.Count - 1
PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
If column = 0 Or column = 1 Then
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT
Else
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT
End If
PdfTable.AddCell(PdfPCell)
Next
Next
'Adding pdftable to the pdfdocument
doc.Add(PdfTable)
End If
doc.Close()
End Sub
Change:
For column As Integer = 1 To DataGridView1.ColumnCount + 1
For row As Integer = 1 To DataGridView1.RowCount
To:
For column As Integer = 0 To (DataGridView1.ColumnCount - 1)
For row As Integer = 0 To (DataGridView1.RowCount -1)
Remember: It's zero-base indexing.
Example:
Dim dtColumn As DataColumn
Dim dtRow As DataRow
For column As Integer = 0 To (Me.DataGridView1.ColumnCount - 1)
dtColumn = dt.Columns.Item(Me.DataGridView1.Columns(column).DataPropertyName)
For row As Integer = 0 To (DataGridView1.RowCount - 1)
dtRow = DirectCast(Me.DataGridView1.Rows(row).DataBoundItem, DataRowView).Row
'Replace this:
'PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
'With this:
PdfPCell = New PdfPCell(New Phrase(row.Item(column).ToString(), font12Normal))
Next
Next

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();