iText : Unable to print mathematical characters li

2019-01-09 19:46发布

问题:

I am using iText 4.0.2 version for pdf generation. I have some characters/symbols to print like ∈, ∩, ∑, ∫, ∆ (Mathematical symbols) and many others. 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();
        writer.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 and generating the pdf file. In place of symbols I tried putting unicode characters in str for the symbols but It didn't worked as well.

回答1:

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

Important: you should always use the most recent, official version of iText. iText 4.0.2 is not an official version.



标签: itext