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

后端 未结 3 1195
南旧
南旧 2020-12-18 21:28

i want to generate a pdf with itext 7,but some wrong happens to us:

com.itextpdf.kernel.PdfException: Pdf indirect object belongs to other PDF document. Copy         


        
相关标签:
3条回答
  • 2020-12-18 22:17

    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();
      
    0 讨论(0)
  • 2020-12-18 22:26

    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.

    0 讨论(0)
  • 2020-12-18 22:30

    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);
        ...
    }
    
    0 讨论(0)
提交回复
热议问题