Search code examples
c#pdfalignmentitext

iTextSharp aligning PDFP table with paragraph within margins of a document


I'm generating a PDF document like this:

  string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            Document doc = new Document(iTextSharp.text.PageSize.A4,50,50,120,40);


            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path+"\\Invoices\\Test.pdf", FileMode.Create));
            PdfPTable table = new PdfPTable(2);
            table.WidthPercentage = 100;
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
            table.AddCell(new PdfPCell() { HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Text to the left"), BorderColor = BaseColor.WHITE, BorderWidth = 0 });
            table.AddCell(new PdfPCell() { HorizontalAlignment = PdfPCell.ALIGN_RIGHT, Phrase = new Phrase("Text to the right"), BorderColor = BaseColor.WHITE, BorderWidth = 0 });

            //   table.AddCell(new PdfPCell("Text to the left", PdfPCell.ALIGN_LEFT));
            //  table.AddCell(new PdfPCell("Text to the left", PdfPCell.ALIGN_RIGHT));
            document.add(table);

            doc.Open();
            Paragraph p = new Paragraph("This is a first text above \n \n", FontFactory.GetFont("Arial", 8.0f, BaseColor.BLACK));
            doc.Add(p);
            doc.Add(table);
            doc.Close();

Which produces a document like this:

enter image description here

Do you guys notice that the text inside the paragrap and the table are not aligned perfectly to the left?

How could I fix this with or without adding the first text into the table itself (both options are fine for me)

Can someone help me out?


Solution

  • Set the cells padding to zero to remove that tiny space on the left, like:

    new PdfPCell { PaddingLeft = 0 }
    

    Btw you can remove this BorderColor and BorderWidth and DefaultCell stuff. Just set:

    Border = Rectangle.NO_BORDER
    

    on the cell properties to remove the border.