News Category

Replace font(s) in PDF document

2017-02-22 09:12:35 Written by  support iceblue
Rate this item
(0 votes)

Spire.PDF supports the functionality to replace font(s) used in PDF document. The following parts shows how we can use Spire.PDF to replace all the fonts used in an existing PDF document with another alternate font in C# and VB.NET.

Screenshot before replacing font:

How to replace font(s) in PDF document

Code snippets:

Step 1: Instantiate an object of PdfDocument class and load the PDF document.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"E:\Program Files\input.pdf");

Step 2: Use the UsedFonts attribute of PdfDocument class to get all the fonts used in the document.

PdfUsedFont[] fonts = doc.UsedFonts;

Step 3: Create a new PDF font. Loop through the fonts and call PdfUsedFont.replace() method to replace them with the new font.

PdfFont newfont = new PdfFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Italic | PdfFontStyle.Bold);
foreach (PdfUsedFont font in fonts)
{
    font.Replace(newfont);
}

Step 4: Save the resultant document.

doc.SaveToFile("output.pdf");

Screenshot after replacing font:

How to replace font(s) in PDF document

Full code:

[C#]
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Fonts;

namespace Replace_font_in_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"E:\Program Files\input.pdf");
            PdfUsedFont[] fonts = doc.UsedFonts;
            PdfFont newfont = new PdfFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Italic | PdfFontStyle.Bold);
            foreach (PdfUsedFont font in fonts)
            {
                font.Replace(newfont);
            }

            doc.SaveToFile("output.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Graphics.Fonts

Namespace Replace_font_in_PDF
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("E:\Program Files\input.pdf")
			Dim fonts As PdfUsedFont() = doc.UsedFonts
			Dim newfont As New PdfFont(PdfFontFamily.TimesRoman, 11F, PdfFontStyle.Italic Or PdfFontStyle.Bold)
			For Each font As PdfUsedFont In fonts
				font.Replace(newfont)
			Next

			doc.SaveToFile("output.pdf")
		End Sub
	End Class
End Namespace

Additional Info

  • tutorial_title: Replace font(s) in PDF document
Last modified on Sunday, 26 September 2021 01:56