简体   繁体   中英

Using Private TTF Fonts in PDFsharp

I am working on a C# .NET WPF desktop application that will generate a PDF that needs a very specific font that would not be installed on the system. I am using PdfSharp-WPF v1.32. The file importantSc.ttf is in the project resources folder.

My best bet is that my URI path is wrong, but I think I have it correct. I do have the font family name correct, as it worked while the font was installed on my dev computer.

using System;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using Microsoft.Win32;
using PdfSharp.Drawing.Layout;
using System.Collections.Generic;
using System.Windows.Input;
using System.Windows;

namespace MyProject
{
    public class MyPdfFile
    {
        private PdfDocument doc;

        public void MakePdf()
        {
            Double x1, y1;      
            XBrush brush = XBrushes.Black;
            XGraphics xgf = XGraphics.FromPdfPage(page);
            doc = new PdfDocument();
            PdfPage page = doc.AddPage();

            // Load in a private font to use.
            XPrivateFontCollection privateFontCollection = new XPrivateFontCollection();
            String fontFamilyName = "Important Script AM";
            String fontUriPath = @"pack://application:,,,/importantSc.ttf";

            Uri fontUri = new Uri( fontUriPath );
            privateFontCollection.Add(fontUri, "./#" + fontFamilyName);

            XFont font = new XFont(fontFamilyName, 9, XFontStyle.Regular); // <-- the error happens here

            //Add text to page
            x1 = 1.96 * 72;
            y1 = 3.25 * 72;
            String printString = "I wish this would work!";
            xgf.DrawString(printString, font, brush, x1, y1);

            xgf.Dispose();
        }
    }
}

I am getting the following error:

An unhandled exception of type 'System.InvalidOperationException' occured in PdfSharp-WPF.dll

Additional Information: Cannot get a matching glyph typeface for font 'Important Script AM'.

You ask no questions.
Here are some notes.

Font handling got much better with PDFsharp 1.50 (currently beta 3b). I'd use 1.50 because I think the new beta is better than the old "stable" release.
With IFontResolver you can avoid dealing with the "pack:" resource syntax.

You can use tools like DotNetPeek from JetBrains to check whether the TTF is really embedded in the assembly and under which name.

You can use the source code package of PDFsharp and debug through privateFontCollection.Add to see if it finds fonts and, if yes, which fonts.

With an MCVE I could help you debugging.
https://stackoverflow.com/help/mcve

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM