java - 使用 iText 外部 CSS 将 HTML 转换为 PDF

标签 java pdf-generation itext flying-saucer

我正在使用 Flying Saucer 将一些 PDF 文档从字符串渲染为 HTML。

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStream is = new ByteArrayInputStream(html.getBytes("UTF-8"));
Document doc = builder.parse(is);

response.setContentType("application/pdf; charset=UTF-8");
response.setHeader("Content-disposition", "inline; filename=\"" + outFileName + "\"");

OutputStream os = response.getOutputStream();

ITextRenderer iTextRenderer = new ITextRenderer();
iTextRenderer.setDocument(doc,null);
iTextRenderer.layout();
iTextRenderer.createPDF(os);
os.flush();
os.close();

当我有纯文本时,这很好用。 我在 HTML 内容中引用了外部 CSS。但是,当 PDF 生成时,CSS 不会被应用。

我读到 setDocument() 方法采用两个参数:文档和 url。 url 参数指示用于添加到 xhtml 中出现的相对路径的基本 url,例如外部 CSS

所以,我尝试提供

context path/css

baseURL 中的 direcotry 并在 setDocument() 中使用它。仍然没有结果

那么,我的问题作为 baseURL 传递的正确 URL 是什么?

String baseURL = ""; // What goes here as root URL for resources
iTextRenderer.setDocument(doc,baseURL);

最佳答案

FAQ告诉我们:

The url is the "base", which for a normal URL would be the parent location—the parent directory, or the location where the document you are rendering is located.If your document has absolute URIs for CSS and images, or it has no external references at all, then the base url can be null.If your document has any relative URIs for CSS or images, then the base URL should not be null, but rather should point to the directory or address where the current document is located.

您是否测试了文档的路径而不是 CSS 的路径?然而,我在链接 CSS 时也遇到了一些麻烦,所以我插入了 URI(到目前为止没有问题:-))。如果您使用我上面发布的链接,它有效吗?

抱歉,新帖子,但评论告诉我我只剩下负字符了......

关于java - 使用 iText 外部 CSS 将 HTML 转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043035/

相关文章:

java - 如何获取jsp中复选框的值?

node.js - 如何在 NightmareJs 中禁用显示打印机提示

Java欧元符号转换为货币符号

java - PDF人群 'Missing artifact'

zend-framework - 如何在 zend PDF 中绘制TextBlock

java - 如何在PDF中查找单词的页码和字体大小?

c++ - pdf文件中的AES 256位加密

java - 找不到文件 mysql-connector-java-5.1.13-bin.jar

java - 从 Java 调用 WMIC.EXE(挂起)

java - 将一个调用 java 程序的响应传递给另一个