Wednesday, 19 January 2022 07:07

Java: Replace Fonts in a PDF Document

The use of appropriate fonts is one of the key elements of making successful documents. For example, we typically use different fonts for headings and paragraphs in order to create distinction and achieve a visually pleasing effect. When you receive a PDF document where the fonts are properly used, you may wish to change them. In this article, you’ll learn how to replace the fonts being used in a PDF document using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.4.4</version>
    </dependency>
</dependencies>
    

Replace All Used Fonts in a Document

A PDF document may use multiple fonts, and each font may have a different font size. When replacing these fonts, make sure that the font size does not change. Otherwise, the generated content may overlap or become disordered. The following are the steps to replace all used fonts in a document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Get all used fonts in the document using PdfDocument.getUsedFonts() method.
  • Loop through the used fonts. Get the size of a specific font using PdfUsedFont.getSize() method.
  • Create a new font based on the size obtained, and replace the old font with the new font using PdfUsedFont.replace() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfFont;
import com.spire.pdf.graphics.PdfFontFamily;
import com.spire.pdf.graphics.PdfFontStyle;
import com.spire.pdf.graphics.fonts.PdfUsedFont;

public class ReplaceAllFonts {

    public static void main(String[] args) throws Exception {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Fonts.pdf");

        //Get all used fonts in the document
        PdfUsedFont[] fonts = doc.getUsedFonts();

        //Travers all used fonts 
        for (PdfUsedFont font: fonts
             ) {

            //Get the font size
            float fontSize = font.getSize();

            //Create a new font
            PdfFont newfont = new PdfFont(PdfFontFamily.Times_Roman, fontSize, PdfFontStyle.Italic);

            //Replace the current font with the new font
            font.replace(newfont);

        }

        //Save the changes to a different PDF file
        doc.saveToFile("output/ReplaceAllFonts.pdf");
    }
}

Java: Replace Fonts in a PDF Document

Replace a Specific Font with a Different Font

The PdfDocument.getUsedFonts() method returns a collection of the fonts used in a PDF document. To identify a specific font from the fonts collection, use the PdfUsedFont.getName() method. The following are the steps to replace a specific font with a different font.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Get all used fonts in the document using PdfDocument.getUsedFonts() method.
  • Loop through the used fonts, determining if a certain font is "Calibri".
  • Get the font "Calibri" and get its size using PdfUsedFont.getSize() method.
  • Create a new font based on the size obtained, and replace the font "Calibri" with the new font using PdfUsedFont.replace() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfFont;
import com.spire.pdf.graphics.PdfFontFamily;
import com.spire.pdf.graphics.PdfFontStyle;
import com.spire.pdf.graphics.fonts.PdfUsedFont;

public class ReplaceSpecificFontWithNewFont {

    public static void main(String[] args) throws Exception {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Fonts.pdf");

        //Get all fonts used in the document
        PdfUsedFont[] fonts = doc.getUsedFonts();

        //Travers all used fonts 
        for (PdfUsedFont font: fonts
        ) {

            //Determine if a font’s name is "Calibri"
            if(font.getName().equals("Calibri")){

                //Get the font size
                float fontSize = font.getSize();

                //Create a new font
                PdfFont newfont = new PdfFont(PdfFontFamily.Times_Roman, fontSize, PdfFontStyle.Italic);

                //Replace the font "Calibri" with the new font
                font.replace(newfont);
            }

        }

        //Save the changes to a different PDF file
        doc.saveToFile("output/ReplaceSpecificFont.pdf");
    }
}

Java: Replace Fonts in a PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Font
Monday, 17 July 2023 06:16

Java: Apply Different Fonts in PDF

When creating PDF, it’s important to use appropriate fonts in different situations. For normal PDF files, you can draw text with common fonts such as Arial, Times New Roman. If you want to create a distinctive PDF with a unique visual identity, you can use private fonts. This article will demonstrate how to use different fonts in a PDF document with Spire.PDF for Java library.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.4.4</version>
    </dependency>
</dependencies>
    

Apply Different Fonts in a PDF Document in Java

Spire.PDF for Java supports standard PDF fonts, TrueType fonts, private fonts as well as CJK font. The following are the steps to draw text in PDF using these fonts.

  • Create a PdfDocument instance.
  • Add a page and then create a brush.
  • Create an instance of the PdfFont class with a standard PDF font, and then use the PdfPageBase.getCanvas().drawString() method to draw text on the page with the standard font.
  • Create an instance of the PdfTrueTypeFont class with a specified font, and then draw text on the page with the TrueType font.
  • Load a private font and create an instance of the PdfTrueTypeFont class with it. Then draw text on the page with the private font.
  • Create an instance of PdfCjkStandardFont class with a CJK font, and then draw text on the page with the CJK font.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

public class PdfFonts {

    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Add a page
        PdfPageBase page = pdf.getPages().add();

        //Create a brush
        PdfBrush brush = PdfBrushes.getBlack();

        //Initialize y coordinate
        float y = 30;

        //Draw text using standard fonts
        PdfFont standardFont = new PdfFont(PdfFontFamily.Helvetica, 14f);
        page.getCanvas().drawString("Standard Font - Helvetica", standardFont, brush, 0, y);
        standardFont = new PdfFont(PdfFontFamily.Times_Roman, 14f);
        page.getCanvas().drawString("Standard Font - Times_Roman", standardFont, brush, 0, (y = y + 16));
        standardFont = new PdfFont(PdfFontFamily.Courier, 14f);
        page.getCanvas().drawString("Standard Font - Courier", standardFont, brush, 0, (y = y + 16));

        //Draw text using truetype font
        java.awt.Font font = new java.awt.Font("Arial", java.awt.Font.BOLD, 14);
        PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(font);
        page.getCanvas().drawString("TrueType Font - Arial", trueTypeFont, brush, 0, (y = y + 30f));

        //Draw text using private font
        String fontFileName = "Khadija.ttf";
        trueTypeFont = new PdfTrueTypeFont(fontFileName, 14f);
        page.getCanvas().drawString("Private Font - Khadija", trueTypeFont, brush, 0, (y = y + 30f));

        //Draw text using cjk fonts
        PdfCjkStandardFont cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Monotype_Hei_Medium, 14f);
        page.getCanvas().drawString("How to say 'Font' in Chinese? \u5B57\u4F53", cjkFont, brush, 0, (y = y + 30f));
        cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Hanyang_Systems_Gothic_Medium, 14f);
        page.getCanvas().drawString("How to say 'Font' in Japanese? \u30D5\u30A9\u30F3\u30C8", cjkFont, brush, 0, (y = y + 16f));
        cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Hanyang_Systems_Shin_Myeong_Jo_Medium, 14f);
        page.getCanvas().drawString("How to say 'Font' in Korean? \uAE00\uAF34", cjkFont, brush, 0, (y = y + 16f));

        //Save the result document
        pdf.saveToFile("PdfFonts.pdf");
        pdf.close();
    }
}

Java: Apply Different Fonts in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Font