Как загрузить PDF документ и получить недостающие шрифты на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите PDF-документ из файла или потока.
  3. Найдите недостающие шрифты.

После процесса загрузки PDF-документов получите названия шрифтов, которые не установлены в Вашей системе, используя свойство FontSettingsMissingFonts.

Кроме того, Вы можете заменить исходный шрифт именем альтернативного шрифта, доступного в Вашей системе, с помощью метода FontSettingsAddFontSubstitutes.

В приведенном ниже примере кода показано, как получить названия шрифтов, которые не установлены в системе, и заменить эти шрифты альтернативными названиями шрифтов.

Полный код

using System;
using System.IO;
using SautinSoft.Document;

namespace Example
{
    class Program
    {

        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            LoadPDF();
        }

        /// <summary>
        /// Load a PDF document and get missing fonts.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-pdf-document-get-missing-fonts-net-csharp-vb.php
        /// </remarks>
        static void LoadPDF()
        {            
            string inpFile = @"..\..\..\fonts.pdf";
            string outFile = "Result.docx";

            // Some PDF documents can use rare fonts which isn't installed in your system.
            // During the loading of a PDF document the component tries to find all necessary 
            // fonts installed in your system.
            // In case of the font is missing, you can find its name in the property 'MissingFonts' (after the loading process).
            DocumentCore dc = DocumentCore.Load(inpFile);
            
            if (SautinSoft.Document.FontSettings.MissingFonts.Count > 0)
            {
                Console.WriteLine("Missing Fonts:");
                foreach (string fontFamily in SautinSoft.Document.FontSettings.MissingFonts)
                    Console.WriteLine(fontFamily);
            }

            // Next, knowing missing fonts, you can install these fonts in your system.

            // Also, you can specify an extra folder where component should find fonts.
            SautinSoft.Document.FontSettings.UserFontsDirectory = @"d:\My Fonts";

            // Furthermore, you can add font substitutes, to use alternative fonts.            
            SautinSoft.Document.FontSettings.AddFontSubstitutes("Melvetika", "Segoe UI");
            Console.WriteLine("We\'ve changed Melvetica font to Segoe UI");

            // Load the document again.
            dc = DocumentCore.Load(inpFile);
            dc.Save(outFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            Console.ReadKey();
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Namespace Example
	Friend Class Program

		Shared Sub Main(ByVal args() As String)
			LoadPDF()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Load a PDF document and get missing fonts.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-pdf-document-get-missing-fonts-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub LoadPDF()
			Dim inpFile As String = "..\..\..\fonts.pdf"
			Dim outFile As String = "Result.docx"

			' Some PDF documents can use rare fonts which isn't installed in your system.
			' During the loading of a PDF document the component tries to find all necessary 
			' fonts installed in your system.
			' In case of the font is missing, you can find its name in the property 'MissingFonts' (after the loading process).
			Dim dc As DocumentCore = DocumentCore.Load(inpFile)

			If SautinSoft.Document.FontSettings.MissingFonts.Count > 0 Then
				Console.WriteLine("Missing Fonts:")
				For Each fontFamily As String In SautinSoft.Document.FontSettings.MissingFonts
					Console.WriteLine(fontFamily)
				Next fontFamily
			End If

			' Next, knowing missing fonts, you can install these fonts in your system.

			' Also, you can specify an extra folder where component should find fonts.
			SautinSoft.Document.FontSettings.UserFontsDirectory = "d:\My Fonts"

			' Furthermore, you can add font substitutes, to use alternative fonts.            
			SautinSoft.Document.FontSettings.AddFontSubstitutes("Melvetika", "Segoe UI")
			Console.WriteLine("We've changed Melvetica font to Segoe UI")

			' Load the document again.
			dc = DocumentCore.Load(inpFile)
			dc.Save(outFile)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
			Console.ReadKey()
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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