We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Replace fonts in existing PDF file not working

I am trying to Replace fonts in existing PDF file, but my output PDF file has the following error when opening with AdobeReader.
An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem.

Please give me an idea to solve this problem.

Sample PDF here:
sample7.pdf (67.8 KB)

Here is all of my source:

public static void ReplaceFonts() {
        Locale.setDefault(new Locale("ja-jp"));
        FontRepository.addLocalFontPath("/Users/mypc/Library/Fonts");

        // Instantiate Document object
        Document pdfDocument = new Document("sample7.pdf");

        // Search text fragments and set edit option as remove unused fonts
        TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(
                new TextEditOptions(TextEditOptions.FontReplace.RemoveUnusedFonts));

        // Accept the absorber for all pages of document
        pdfDocument.getPages().accept(textFragmentAbsorber);

        // traverse through all the TextFragments
        TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();
        for (TextFragment textFragment : (Iterable<TextFragment>) textFragmentCollection)
        {
            String fontName = textFragment.getTextState().getFont().getFontName();
            // if the font name is Ryumin-Light-Identity-H, replace font name with MSMincho
            if (fontName.equals("Ryumin-Light-Identity-H")) {
                textFragment.getTextState().setFont(FontRepository.findFont("MSMincho"));
            }
            if (fontName.equals("GothicBBB-Medium-Identity-H")) {
                textFragment.getTextState().setFont(FontRepository.findFont("MSGothic"));
            }
        }
        // Save the updated PDF file
        pdfDocument.save( "sample7_output.pdf");
    }

@phunv

While using latest version of Aspose.PDF for Java 22.2, the loop for TextFragmentCollection does not end. We have logged this problem in our issue tracking system as PDFJAVA-41423. You will be notified via this forum thread once this issue is resolved.

We apologize for your inconvenience.