简体   繁体   English

在iTextPDF中将BOLD设置为自定义字体

[英]Setting BOLD to a custom font in iTextPDF

I need to use a particular font to make a document because it contains specia charactesrs such as "Đ" that are not supported by the normal fonts iText comes with. 我需要使用一种特殊的字体来制作文档,因为它包含iText随附的常规字体不支持的特殊字符,例如“Đ”

So, I made this: 所以,我做到了:

BaseFont CROACIA = BaseFont.createFont("C:\\FreeSans.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);

Font CROATA = new Font(CROACIA, 12);

It works fine and my "Đ" problem is solved, the thing is that I cant set it to be bold 它工作正常,我的“Đ”问题已解决,问题是我无法将其设置为大胆

I tried to make a different font with "BOLD" setting like this_ 我尝试使用“ BOLD”设置制作其他字体,例如this_

Font CROATABOLD = new Font(CROACIA, 12, BOLD);

The code does not seems erroneous but when I apply it to a paragraph it just not work, the font seems as normal as usual 该代码似乎没有错误,但是当我将其应用于段落时,它却无法正常工作,字体看起来像往常一样正常

FreeSans and FreeSansBold are different fonts of the same family . FreeSans和FreeSansBold是同一家族的 不同字体 You provide a path to the FreeSans.ttf font program and as a result iText can use the regular font in the FreeSans family. 您提供了FreeSans.ttf字体程序的路径,因此iText可以使用FreeSans系列中的常规字体。 If you want to use the bold font, you need to provide a path to FreeSansBold.ttf which is a different font program for a font in the same family. 如果要使用粗体字体,则需要提供FreeSansBold.ttf的路径,该路径是同一家族中字体的不同字体程序。

This is shown in the FreeSansBold example: 这在FreeSansBold示例中显示:

public static final String FONT = "resources/fonts/FreeSans.ttf";
public static final String FONTBOLD = "resources/fonts/FreeSansBold.ttf";

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font font = new Font(bf, 12);
    Paragraph p = new Paragraph("FreeSans regular: \u0110", font);
    document.add(p);
    BaseFont bfbold = BaseFont.createFont(FONTBOLD, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font bold = new Font(bfbold, 12);
    p = new Paragraph("FreeSans bold: \u0110", bold);
    document.add(p);
    document.close();
}

We have two different fonts FreeSans.ttf and FreeSansBold.ttf of the same family. 我们拥有同一个家族的两种不同的字体FreeSans.ttfFreeSansBold.ttf One is the regular font; 一种是常规字体;另一种是常规字体。 the other one is the bold font. 另一种是粗体。 If you look at the document properties of the result, free_sans_bold.pdf , you clearly see that two different fonts are at play: 如果查看结果的文档属性free_sans_bold.pdf ,您会清楚地看到两种不同的字体在起作用:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM