【问题标题】:error while convert html to pdf in itext7在itext7中将html转换为pdf时出错
【发布时间】:2017-07-11 20:12:54
【问题描述】:

要将我的 html 转换为 pdf,我使用 itext7 的 API convertToDocument,将参数传递给模板的 ByteArrayInputStream、PDFDocument 和 convertProperties。

相关代码sn-p:

HtmlConverter.convertToDocument(new ByteArrayInputStream(templateWritten), pdfDocument, converterProps);

正如文档所说,如果我设置了 convertProperties 的 baseURI 就没有问题,但是如果我设置 PDF 字体,当有很多并发调用时会出现此错误:

“PDF间接对象属于其他PDF文档。将对象复制到当前pdf文档。”

创建转换属性

private ConverterProperties addResourcesForInitiative(String templateKey, FontProvider fontProvider) {
//        CustomDefaultFontProvider cdfp = new CustomDefaultFontProvider();
        ConverterProperties converterprops = new ConverterProperties();
//        converterprops.setFontProvider(fontProvider);
        converterprops.setBaseUri(ConfigurationManager.getParamValue("resource.path") + templateKey + "/resources/");
        log.info("Properties for conversione are setted. Url of folder loaded " + converterprops.getBaseUri());
        return converterprops;
    }

在每次调用 convertToDocument API 之前创建对象

我错过了什么吗?

感谢大家的帮助

【问题讨论】:

    标签: java itext html2pdf itext7


    【解决方案1】:

    我遇到了同样的问题。它与Itext7 generate pdf with Exception "Pdf indirect object belongs to other PDF document. Copy object to current pdf document." 相关(但不重复)

    一开始我对 iText 7 的不理解是,你有一个 FontProgram 和一个 PdfFont

    • FontProgram 是一个包含 iText 使用字体程序所需的所有信息的类。它可以在创建许多不同 PDF 文件的过程中重复使用。
    • PdfFont 是一个在单个文档的上下文中使用 FontProgram 的类。每个PdfFont 对象只属于一个PdfDocument

    如果您尝试使用PdfFont 对象创建另一个文档,则会收到错误“Pdf 间接对象属于其他 PDF 文档。将对象复制到当前 pdf 文档。”

    换句话说:你不能只重用PdfFont 对象,只能重用FontProgram 对象。重用ConverterProperties(或FontProvider)时可能会出现问题。诀窍不是在FontProvider 中缓存PdfFont 对象,而是缓存FontProgram

    由于这非常令人困惑,我已要求 iText 7 开发团队解决此问题。当我查看封闭的票务系统时,我可以看到文档将得到修复,并且将针对ConverterProperties 进行努力。这意味着您将在下一个版本中看到改进。

    与此同时,我通过更改使用FontProviderConverterProperties 的方式为自己解决了这个问题。必须为每个新文档创建 PdfFont 的新实例,我理解原因:PdfFont 跟踪特定文档中使用的字符,并使用该信息创建字体子集。该子集对于每个文档都是不同的;因此每个文档都需要一个不同的PdfFont 实例。

    我会在关于这个主题的票中添加对这个问题的引用。

    【讨论】:

    • 感谢您的回复。现在我尝试按照您的建议解决问题。是否有修复或 itext7 html2pdf 的新版本的发布日期?
    • 我不知道,但@rafhens 知道。
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多