如何使用 iTextSharp 设置等宽字体?

How to set monospaced font by using iTextSharp?

到目前为止,我是这样管理字体的:

BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, false);
Font titleFont = new Font(bf, 20);

现在,我想设置等宽(固定宽度)字体以进行字符串格式化。我是否必须下载一些 ttf 文件(正如我正在阅读的那样)或者 iTextSharp

中已经包含等宽字体

如果你不想嵌入字体,你可以使用这个:

BaseFont bf = BaseFont.createFont(
    BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
Font titleFont = new Font(bf, 20);

Helvetica 是比例字体。如果需要等宽字体,则需要使用 Courier 等字体。请参阅 the Wikipedia page 关于等宽字体。

请注意,您的代码也没有创建嵌入的字体:Helvetica 是(就像 Courier 一样)所谓的标准 Type 1 字体之一。标准 Type 1 字体永远不会嵌入,因为 iText 只能访问这些字体的 AFM 文件,而不能访问 PFB 文件。阅读例如:Why do I get a font embedding error when creating PDFA/1a?. In some other cases, iText embeds a font even if you don't want to. See for instance: Why is iText embedding a font even when I specify not to embed?

如果您想嵌入等宽字体,或者如果您不喜欢 Courier,则需要一个字体文件,例如 ttf 文件。我在谷歌上搜索了 "sexier" 等宽字体,我找到了这些页面:Top 10 Most Popular Monospaced Fonts and 10 great free monospaced fonts for programming. If you work on Windows, you have the choice between Courier New and Lucida Sans Typewriter as described in this knowledge base article.

获得 TTF 文件后,只需使用标准的 iText 代码即可。对于 Lucida Sans Typewriter Regular,您需要这样的东西:

BaseFont bf = BaseFont.createFont(
    "c:/windows/fonts/LTYPE.TTF", BaseFont.CP1250, BaseFont.EMBEDDED);
Font titleFont = new Font(bf, 20);

注意:始终检查您使用的字体是否支持您要使用的编码。不要假设每种字体都知道每种编码。

请注意,大多数字体都不是免费的。另见 Do I need a license for Windows fonts when using iText?。您可以下载字体这一事实并不自动意味着您可以免费使用它(iText 也是如此;如果您正在为客户构建应用程序,则必须购买 iText 许可证)。