How to make Cyrillic characters display correctly when converting to PDF with itextpdf?

3k views Asked by At

Does any body knows how to make itextpdf work with Cyrillic symbols?

I have code: 

 Font normal = FontFactory.getFont(String.valueOf(Font.FontFamily.HELVETICA), "CP1251", false, 13);
 Document doc = new Document(PageSize.A4, 36, 36, 36, 65);
 Paragraph paragraph = new Paragraph("ЗАПИСЬ!!!", normal);
 doc.add(paragraph);

I saw that CP1251 works good BUT for a single char -while for texts - ("ЗАПИСЬ" in my example). And it displays all the chars overlapped onto each other.

What is wrong with my code? Thnx!

1

There are 1 answers

1
e5d3e1 On BEST ANSWER

You can download font source from network (http://fonts4web.ru/Helvetica.html#test).

Save font in your resource directory.

Act as it is in example bellow:

public class HelloWorld {

    /** Path to the resulting PDF file. */
    public static final String RESULT = "results/hello.pdf";
    public static final String FONT = "fonts/HelveticaRegular.ttf";

    /**
     * Creates a PDF file: hello.pdf
     * @param    args    no arguments needed
     */
    public static void main(String[] args)
            throws DocumentException, IOException {
        new HelloWorld().createPdf(RESULT);
    }

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException
     * @throws    IOException
     */
    public void createPdf(String filename)
            throws DocumentException, IOException {
        Font font = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, true);

        Document document = new Document();

        PdfWriter.getInstance(document, new FileOutputStream(filename));

        document.open();

        document.add(new Paragraph("Hello World! Ты можешь использовать кирилицу.", font));

        document.close();
    }
}