Font Embedding for Text Creation in C# and .NET PDFs

Embedding fonts in PDF documents is an important feature if you want your text to display the same on all devices, regardless of whether the font is installed on them. This is especially important to preserve the integrity of the corporate identity and ensure the readability of the document. In this article, we will look at how to embed fonts in a PDF document and draw text using the embedded font using C# and .NET, using the SautinSoft.SautinSoft.Pdf.

It is important to know: In order to embed a font in a PDF document, you need to have access to the font file (usually a file with an extension .ttf or .otf).

By following the steps described below, you will be able to ensure consistent text display on all devices. This is very important for creating professional and reliable PDF documents.

The SautinSoft.PDF library of makes it easy to insert fonts, here's how to do it:

  1. Add SautinSoft.PDF from NuGet.
  2. Create a new document.
  3. Use the font family "Almonte Snow", the font file of which is located in the "Resources" directory.
  4. Use the font family 'Almonte Woodgrain' whose font file is located in the 'Resources' location of the current assembly.
  5. Draw this text.
  6. Save the document in PDF format.

Output result:

Полный код

using System;
using System.IO;
using System.Linq;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Using Embedded Fonts
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/embedded-fonts.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            using (var document = new PdfDocument())
            {
                var page = document.Pages.Add();

                using (var formattedText = new PdfFormattedText())
                {
                    formattedText.FontSize = 48;
                    formattedText.LineHeight = 72;

                    // Use the font family 'Almonte Snow' whose font file is located in the 'Resources' directory.
                    formattedText.FontFamily = new PdfFontFamily(@"..\..\..\Resources", "Almonte Snow");
                    formattedText.AppendLine("Hello World 1!");

                    // Use the font family 'Almonte Woodgrain' whose font file is located in the 'Resources' location of the current assembly.
                    formattedText.FontFamily = new PdfFontFamily("..\\..\\..\\Resources", "Almonte Woodgrain");
                    formattedText.AppendLine("Hello World 2!");

                    // Another way to use the font family 'Almonte Snow' whose font file is located in the 'Resources' directory.
                    formattedText.FontFamily = PdfFonts.GetFontFamilies("..\\..\\..\\Resources").First(ff => ff.Name == "Almonte Snow");
                    formattedText.AppendLine("Hello World 3!");

                    // Another way to use the font family 'Almonte Woodgrain' whose font file is located in the 'Resources' location of the current assembly.
                    formattedText.FontFamily = PdfFonts.GetFontFamilies("..\\..\\..\\Resources").First(ff => ff.Name == "Almonte Woodgrain");
                    formattedText.Append("Hello World 4!");

                    // Draw this text.
                    page.Content.DrawText(formattedText, new PdfPoint(100, 500));
                }
                // Save PDF Document.
                document.Save("Private Fonts.pdf");
            }

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Private Fonts.pdf") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports System.Linq
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Using Embedded Fonts
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/embedded-fonts.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free license:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Using document = New PdfDocument()
				Dim page = document.Pages.Add()

				Using formattedText = New PdfFormattedText()
					formattedText.FontSize = 48
					formattedText.LineHeight = 72

					' Use the font family 'Almonte Snow' whose font file is located in the 'Resources' directory.
					formattedText.FontFamily = New PdfFontFamily("..\..\..\Resources", "Almonte Snow")
					formattedText.AppendLine("Hello World 1!")

					' Use the font family 'Almonte Woodgrain' whose font file is located in the 'Resources' location of the current assembly.
					formattedText.FontFamily = New PdfFontFamily("..\..\..\Resources", "Almonte Woodgrain")
					formattedText.AppendLine("Hello World 2!")

					' Another way to use the font family 'Almonte Snow' whose font file is located in the 'Resources' directory.
					formattedText.FontFamily = PdfFonts.GetFontFamilies("..\..\..\Resources").First(Function(ff) ff.Name = "Almonte Snow")
					formattedText.AppendLine("Hello World 3!")

					' Another way to use the font family 'Almonte Woodgrain' whose font file is located in the 'Resources' location of the current assembly.
					formattedText.FontFamily = PdfFonts.GetFontFamilies("..\..\..\Resources").First(Function(ff) ff.Name = "Almonte Woodgrain")
					formattedText.Append("Hello World 4!")

					' Draw this text.
					page.Content.DrawText(formattedText, New PdfPoint(100, 500))
				End Using
				' Save PDF Document.
				document.Save("Private Fonts.pdf")
			End Using

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Private Fonts.pdf") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.