【问题标题】:What is the iText 7 equivalent of FontSelector.Process?什么是 FontSelector.Process 的 iText 7 等效项?
【发布时间】:2018-03-14 21:47:01
【问题描述】:

我正在开始更新针对 iText5 编写的代码以使用 iText7。

iText7 中是否有与 FontSelector 类类似的机制,您可以在其中加载字体,“处理”操作将自动确定要使用的字体(并返回可以添加到文档中的格式化 pdf“块” )?这是代码 sn-p(这是 C++,但我的“本机”语言是 C#,所以请随意用 C# 回答)。

try {
    doc = gcnew Document();
    pdfWriter = PdfWriter::GetInstance(doc, pdfStream);

    FontSelector^ selector = gcnew FontSelector();
    selector->AddFont(gcnew Font(BaseFont::CreateFont("Fonts\\cour.ttf"), BaseFont::IDENTITY_H, BaseFont::NOT_EMBEDDED), 10.0f));
    selector->AddFont(gcnew Font(BaseFont::CreateFont("Fonts\\arialuni.ttf"), BaseFont::IDENTITY_H, BaseFont::NOT_EMBEDDED), 10.0f));

    doc->Open();
    while (textReader->EndOfStream == false)
    {
        String^ line = textReader->ReadLine();
        doc->Add(selector->Process(line + "\n"));
}

【问题讨论】:

    标签: fonts itext itext7


    【解决方案1】:

    iText7 中确实有类似的机制。甚至还有一种方法可以使其隐式工作,而无需处理块并将它们手动添加到文档中。您要查找的课程名为FontProvider。首先,您需要创建一个实例并向其中添加字体:

    FontProvider provider = new FontProvider();
    provider.AddFont(fontsFolder + "NotoSans-Regular.ttf");
    provider.AddFont(fontsFolder + "FreeSans.ttf");
    provider.GetFontSet().AddFont(fontsFolder + "Puritan2.otf", PdfEncodings.IDENTITY_H);
    

    然后,您需要layoutDocument 实例,它可能是这样创建的,或者以任何其他方式:

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
    Document doc = new Document(pdfDoc);
    

    然后,您只需为文档设置字体提供程序,最重要的是,设置首选字体名称以触发字体选择器机制。如果您没有选择首选字体名称并且没有明确设置PdfFont,则将使用默认字体Helvetica

    执行上述操作的代码可能如下所示:

    doc.SetFontProvider(provider);
    doc.SetFont("NotoSans");
    Paragraph paragraph = new Paragraph("Hello world! \u05E2\u05B4\u05D1\u05B0\u05E8\u05B4\u05D9\u05EA\u202C");
    doc.Add(paragraph);
    

    最后别忘了关闭文档:

    doc.Close();
    

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 2017-12-17
      • 2012-12-27
      • 2018-11-12
      • 2012-10-16
      • 2010-10-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多