在PDFsharp中使用私有TTF字体

时间:2017-02-27 13:37:50

标签: c# .net wpf true-type-fonts pdfsharp

我正在开发一个C#.NET WPF桌面应用程序,它将生成一个需要非特定字体的PDF,该字体不会安装在系统上。我正在使用PdfSharp-WPF v1.32。文件importantSc.ttf位于项目资源文件夹中。

我最好的选择是我的URI路径错误,但我认为我说得对。我的字体系列名称是正确的,因为它在我的开发计算机上安装了字体时起作用。

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();
        }
    }
}

我收到以下错误:

PdfSharp-WPF.dll中出现未处理的“System.InvalidOperationException”类型异常

其他信息:无法获取字体的 '重要脚本AM' 匹配的字形字体

1 个答案:

答案 0 :(得分:0)

你不问任何问题 这是一些笔记。

使用PDFsharp 1.50(目前为beta 3b),字体处理得到了更好的处理。我使用1.50因为我认为新的测试版比旧的“稳定版”更好 使用IFontResolver,您可以避免处理“pack:”资源语法。

您可以使用JetBrains的DotNetPeek等工具来检查TTF是否真的嵌入在程序集中以及名称下。

您可以使用PDFsharp的源代码包并通过privateFontCollection.Add进行调试,以查看是否找到字体,如果是,则查找哪些字体。

使用MCVE,我可以帮助您调试 https://stackoverflow.com/help/mcve