如何在 Itext7 中使用任何印地文字体?

How to use any Hindi Font in Itext7?

我正在使用 iText 7.net 根据用户语言选择输入创建印地语或英语 pdf,但我想不出任何方法将我选择的印地语 .ttf 字体文件转换为 itext Pdffonts。使用标准的 Itext 字体,它在英语中运行良好。

这是我的代码:

    PdfFontFactory.Register(HindiFont1.ToString(), "HindiFont1");

    //Error at this line: Font Not Recognized
    PdfFont myHindiFont1 = PdfFontFactory.CreateFont("HindiFont1", PdfEncodings.IDENTITY_H, true);
    //Create Writer
    PdfWriter writer = new PdfWriter(path);

    //Create Pdf Document Object
    PdfDocument pdf = new PdfDocument(writer);
    Document document = new Document(pdf, size);
    PdfPage page1 = pdf.AddNewPage();
     PdfCanvas canvas3 = new PdfCanvas(page3);
    Rectangle pageSize3 = page3.GetPageSize();

    //String in Title9 Paragraph is a translation of English Phrase
     iText.Layout.Element.Paragraph Title9 = new iText.Layout.Element.Paragraph("ew[;kad fo'kslrk;sa%");

    Title9.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
   // Title9.SetFont(myHindiFont1);

     document.Close();

代码在顶部保存 pdf 第二行时出错。变量 HindiFont1 包含印地语字体 .ttf 文件。

Title9 Paragraph中的String是英文Phrase的翻译。

任何人都可以帮助使用我的印地语字体吗?我有 4-5 种字体要使用。

首先,要检索以前注册的字体,请使用 PdfFontFactory 方法 CreateRegisteredFont 而不是 CreateFont。因此,替换

PdfFont myHindiFont1 = PdfFontFactory.CreateFont("HindiFont1", PdfEncodings.IDENTITY_H, true);

来自

PdfFont myHindiFont1 = PdfFontFactory.CreateRegisteredFont("HindiFont1", PdfEncodings.IDENTITY_H, true);

那么,如果要在要绘制的段落中添加特定字体的文本,请先设置字体,然后再添加文本。因此,而不是

iText.Layout.Element.Paragraph Title9 = new iText.Layout.Element.Paragraph("ew[;kad fo'kslrk;sa%");
Title9.SetFont(myHindiFont1);

iText.Layout.Element.Paragraph Title9 = new iText.Layout.Element.Paragraph().SetFont(myHindiFont1).Add("ew[;kad fo'kslrk;sa%");

或者您可以将该字体设置为文档默认字体:

Document document = new Document(pdf, size);
document.SetFont(myHindiFont1);

iText.Layout.Element.Paragraph Title9 = new iText.Layout.Element.Paragraph("ew[;kad fo'kslrk;sa%");

最后,将您的新段落添加到某个实体,例如

document.Add(Title9);

结果:


这里是我用来成功呈现上面屏幕截图的最终代码:

String HindiFont1 = @"LEOPALMHINDI15K710.TTF";
PageSize size = PageSize.A4;

PdfFontFactory.Register(HindiFont1, "HindiFont1");

//Error at this line: Font Not Recognized
PdfFont myHindiFont1 = PdfFontFactory.CreateRegisteredFont("HindiFont1", PdfEncodings.IDENTITY_H, true);
//Create Writer
PdfWriter writer = new PdfWriter(@"UseLeopalmhindi15K710LikeDivyanshuAgarwalImproved.pdf");

//Create Pdf Document Object
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, size);
//document.SetFont(myHindiFont1);
//String in Title9 Paragraph is a translation of English Phrase
//iText.Layout.Element.Paragraph Title9 = new iText.Layout.Element.Paragraph("ew[;kad fo'kslrk;sa%");
iText.Layout.Element.Paragraph Title9 = new iText.Layout.Element.Paragraph().SetFont(myHindiFont1).Add("ew[;kad fo'kslrk;sa%");

Title9.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);

document.Add(Title9);

document.Close();