这不是一个重复的问题。在发布这个问题之前,我已经搜索并尝试了很多选项。
我们有一个网页,用户应该能够在文本框、文本区域、图像以及富文本编辑器中输入数据。这些数据必须填写在现有的报告中,就像填空一样。
当用户输入是简单文本时,我能够使用 Apache FOP 实现该功能。但是如果用户输入是富文本(html 格式),Apache FOP 将不起作用。 FOP 不会渲染 html,它只是将 html 代码(例如: <strong> XYZ /strong>
)推送到 pdf 中。
我尝试使用 iText,但这里的挫折是,即使 iText 支持将 html 渲染为 pdf,它也无法放置 <img>
中包含的图像。标签,在 pdf 文件中。
我可以尝试使用 iText api 逐 block 创建 pdf,但问题是用户输入的富文本数据无法嵌入代码之间,因为逐 block 构建 pdf 和 html 到 pdf 不能一起完成在 iText 中。或者至少根据我的经验我是这么认为的。
是否有其他方法可以从 java 创建包含图像、富文本呈现、页眉和页脚的 pdf 文件?
最佳答案
iText 提供将 HTML 数据转换为 Pdf 的功能。下面是执行此操作的代码片段:
Lets assume the html data is available as Input Stream (If its a String then we can convert it to InputStream using Apache Commons - IOUtils)
InputStream htmlData; // Html Data that needs to converted to Pdf
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
document.open();
// convert the HTML with the built-in convenience method
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, htmlData);
document.close();
// outputStream now has the required pdf data
关于java - 用 Java 创建动态 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23135708/