在我的生产管道中,我需要从 HTML 生成数百个 PDF。对于这种情况,我首先将 HTML 转换为 XHTML。比我将“清理”的 XHTML 和 uri 传递给渲染器。
由于 *.css 和 imageFiles 对于所有 XHTML 文件都是相等的,因此我不需要在处理文件时一直解析它们。我成功使用以下代码缓存图像。我怎样才能缓存 .css 文件呢?我想避免将所有文件放入我的类路径中。
ITextRenderer renderer = new ITextRenderer();
ResourceLoaderUserAgent callback = new ResourceLoaderUserAgent(renderer.getOutputDevice());
callback.setSharedContext(renderer.getSharedContext());
for (MyObject myObject : myObjectList) {
OutputStream os = new FileOutputStream(tempFile);
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(myObject.getLocalPath); // full path to .xhtml
renderer.getSharedContext().setUserAgentCallback(callback);
renderer.setDocument(document, myObject.getUri());
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close();
}
...
private static class ResourceLoaderUserAgent extends ITextUserAgent
{
public ResourceLoaderUserAgent(ITextOutputDevice outputDevice) {
super(outputDevice);
}
protected InputStream resolveAndOpenStream(String uri) {
InputStream is = super.resolveAndOpenStream(uri);
System.out.println("IN resolveAndOpenStream() " + uri);
return is;
}
}