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
This is how i solved the issue.
Add a static method
public class DocumentUtils {
public static PdfFont setFont() throws Exception {
return PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
}
}
Use the font like:
PDfFont font = DocumentUtil.setFont();
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);
...
}