How to add a border to a PDF page?

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.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now