Marshall.Z
Marshall.Z

Reputation: 1

How to use font in other PDF files? (itext7 PDF)

I am now trying to modify a PDF file with ONLY text content. When I use

TextRenderInfo.getFont()

it returns me a Font which is actually an indirect object.

pdf.inderect.object.belong.to.other.pdf.document.Copy.object.to.current.pdf.document 

would be thrown in this case when close the PdfDocument.

Is there a way to let me reuse this Font in a new PDF file? OR, is there a way to in-place edit the text content in PDF (without changing the font, color, fontSize)?

I'm using itext7.

Thanks

Upvotes: 0

Views: 461

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

First of all, from the error message I see that you are not using the latest version of iText, which is 7.0.2 at the moment. So I recommend that you update your iText version.

Secondly, it is indeed possible to use a font in another document. But to do that, you first have to copy the corresponding font object to that other document (as stated in the exception message by the way). But you should be warned that this approach has some limitations, e.g. in case of a font subset, you will only be able to use the glyphs that are present in the original font subset in the source document and will not be able to use other glyphs.

PdfFont font = textRenderInfo.getFont(); // font from source document
PdfDocument newPdfDoc = ... // new PdfDocument you want to write some text to

// copy the font dictionary to the new document
PdfDictionary fontCopy = font.getPdfObject().copyTo(newPdfDoc); 

// create a PdfFont instance corresponding to the font in the new document
PdfFont newFont = PdfFontFactory.createFont(fontCopy);

// Use newFont in newPdfDoc, e.g.:
Document doc = new Document(newPdfDoc);
doc.add(new Paragraph("Hello").setFont(newFont));

Upvotes: 2

Related Questions