Search code examples
c#winformspdfitextborder

How do I add a border to a page using iTextSharp?


Is it possible to add a border to a page in a PDF document using iTextSharp? I'm generating the PDF file from scratch, so I don't need to add borders to an already existing document.

Here's my code for example:

Document pdfDocument = new Document(PageSize.LETTER);
Font headerFont = new Font(baseFont, 13);
Font font = new Font(baseFont, 10);
PdfWriter writer = PdfWriter.GetInstance(pdfDocument, 
                                         new FileStream(fileName, FileMode.Create));
pdfDocument.Open();

//I add IElements here.

pdfDocument.Close();

Solution

  • Here is an answer (adapted from Mark Storer) in C#. This example uses the margins of the page to draw the border, which I sometimes find useful for debugging the page layout.

    public override void OnEndPage(PdfWriter writer, Document document)
    {
        base.OnEndPage(writer, document);
    
        var content = writer.DirectContent;
        var pageBorderRect = new Rectangle(document.PageSize);
    
        pageBorderRect.Left += document.LeftMargin;
        pageBorderRect.Right -= document.RightMargin;
        pageBorderRect.Top -= document.TopMargin;
        pageBorderRect.Bottom += document.BottomMargin;
    
        content.SetColorStroke(BaseColor.RED);
        content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
        content.Stroke();
    }