Search code examples
javaspring-bootpdfitextpdf-generation

Java itext: modify a PDF and set this background color: #2E506F


I have created this class , but I have an error when opening the pdf

public class ModifyPDFWithBackgroundColor {

    public static void main(String[] args) throws IOException {

        String inputPdfFilePath = "/Users/nunyet/IdeaProjects/mystic-river-api/docs/style-guide/LogoFiles/ForPrint/pdf/color-logo-with-background.pdf";
        String outputPdfFilePath =  "/Users/nunyet/IdeaProjects/mystic-river-api/docs/style-guide/LogoFiles/ForPrint/pdf/color-logo-with-background2.pdf";
        DeviceRgb backgroundColor = new DeviceRgb(46, 80, 111);  // Convert HEX to RGB

        PdfDocument pdfDoc = new PdfDocument(new PdfReader(inputPdfFilePath), new PdfWriter(outputPdfFilePath));

        // Access the first page of the PDF document
        PdfPage page = pdfDoc.getFirstPage();

        // Create a PdfCanvas for the page
        PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);

        // Set the background color
        canvas.saveState();
        canvas.setFillColor(backgroundColor);
        canvas.rectangle(0, 0, page.getPageSize().getWidth(), page.getPageSize().getHeight());
        canvas.fill();
        canvas.restoreState();



        System.out.println("PDF modified successfully!");
    }
}

enter image description here


Solution

  • I think you need to close the document, when you finish writing. add this pdfDoc.close();

    public class ModifyPDFWithBackgroundColor {
    
    public static void main(String[] args) throws IOException {
    
        String inputPdfFilePath = "/Users/nunyet/IdeaProjects/mystic-river-api/docs/style-guide/LogoFiles/ForPrint/pdf/color-logo-with-background.pdf";
        String outputPdfFilePath =  "/Users/nunyet/IdeaProjects/mystic-river-api/docs/style-guide/LogoFiles/ForPrint/pdf/color-logo-with-background2.pdf";
        DeviceRgb backgroundColor = new DeviceRgb(46, 80, 111);  // Convert HEX to RGB
    
        // Open the input PDF document
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(inputPdfFilePath), new PdfWriter(outputPdfFilePath));
    
        // Access the first page of the PDF document
        PdfPage page = pdfDoc.getFirstPage();
    
        // Create a new page with the same dimensions as the original page
        PdfPage newPage = pdfDoc.addNewPage(page.getPageSize());
    
        // Create a PdfCanvas for the new page
        PdfCanvas canvas = new PdfCanvas(newPage);
    
        // Set the background color
        canvas.saveState();
        canvas.setFillColor(backgroundColor);
        canvas.rectangle(0, 0, newPage.getPageSize().getWidth(), newPage.getPageSize().getHeight());
        canvas.fill();
        canvas.restoreState();
    
        // Close the PDF document
        pdfDoc.close();
    
        System.out.println("PDF modified successfully!");
    }
    

    }