What is the iText 7 equivalent of FontSelector.Process?

蓝咒 提交于 2019-12-24 23:42:49

问题


I'm beginning the process of updating code written against iText5 to work with iText7.

Is there a similar mechanism in iText7 to the FontSelector class, where you would load up fonts and the "Process" action would automatically determine which font to use (and return a formatted pdf "chunk" that could be added to the document)? Here's the code snippet (this is C++, but my "native" language is C#, so feel free to answer with 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"));
}

回答1:


A similar mechanism is indeed available in iText7. And there is even a way to make it work implicitly without processing chunks and adding them manually to the document. The class you are looking for is called FontProvider. To start with, you need to create an instance and add your fonts to it:

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

Then, you need layout's Document instance which might have been created like this, or in any other way:

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

Then, all you need is set the font provider to the document and, most importantly, set the preferred font name to trigger the font selector mechanism. If you don't select the preferred font name and don't set PdfFont explicitly, the default font, Helvetica, will be used.

The code to do the above might look like following:

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

Finally, don't forget to close the document:

doc.Close();


来源:https://stackoverflow.com/questions/49288142/what-is-the-itext-7-equivalent-of-fontselector-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!