【问题标题】:C# add programmatically a font to PDFC# 以编程方式将字体添加到 PDF
【发布时间】:2017-01-27 06:56:27
【问题描述】:

我必须以编程方式向 PDF 添加(注册、嵌入)字体。 我尝试了很多实用程序,例如 ghostscript 或 itextsharp,但我没有设法解决问题。

例如在这种情况下:

我想添加 Courier-Bold 并得到这种情况:

【问题讨论】:

  • 请告诉我们您已经尝试过什么。
  • 我通过 ghostscript 尝试过;我使用的最完整的脚本:-dSAFER -dNOPLATFONTS -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/printer -dCompatibilityLevel=1.4 -dSubsetFonts=true -dEmbedAllFonts=true -sFONTPATH=font_path.ttf -sOutputFile=pdf_out_path -f pdf_in_path I还在 itextsharp 库中搜索了对这个目标有用的东西,但我找不到任何东西。好像只能设置一个段落的字体。
  • 也许这会有所帮助:stackoverflow.com/questions/4231656/…
  • 由于您的文档没有(似乎)使用 Courier-Bold,而是使用 CourierNew-Bold,为什么要添加 Courier-Bold ? Ghostscript 肯定不会在 PDF 文件中添加未使用的字体,这有什么意义呢?如果您发布了一个示例 PDF 文件的 URL 以供查看,并解释为什么要在其中嵌入字体,这可能会有所帮助。
  • 我在 SO 上搜索并没有找到确切的答案,我计划在未来使用 itext,所以我把一些东西放在一起。很快就会发布。

标签: c# pdf fonts ghostscript


【解决方案1】:

我刚刚通过 NuGet 使用 iTextSharp v5.5.9 创建了一个项目,并使用了以下代码:

    const string PdfLocation = @"C:\fakepath\output.pdf";

    static void Main(string[] args)
    {
        using (var pdfDoc = new Document())
        using (var fs = new FileStream(PdfLocation, FileMode.OpenOrCreate))
        using (var writer = PdfWriter.GetInstance(pdfDoc, fs))
        {
            pdfDoc.Open();

            var font = FontFactory.GetFont(FontFactory.COURIER_BOLD);

            // Doesn't use font
            var paragraph = new Paragraph("LINE 1");
            paragraph.Font = font;
            pdfDoc.Add(paragraph);

            // Doesn't use font
            var paragraph2 = new Paragraph();
            paragraph2.Add("LINE 2");
            paragraph2.Font = font;
            pdfDoc.Add(paragraph2);

            // Does use font
            var paragraph3 = new Paragraph();
            paragraph3.Font = font;
            paragraph3.Add("LINE 3"); // This must be done after setting the font
            pdfDoc.Add(paragraph3);

            var cb = writer.DirectContent;

            pdfDoc.Close();
        }
    }

我发现您需要先设置字体,然后再编写文本。以下代码输出具有以下属性的 PDF。我没有从中得到 TrueType 要求,但也许这会让你朝着正确的方向前进。

我使用paragraphparagraph2 的地方将使用默认字体,对我来说是Helvetica,因为我在设置文本后设置字体。顺序很重要!

这方面的文档当然需要扩展...

【讨论】:

  • 您的奖金根本没有任何区别:您只需将 pdf 读入内存,删除内存中未使用的对象,并最终丢弃内存中的表示。磁盘上的pdf根本没有改变。
  • 啊,你是对的。我有一些代码在那里工作。我会在第二个@mkl 修复它。我将不得不删除原始文件以使其正常工作,因为我不知道在创建 PDF 时是否有执行此操作的命令。
猜你喜欢
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多