Search code examples
javahtmlcharacter-encodingspecial-characterspdf-writer

pdfwriter doesn't translate special characters


I have HTML file with an external CSS. I want to create PDF from the HTML file, but the endcoing doesn't work. HTML file works fine, but after transfering to PDF, some characters in PDF are missing. (čřě...) It happens even if I set the Charset in PDFWriter constructor.

How do I solve this, please?

 public void createPDF() {
    try {

        Document document = new Document();


        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(username + ID + ".pdf"));

        document.open();
        String hovinko = username + ID + ".html";

        XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(hovinko), Charset.forName("UTF-8"));

        document.close();

        System.out.println("PDF Created!");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Solution

  • Did you try to convert your special characters before writing them to your PDF?

    yourHTMLString.replaceAll(oldChar, newChar);
    

    ć = ć
    ř = ř
    ě = ě

    If you need more special characters, visit this link.

    EDIT: Then try this out, it worked for me:

    BaseFont basefont = BaseFont.createFont("C:/Windows/Fonts/ARIAL.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font font = new Font(basefont, 12);
                document.add(new Paragraph("čřě", font));