Itext7 generate pdf with Exception “Pdf indirect object belongs to other PDF document. Copy object to current pdf document.”

我的未来我决定 提交于 2019-11-29 10:08:24

I have experienced the same problem myself (and it took me hours to discover what I was doing wrong). As it turns out, you can use a specific PdfFont instance for only one document. As soon as you use a PdfFont instance it is linked to that document, and you can no longer use it in another document.

For instance:

class ThisGoesWrong {

    protected PdfFont font;

    public ThisGoesWrong() {
        font = PdfFontFactory.createFont(...);
    }

    public void createPdf() {
        ...
        Paragraph p = new Paragraph("test").setFont(font);
        document.add(p);
        ...
    }
}

The class ThisGoesWrong creates a correct PDF the first time you call createPdf(), but it shows the exception you have when you call it a second time.

I discovered that this solves the problem:

class ThisWorksOK {

    public ThisWorksOK() {
    }

    public void createPdf() {
        ...
        PdfFont font = PdfFontFactory.createFont(...);
        Paragraph p = new Paragraph("test").setFont(font);
        document.add(p);
        ...
    }
}

I don't know if this is a bug (it certainly feels like a bug), so I will create an internal ticket at iText Group.

To improve preformance you should reuse FontProgram:

private FontProgram bfChinese = null;

public GeneratePDFService() {
    String PdfFontPath = EnvironmentUtils.getClasspathFilePath("font/MSYH.TTF");
    try {
        bfChinese =  FontProgramFactory.createFont(PdfFontPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And then:

public void createPdf() {
    ...
    PdfFont font = PdfFontFactory.createFont(bfChinese, "Identity-H", true);
    Paragraph p = new Paragraph("test").setFont(font);
    document.add(p);
    ...
}
Gil Nz

This is how i solved the issue.

  1. Created an DocumentUtil class
  2. Add a static method

    public class DocumentUtils {    
        public static PdfFont setFont() throws Exception {
                return PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
        }
    }
    
  3. Use the font like:

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