代码之家  ›  专栏  ›  技术社区  ›  Soutzikevich

如何使用IText7向PDF添加背景色?

  •  0
  • Soutzikevich  · 技术社区  · 6 年前

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

    我希望我的页面有颜色作为背景,甚至是图片。文件让我头晕。

    为什么用这个图书馆很难做到?我必须读A吗 book 只是为了了解如何使用图书馆?我宁愿买本书来学习一种新的编程语言。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Soutzikevich    6 年前

    在网上或在他们的“示例”中没有直接的答案,但是我设法找到了一个类似的问题,关于在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