Erkan Erol
Erkan Erol

Reputation: 1354

Custom font works in Windows but not in Ubuntu when converting html to pdf with itext

I try to show UTF-8 characters (Ş,Ğ etc.) in converted pdf files from html. I have read many Q&A and wrote the code below. It works in my local machine (Windows) but doesn't work in test server (Ubuntu). The font is not used in test server and some characters are missing. What is the problem?

My html file uses a font that doesn't exist in windows and ubuntu.

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
        * { font-family:'Hickory Jack'; }
    </style>
</head>

Java Method: It takes htmlText and returns bytes of pdf file.

public static byte[] convertHtmlToPdf(String htmlText) throws Exception{        
        String fontPath = PdfConverter.class.getResource("/fonts/").getPath();
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(fontPath, null);
        FontFactory.setFontImp(fontImp);


        ByteArrayOutputStream output = new ByteArrayOutputStream();
        InputStream is = new ByteArrayInputStream(htmlText.getBytes("UTF-8"));


        Document document = new Document();  
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();


        XMLWorkerHelper xmlWorkerHelper = XMLWorkerHelper.getInstance();         
        xmlWorkerHelper.parseXHtml(writer, document, is, Charset.forName("UTF-8"),fontImp);

        document.close();

        byte[] bytes = output.toByteArray();
        output.close();     

        return bytes;
    }

Upvotes: 3

Views: 470

Answers (1)

Erkan Erol
Erkan Erol

Reputation: 1354

The problem is actually a path problem. Full path of resource file is not valid as a font path. I change the font provider part like this and it works.

    XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
    fontImp.register("/fonts/Hickory-Jack.ttf");
    fontImp.setUseUnicode(true);

    FontFactory.setFontImp(fontImp);

Upvotes: 1

Related Questions