Alexev
Alexev

Reputation: 157

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.

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_

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

Upvotes: 0

Views: 4239

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

FreeSans and FreeSansBold are different fonts of the same family. You provide a path to the FreeSans.ttf font program and as a result iText can use the regular font in the FreeSans family. 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.

This is shown in the FreeSansBold example:

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. 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:

enter image description here

Upvotes: 2

Related Questions