我正在使用iText
将HTML转换为PDF格式。
在我的CSS中,我有:
background: linear-gradient(to bottom, #fff 0%, #e6e6e6 100%);
有了这个,它就抛出了异常:
IllegalPdfSyntaxException: Unbalanced save/restore state operators
(exception at document.close();)
这是我写的代码:
Document document = null;
try{
FileOutputStream fileOuputStream = new FileOutputStream("D:\\DEV\\testpdf.html");
fileOuputStream.write(str.getBytes());
String CSS = "D:\\DEV\\all.css";
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream(CSS));
cssResolver.addCss(cssFile);
FileInputStream fileInputStream = new FileInputStream("D:\\DEV\\testpdf.html");
// step 1
document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
// step 3
document.open();
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(fileInputStream);
// step 4
// XMLWorkerHelper.getInstance().parseXHtml(writer, document, fileInputStream);
//step 5
fileInputStream.close();
fileOuputStream.close();
System.out.println( "PDF Created!" );
}catch(IOException e){
e.printStackTrace();
return false;
}
document.close();
如果我从CSS中删除它:
background: linear-gradient(to bottom, #fff 0%, #e6e6e6 100%);
然后,我能够生成超出异常的PDF。
iText版本:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.4.1</version>
</dependency>