我正在使用iText将 HTML 转换为 PDF 文件。我意识到输出文件大小太大,因此我决定使用它PdfSmartCopy来删除对象重复项。PdfSmartCopy我可以在 HTML 到 PDF 过程完成后使用,例如,我用来PdfSmartCopy从磁盘加载文件并将 PDF 转换为较小的尺寸。
我的问题是,我可以简化PdfSmartCopyHTML 到 PDF 的流程吗?我发现这PdfSmartCopy是 的子类PdfWriter。所以我将代码更改为:
public static void main(String[] args) throws Exception {
try (OutputStream file = new FileOutputStream(new File("output.pdf"))) {
Document document = new Document(PageSize.A4);
//PdfWriter writer = PdfWriter.getInstance(document, file); // remove this line
PdfSmartCopy pdfCopy = new PdfSmartCopy(document, file); // change to this line
pdfCopy.setInitialLeading(12.5f);
document.open();
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream("itext2\\css\\bootstrap.min.css"));
cssResolver.addCss(cssFile);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
PdfWriterPipeline pdf = new PdfWriterPipeline(document, pdfCopy);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
String fileContent = PdfTest.readFile("itext2\\template.html");
p.parse(new StringReader(fileContent));
document.close();
pdfCopy.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
PdfSmartCopy是否可以在进行 HTML 到 PDF 渲染的同时使用?
https://api.itextpdf.com/iText5/5.5.9/com/itextpdf/text/pdf/PdfSmartCopy.html#PdfSmartCopy-com.itextpdf.text.Document-java.io.OutputStream-
qq_遁去的一_1
相关分类