首页 > 解决方案 > 如何使用 iText 7 为我的 PDF 添加背景颜色?

问题描述

我只是想为我用这个库生成的 PDF 的背景添加颜色。

我希望我的页面有颜色作为背景,甚至是图片。文档让我头晕目眩。没有有用或有意义的描述;它几乎不能称为文档。

为什么这个简单的任务很难用这个库来完成?我是否必须费尽心思阅读整本书,才能了解如何使用图书馆?

标签: javapdfbackgroundbackground-coloritext7

解决方案


在线或他们的“示例”中没有直接的答案,但我设法找到了一个类似的问题,即在此处的 PDF 文件中有各种页面背景颜色。

更新:似乎 iText-7 电子书/资源在过去 3 年中已更新。以下链接自 21/07/2021 起有效。

  • 此处为 ITEXT-7 构建模块的新电子书 URL
  • 这里有各种代码示例
  • 所有资源索引在这里

在我看来,解决方案过于复杂。这只是背景颜色,这是一项可以大大减少理解时间的任务。使框架尽可能模块化和灵活是可以理解的,但有时人们只想快速完成一些琐碎的任务。

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

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

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


推荐阅读