How to add a border to a PDF page?

Tags: page borderrectangleiText 7

This is a snippet of my source code:

Rectangle rect= new Rectangle(36,108);
Why am I not able to add border to my PDF page even after enabling borders for all sides? I've set border and its color too still I'm not able to add border.

Posted on StackOverflow on Jul 11, 2014 by user3819936

In iText 7 you will need a few lines of simple code to draw a border of a page:

public void createPdf(String dest) throws IOException {
    // Create a PdfDocument
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    // Create a page
    // Get the dimensions of the page
    float width = pdfDoc.getDefaultPageSize().getWidth();
    float height = pdfDoc.getDefaultPageSize().getHeight();
    // Define a PdfCanvas instance
    PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
    // Add a rectangle
    canvas.rectangle(20, 20, width - 40, height - 40);
    // Close PdfDocument

Moreover PdfDocument has a getPage(int page) method, so you can get any page you want. Whether you are looking for drawing a border for every page, see the PageBorder example, where we implement the IEventHandler interface and add it to the pdfDoc on the start page event:

pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, new PageBorderEventHandler());

Click this link if you want to see how to answer this question in iText 5.