Shaldryn
Shaldryn

Reputation: 33

PdfBox - change font or fontName in pdf file?

please tell me.

I have a pdf files with fonts HPDFAA+Arial-BoldMTBold. This font name incorrect and it's a subset... I change fonts with library Asponse.pdf.dll, https://docs.aspose.com/pdf/net/replace-text-in-pdf/, paragraph - Replace fonts in existing PDF file, but this library trail version.

How can i do this with PDFBox? I want to replace this font on Arial-BoldMT or rename font name.

UPD: my attempts have led nowhere...In PDFontDescriptor i can rename font, but how i can apply for PDFont? Or i'm going the wrong way?

        PDDocument pdfDocument = PDDocument.load(new File("Sample.pdf"));

        PDPageTree pages = pdfDocument.getDocumentCatalog().getPages();
        for (PDPage page : pages) {
            PDResources res = page.getResources();

            for (COSName fontName : res.getFontNames()) {
                PDFont font = res.getFont(fontName);
                PDFontDescriptor fontDescriptor = font.getFontDescriptor();
                System.out.println("fontDes: " + fontDescriptor.getFontName());
                String oldFontName = fontDescriptor.getFontName();
                String newFontName = oldFontName.replace("Arial-BoldMTBold", "Arial-BoldMT");
                fontDescriptor.setFontName(newFontName);

                System.out.println("font: " + font.getName());
            }

Upvotes: 1

Views: 5707

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18861

Here's code that is tailored to your file. It will only help you if this is about many similar files.

try (PDDocument doc = PDDocument.load(new File(XXX,"outerBox.pdf")))
{
    PDPage page = doc.getPage(0);
    for (COSName name : page.getResources().getFontNames())
    {
        PDFont font = page.getResources().getFont(name);
        String fontName = font.getName();
        if (font instanceof PDType0Font && fontName.endsWith("BoldMTBold"))
        {
            PDType0Font type0font = (PDType0Font) font;
            String newFontName = fontName.substring(0, fontName.length() - 4);
            type0font.getCOSObject().setString(COSName.BASE_FONT, newFontName);
            PDCIDFont descendantFont = type0font.getDescendantFont();
            descendantFont.getCOSObject().setString(COSName.BASE_FONT, newFontName);
            PDFontDescriptor fontDescriptor = descendantFont.getFontDescriptor();
            fontDescriptor.setFontName(newFontName);
        }
    }
    doc.save(new File(XXX,"outerBox-saved.pdf"));
}

PDF structure, seen with PDFDebugger:

enter image description here

Upvotes: 1

Related Questions