There may be a situation that you want to change the font(s)
in your PDF document. In this article, I will show you how to replace fonts in PDF
programmatically in Java using Free Spire.PDF for Java library.
Installation
If you use maven, you need to specify the dependencies for Free
Spire.PDF for Java in your project’s pom.xml file.
- <repositories>
- <repository>
- <id>com.e-iceblue</id>
- <name>e-iceblue</name>
- <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
- </repository>
- </repositories>
- <dependencies>
- <dependency>
- <groupId>e-iceblue</groupId>
- <artifactId>spire.pdf.free</artifactId>
- <version>4.4.1</version>
- </dependency>
- </dependencies>
For non-maven projects, download Free Spire.PDF for Java
pack from this website and add Spire.Pdf.jar in the lib folder into your
project as a dependency.
Implementation
The following are the steps to replace fonts in a PDF
document:
- Create a PdfDocument instance
- Load the document using PdfDocument.loadFromFile(String) method
- Create a PDFFont instance
- Get the fonts used in the document using PdfDocument.getUsedFonts() method
- Replace font with the PDFFont instance using PdfUsedFont.replace(PdfFontBase) method
- Save the document using PdfDocument.saveToFile(String) method
Sample code
- import com.spire.pdf.PdfDocument;
- import com.spire.pdf.graphics.*;
- import com.spire.pdf.graphics.fonts.PdfUsedFont;
- import java.awt.*;
- public class ReplaceFonts {
- public static void main(String []args) throws Exception {
- //Create a PdfDocument instance
- PdfDocument pdf = new PdfDocument();
- //Load the PDF document
- pdf.loadFromFile("E:\\Program Files\\input.pdf");
- //Create a PdfFont instance
- PdfFont baseFont = new PdfFont(PdfFontFamily.Helvetica, 11f, PdfFontStyle.Italic);
- //Get the fonts used in the Pdf document
- PdfUsedFont[] usedFonts = pdf.getUsedFonts();
- //Replace the first font
- usedFonts[0].replace(baseFont);
- //Save the result file
- pdf.saveToFile("output.pdf");
- }
- }
The above example shows how to replace a font with a PDF base font, if you want to replace the font with a TrueType font or with a font file that is available on your system but is not installed, simply create a PdfTrueTypeFont instance instead of PdfFont instance.
For example, use
- //Create a PdfTrueTypeFont instance with font name
- PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(new Font("Arial",Font.ITALIC, 14));
or
- //Create a PdfTrueTypeFont instance with font file
- PdfTrueTypeFont fontFile = new PdfTrueTypeFont("Arial.ttf", 14);
instead of
- PdfFont baseFont = new PdfFont(PdfFontFamily.Helvetica, 11f, PdfFontStyle.Italic);
Besides, you can also replace the font with a CJK(Chinese, Japanese, Korean) font using PdfCjkStandardFont instance:
- PdfCjkStandardFont cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Hanyang_Systems_Gothic_Medium, 14);
That’s all. Thanks for taking time to read my article.
Comments
Post a Comment