Search code examples
javapdfbackgroundbackground-coloritext7

How can I add a background color to my PDF using iText 7?


I simply want to add color to the background of the PDF that I'm generating with this library.

I want my pages to have color as the background or even a picture. The documentation got me dizzy. There are no useful or meaningful descriptions; it can hardly be called documentation.

Why is this simple task so hard to achieve with this library? Do I have to go through the trouble of reading a whole book, just to understand how to use a library?


Solution

  • There is no straightforward answer online, or in their "examples", but I managed to find a similar question about having various page background-colors in the PDF file here.

    UPDATE: It seems that the iText-7 eBooks/resources have been updated during the past 3 years. The following links are working as of 21/07/2021.

    • NEW EBOOK URL FOR ITEXT-7 BUILDING BLOCKS HERE
    • VARIOUS CODE EXAMPLES HERE
    • ALL RESOURCES INDEX HERE

    The solution is overly complex, in my opinion. This is just background color and it is a task that could have been made considerably less time consuming to understand. Making a framework as modular and flexible as possible is understandable, but sometimes there are some trivial tasks that people just want to get done quickly.

    Anyway, here is the solution for anyone who might have the same problem as I did:

    //Class that creates the PDF
    public class PdfCreator {
    
    //Helper class so we can add colour to our pages when we call it from outer class
    private static class PageBackgroundsEvent implements IEventHandler {
        @Override
        public void handleEvent(Event event) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
            PdfPage page = docEvent.getPage();
    
            PdfCanvas canvas = new PdfCanvas(page);
            Rectangle rect = page.getPageSize();
            //I used custom rgb for Color
            Color bgColour = new DeviceRgb(255, 204, 204);
            canvas  .saveState()
                    .setFillColor(bgColour)
                    .rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight())
                    .fillStroke()
                    .restoreState();
            }
        }
        
        //PATH_OF_FILE is the path that the PDF will be created at.
        String filename = PATH_OF_FILE + "/myFile.pdf";
        OutputStream outputStream = new FileOutputStream(new File(filename));
        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdfDoc = new PdfDocument(writer);
        pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, new PageBackgroundsEvent());
        PageSize pageSize = pdfDoc.getDefaultPageSize();
        Document document = new Document(pdfDoc, pageSize);
        document.close();
    }
    

    Background images can be added the same way! See this link