java - 如何使用 iText 7 为我的 PDF 添加背景颜色?
问题描述
我只是想为我用这个库生成的 PDF 的背景添加颜色。
我希望我的页面有颜色作为背景,甚至是图片。文档让我头晕目眩。没有有用或有意义的描述;它几乎不能称为文档。
为什么这个简单的任务很难用这个库来完成?我是否必须费尽心思阅读整本书,才能了解如何使用图书馆?
解决方案
在线或他们的“示例”中没有直接的答案,但我设法找到了一个类似的问题,即在此处的 PDF 文件中有各种页面背景颜色。
更新:似乎 iText-7 电子书/资源在过去 3 年中已更新。以下链接自 21/07/2021 起有效。
在我看来,解决方案过于复杂。这只是背景颜色,这是一项可以大大减少理解时间的任务。使框架尽可能模块化和灵活是可以理解的,但有时人们只想快速完成一些琐碎的任务。
无论如何,对于可能遇到与我相同问题的任何人,这里都是解决方案:
//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();
}
背景图像可以以相同的方式添加!看到这个链接
推荐阅读
- ruby-on-rails - Why is passenger with Nginx looking for passenger_wsgi.py in my rails app
- javascript - ReactJS - ref returns "undefined"
- angular6 - JHipster 和 Angular ng-select 组件
- c# - 如何从服务器检查协商的 TLS 握手?
- python - 在门户网站上尝试用户名和密码
- java - 我正在尝试为我的字符串创建一个回文,但我的 equals 方法()不起作用,
- javascript - Javascript对获取的数据进行排序
- sql - SQL 反透视函数
- javascript - 将秒表时间转换为秒
- react-native - React-Native 未构建应用程序,显示未找到模块错误