I am using iText for PDF generation. I have some characters/symbols to print like ∈, ∩, ∑, ∫, ? (Mathematical symbols) and many others. How can I add them to a PDF?

This is my code :

Document document = new Document(PageSize.A4, 60, 60, 60, 60);
try {
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/adeel/experiment.pdf"));
    document.open();
    String str = "this string will contains special character like this  ∈, ∩, ∑, ∫, ?";
    BaseFont bfTimes = null;
    try {
        bfTimes = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Font fontnormal = new Font(bfTimes, 12, Font.NORMAL, Color.BLACK);
    Paragraph para = new Paragraph(str, fontnormal);
    document.add(para);
    document.close();
    System.out.println("Done!");
} catch (DocumentException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
     e.printStackTrace();
}
In the above code I am putting all the symbols in str. Instead of symbols, I also tried putting unicode characters in str for the symbols, but It didn't worked either.

Posted on StackOverflow on Jul 7, 2015 by Adeel Ahmad

Please take a look at the MathSymbols example.

  • First you need a font that supports the symbols you need. Incidentally, FreeSans.ttf is such a font. Then you need to use the right encoding.

  • You're using UNICODE, so you need Identity-H as the encoding.

  • You should also use notations such as \u2208, \u2229, \u2211, \u222b, \u2206. That's not a must, but it's good practice.

This is how it should be done in iText 7:

public static final String FONT = "./src/test/resources/font/FreeSans.ttf";
public void createPdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H, true);
    Paragraph p = new Paragraph("Testing of math symbols \u2208, \u2229, \u2211, \u222b, \u2206").setFont(font);
    doc.add(p);
    doc.close();
}

The result looks like this:

Symbols in a PDF file

Symbols in a PDF file

Click How to print mathematical characters like ∈, ∩, ∑, ∫, ? √, ∠? if you want to see how to answer this question in iText 5.