Skip to main content
Skip table of contents

How to print mathematical characters like ?, ?, ?, ?, ? ?, ??

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?

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

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's done:

public static final String DEST = "results/fonts/math_symbols.pdf";
public static final String FONT = "resources/fonts/FreeSans.ttf";
public static final String TEXT = "this string contains special characters like this  \u2208, \u2229, \u2211, \u222b, \u2206";

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 f = new Font(bf, 12);
    Paragraph p = new Paragraph(TEXT, f);
    document.add(p);
    document.close();
}

The result looks like this: math_symbols.pdf

Symbols in a PDF file

Symbols in a PDF file

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.