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

后端 未结 3 1203
南旧
南旧 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: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.

提交回复
热议问题