Java itext:修改 PDF 并设置背景颜色:#2E506F

问题描述 投票:0回答:1

我已经创建了这个类,但是打开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!");
    }
}
java spring-boot pdf itext pdf-generation
1个回答
0
投票

我认为你写完后需要关闭文档。 添加这个 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!");
}

}

© www.soinside.com 2019 - 2024. All rights reserved.