How to set monospaced font by using iTextSharp?

坚强是说给别人听的谎言 提交于 2019-12-20 05:58:24

问题


This is how I managed my font so far:

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

Now, I want to set monospaced (fixed width) font for purpose of string formatting. Do I have to download some ttf file (as I was reading about it) or there is monospaced font already included in iTextSharp


回答1:


If you don't want to embed a font, you can use this:

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

Helvetica is a proportional font. If you need a monospaced font, you need to use a font such as Courier. See the Wikipedia page about monospaced fonts.

Note that your code didn't create a font that was embedded either: Helvetica is (just like Courier for that matter) one of the so-called Standard Type 1 fonts. Standard Type 1 fonts are never embedded because iText only has access to the AFM files of these fonts, not to the PFB files. Read for instance: 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?

If you want to embed a monospaced font or, if you don't like Courier, you need a font file, for instance a ttf file. I Googled for "sexier" monospaced fonts and I found these pages: 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.

Once you have a TTF file, just use the standard iText code. In the case of Lucida Sans Typewriter Regular, you'd need something like this:

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

Note: always check if the encoding you want to use is supported by the font you're using. Don't assume that every font knows every encoding.

Be aware that most fonts aren't free. See also Do I need a license for Windows fonts when using iText?. The fact that you can download a font doesn't automatically mean you can use it for free (the same is true for iText; if you are building an application for a customer, you'll have to purchase an iText license).



来源:https://stackoverflow.com/questions/34495221/how-to-set-monospaced-font-by-using-itextsharp

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