How to replace fonts in PDF with Java
This article is about how Java can replace fonts in PDF. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Introduction of jar
Configure pom.xml in the Maven program:
Com.e-iceblue https://repo.e-iceblue.cn/repository/maven-public/ e-iceblue spire.pdf.free 5.1.0
If you need to import manually, download the Jar package locally, extract it, and find the Spire.Pdf.jar file in the lib folder. Open "Project Structure" in IDEA and import the jar under the local path into the program, as shown in the figure:
Java code 1. Replace all fonts
Idea: after loading the PDF document, get the font in the source document, then define the new font, replace the original font, and finally save the document.
Java
Import com.spire.pdf.*;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 an object of PdfDocument class PdfDocument pdf = new PdfDocument (); / / load PDF document pdf.loadFromFile ("input.pdf") / / get all fonts in the document PdfUsedFont [] fonts = pdf.getUsedFonts (); / / traverse all fonts for (PdfUsedFont font: fonts) {/ / get font size float fontSize = font.getSize (); / / create new fonts PdfFont newfont = new PdfFont (PdfFontFamily.Times_Roman, fontSize, PdfFontStyle.Italic) / / replace the original font font.replace (newfont);} / / Save the document pdf.saveToFile ("ReplaceAllFonts.pdf"); pdf.dispose ();}}
two。 Replace the specified font
Idea: after loading the PDF document, find and get the specified font in the document, then define a new font, replace the original font found, and finally save the document.
Java
Import com.spire.pdf.PdfDocument;import com.spire.pdf.graphics.*;import com.spire.pdf.graphics.fonts.PdfUsedFont;public class ReplaceSpecificFont {public static void main (String [] args) throws Exception {/ / create an object of PdfDocument class PdfDocument pdf = new PdfDocument (); / / load PDF document pdf.loadFromFile ("sample.pdf") / / get all fonts in the document PdfUsedFont [] fonts = pdf.getUsedFonts () / / traverse all fonts for (PdfUsedFont font: fonts) {/ / determine the font if (font.getName (). Equals ("Calibri")) {/ / get the font size float fontSize = font.getSize () / / create new fonts PdfFont newfont = new PdfFont (PdfFontFamily.Times_Roman, fontSize, PdfFontStyle.Italic); / / replace Calibri fonts font.replace (newfont);}} / / Save document pdf.saveToFile ("ReplaceSpecificFont.pdf"); pdf.dispose ();}}
Thank you for reading! This is the end of this article on "how to replace the font function in PDF by Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!