What's the easiest way of converting an xhtml string to PDF using Flying Saucer?

爱⌒轻易说出口 提交于 2019-12-04 05:20:43

The following works:

Document document = XMLResource.load(new ByteArrayInputStream(templateString.getBytes())).getDocument();

Previously, I had tried

final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);

final DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
Document document = documentBuilder.parse(new ByteArrayInputStream(templateString.getBytes()));

but that fails as it attempts to download the HTML docType from http://www.w3.org (which returns 503's for the java libs).

I use the following without problem:

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setValidating(false);
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    builder.setEntityResolver(FSEntityResolver.instance());
    org.w3c.dom.Document document = builder.parse(new ByteArrayInputStream(doc.toString().getBytes()));

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(document, null);
    renderer.layout();
    renderer.createPDF(os);

The key differences here are passing in a null URI, and also provided the DocumentBuilder with an entity resolver.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!