0

I am designing a table in pdf using itextsharp. I want to ask if anyone knows:

  1. How to give border (like color = silver, 1px, fit to width) to header text?
  2. How to make table fit to page width (like 100%)?

I am using vb.net

Protected Sub Create_Pdf_Click(sender As Object, e As EventArgs) Handles Create_Pdf.Click
    Dim pdfDoc As New Document()
    Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("D://PDF/myfile.pdf", FileMode.Create))
    pdfDoc.Open()
    pdfDoc.Add(New Paragraph("Here is header text"))
    Dim table As New PdfPTable(3)
    Dim cell As New PdfPCell(New Phrase("Header spanning 3 columns"))
    cell.Colspan = 3
    cell.HorizontalAlignment = 1

    table.AddCell(cell)
    table.AddCell("Col 1 Row 1")
    table.AddCell("Col 2 Row 1")
    table.AddCell("Col 3 Row 1")
    table.AddCell("Col 1 Row 2")
    table.AddCell("Col 2 Row 2")
    table.AddCell("Col 3 Row 2")
    pdfDoc.Add(table)
    pdfDoc.Close()
End Sub
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Elyor
  • 5,396
  • 8
  • 48
  • 76

1 Answers1

0

When you define a Document like this:

Dim pdfDoc As New Document()

You define a document with pages of size A4 and margins of 36 user units. If you don't want any margins, you need to create your document like this:

Document doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);

When you create your PdfPTable like this:

Dim table As New PdfPTable(3)

You create a table that takes 80% of the available width. You can change this to 100% by adding this line:

table.WidthPercentage = 100

Or, if you want to specify a specific width, then you can use:

table.TotalWidth = 595f
table.LockedWidth = true

Note that 595 is the width (in user units) of an A4 page.

Borders are defined at the level of a PdfPCell:

PdfPCell cell = new PdfPCell(phrase)
cell.BorderColor = BaseColor.RED
cell.BorderWidth = 3f
cell.Border = Rectangle.BOX

Of course, you can also define each border separately. That is explained here: ITextSharp: Set table cell border color

In your case, you may want to define these properties for the DefaultCell. This way, you don't have to define them over and over again for each separate cell.

It would lead us too far if I would go into more detail (e.g. I could also talk about table events and cell events, for instance to draw dashed borders). Please download the free ebook The Best iText Questions on StackOverflow where you will find the answers to some questions that are even less trivial than yours.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165