如何使用java向Itext添加新字体

当我想使用字体是iText时,我会做以下事情:

protected final static Font FONT_SIZE_11_BOLD = new Font(Font.HELVETICA, 11f, Font.BOLD); 

然后我可以随意使用它,如下所示:

 monthSize11 = new Chunk(month, FONT_SIZE_11_BOLD); 

我想使用Arial而不是HELVETICA,但Arial不能直接使用。 我的意思是,我做不到

 new Font(Font.ARIAL, 11f, Font.BOLD); 

因为Arial没有在Font类中定义,但Arial.ttf文件位于C:\ WINDOWS \ Fonts下的系统中。 问题是如何将Arial.ttf文件绑定到iText以及如何使用它。

提前许多事情发生了。

编辑:我想使用自己的字体。 我的意思是,我有一个名为“myCompany.ttf”的文件,其中定义了自己的字体,在某些地方我必须使用。 问题不仅在于Arial。

 BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI); Font font = new Font(base, 11f, Font.BOLD); .... 

在这里阅读更多。

使用前导斜杠从JAR内部加载它; 否则,使用字体的绝对路径( C:\...\fonts\Sansation_Regular.ttf )。 例如:

 Font font = FontFactory.getFont("/fonts/Sansation_Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0.8f, Font.NORMAL, BaseColor.BLACK); BaseFont baseFont = font.getBaseFont(); 
  • 字体的相对路径是:’src / main / resources / fonts’
  • 使用Itext 5.4.5
  • 示例代码

使用BaseFont.createFont创建一个新的Font对象。

您可以传递任何Type1或TTF字体。 您只需要确保您的字体文件随之分发。 请参阅BaseFont API

使用itext创建自定义字体很简单

我在下面写了相同的代码

肯定会帮助别人

 public class CustomFontStyle { public static void main(String[] args) { // creation of the document with a certain size and certain margins // may want to use PageSize.LETTER instead Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // creation of the different writers PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("CustomFontsStyle.pdf")); final String NEWLINE = "\n"; document.open(); Phrase phrase = new Phrase(); BaseFont baseFont3 = BaseFont.createFont("Xenotron.ttf", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); Font font2 = new Font(baseFont3, 12); document.add(new Paragraph("Custom Xenotron Font: ", font2)); phrase.add(NEWLINE); document.add(phrase); document.close(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } }