如何使用iText 7在PDF中添加背景色?

时间:2018-07-27 10:01:56

标签: java pdf pdf-generation background-color itext7

我只是想在此库生成的PDF背景中添加颜色。

我希望我的页面以彩色为背景甚至是图片。文档使我头晕目眩。

为什么使用此库很难实现?我是否必须阅读book只是为了了解如何使用库?我宁愿买一本书来学习一种新的编程语言。

1 个答案:

答案 0 :(得分:1)

在线上或在其“示例”中都没有简单的答案,但是我设法找到了一个类似的问题,关于在PDF文件here中使用各种页面背景颜色。

我认为

解决方案非常复杂。这只是背景色。

无论如何,这是针对可能遇到与我相同问题的任何人的解决方案:

//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();
}

可以以相同的方式添加背景图像!看到这个link