编译将html转换为pdf的PDFRender类我得到了“文件过早结束”:
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.*;
import org.xhtmlrenderer.resource.*;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.*;
public class PDFRender
{
public static void main(String[] args) throws IOException, DocumentException
{
createPDF("/home/user/test.pdf", Renderer.class.getResource("/resource/print/test.html").getPath());
}
public static void createPDF(String url, String pdf)
throws IOException, DocumentException
{
OutputStream os = null;
try
{
os = new FileOutputStream(pdf);
ITextRenderer renderer = new ITextRenderer();
ResourceLoaderUserAgent callback = new ResourceLoaderUserAgent(renderer.getOutputDevice());
callback.setSharedContext(renderer.getSharedContext());
renderer.getSharedContext().setUserAgentCallback(callback);
Document doc = XMLResource.load(new InputSource(url)).getDocument();
renderer.setDocument(doc, url);
renderer.layout();
renderer.createPDF(os);
os.close();
os = null;
}
catch(Exception e)
{}
}
private static class ResourceLoaderUserAgent extends ITextUserAgent
{
public ResourceLoaderUserAgent(ITextOutputDevice outputDevice)
{
super(outputDevice);
}
protected InputStream resolveAndOpenStream(String uri)
{
InputStream is = super.resolveAndOpenStream(uri);
return is;
}
}
}
我想使用此片段将setNamespaceAware用于false,但我的代码不使用DocumentBuilderFactory
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(false);
我该怎么做?