在我的生产管道中,我需要从
HTML生成几百个PDF.对于这种情况,我首先将HTML转换为XHTML.
比我将’已清理’的XHTML和uri传递给渲染器.
比我将’已清理’的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; } }
解决方法
在这里遇到同样问题的人是我如何解决它.
由于我无法在我的CustomUserAgent中缓存* .css文件,我必须找到另一种方法.我的解决方案使用 Squid作为http-proxy来缓存所有常用资源.
由于我无法在我的CustomUserAgent中缓存* .css文件,我必须找到另一种方法.我的解决方案使用 Squid作为http-proxy来缓存所有常用资源.
在我的CustomUserAgent中,我只需要通过传递proxy-object来访问此代理.
public class ResourceLoaderUserAgent extends ITextUserAgent { public ResourceLoaderUserAgent(ITextOutputDevice outputDevice) { super(outputDevice); } protected InputStream resolveAndOpenStream(String uri) { HttpURLConnection connection = null; URL proxyUrl = null; try { Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("localhost",3128)); proxyUrl = new URL(uri); connection = (HttpURLConnection) proxyUrl.openConnection(proxy); connection.connect(); } catch (Exception e) { throw new RuntimeException(e); } java.io.InputStream is = null; try { is = connection.getInputStream(); } catch (java.net.MalformedURLException e) { XRLog.exception("bad URL given: " + uri,e); } catch (java.io.FileNotFoundException e) { XRLog.exception("item at URI " + uri + " not found"); } catch (java.io.IOException e) { XRLog.exception("IO problem for " + uri,e); } return is; } }
缓存:
resolving css took 74 ms resolving images took 225 ms
未缓存:
resolving css took 15466 ms resolving images took 11236 ms
如您所见,缓存和未缓存资源之间的差异很大
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。