为什么 courier 字体在 iText PDF 文档中不起作用?

why courier font not working in iText PDF document?

使用以下代码使用 iText 5 在 C# 中创建 PDF 文档。文本未以 courier 字体呈现。为什么不呢?

private void SimpleFontDoc(string pdfDocPath)
{
  Document doc = new Document(PageSize.LETTER, 10, 10, 42, 30);
  var fs = new FileStream(pdfDocPath, FileMode.Create);
  PdfWriter writer = PdfWriter.GetInstance(doc, fs);
  doc.Open();

  string[] lines = new string[]
    {
        "First   text   line",
        "Second  text   line"
    };
  var font = FontFactory.GetFont("courier", 12.0f, BaseColor.BLACK);

  foreach (var line in lines)
  {
    var para = new iTextSharp.text.Paragraph(line);
    para.Font = font;
    doc.Add(para);
  }

  doc.Close();
}

在 iText5 中,您必须在向段落元素添加文本之前指定字体(或者将其传递给构造函数)。

改变

var para = new iTextSharp.text.Paragraph(line);
para.Font = font;

进入

var para = new iTextSharp.text.Paragraph(line, font);