2012-07-24 64 views
7

在我的生產流水線中,我需要從HTML生成幾百PDF。對於這種情況,我首先將HTML轉換爲XHTML。 比im將'已清理'的XHTML和uri傳遞給渲染器。XHTML爲PDF使用飛碟如何緩存css

由於* .css和imageFiles對於所有XHTML文件都是相同的,所以我不需要在處理文件的時候解決它們。 Im成功使用以下代碼來緩存圖像。我怎樣才能緩存.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; 
    } 
} 

回答

3

因爲有人面對同樣的問題,所以我解決了這個問題。 因爲我無法緩存CustomUserAgent中的* .css文件,所以我不得不尋找另一種方法。我的解決方案使用Squid作爲http代理來緩存所有經常使用的資源。

在我的CustomUserAgent裏面我只需要通過傳遞代理對象來訪問這個代理。

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 

,你可以看到,高速緩存和非高速緩存的資源之間的型動物是顯著