Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use FileOutputStream to Create a UTF-8 PDF File

I am using JasperReports and DynamicReports with this piece of java code to create a report in pdf format which contains utf-8 characters, the problem is generated pdf file does not contain utf-8 characters at all, like if they have been replaced with "". is there any thing that i should be aware of when using OutputStream to create a utf-8 file?

    public void toPdf(String path){
        OutputStream outHtml;
        try {
            outHtml = new FileOutputStream(path);

            jasperBuilder.toPdf(outHtml);
        } catch (Exception e1) {
            logger.error("failed to create PDF", e1);
        }
}

this may be notable that creating XLS and HTML file faces no such problem.

note that there are lots of lines of code under jasperBuilder.toPdf(outHtml); that i have traced and no where in those lines my utf-8 characters are being eliminated. so i guess the devil is in outHtml = new FileOutputStream(path);

like image 360
MoienGK Avatar asked Mar 21 '23 07:03

MoienGK


1 Answers

I managed to solve it. It was a font and encoding problem. Just followed tutorial here, but change <pdfEncoding>UTF-8</pdfEncoding> to <pdfEncoding>Identity-H</pdfEncoding> in fonts.xml

<fontFamilies>
  <fontFamily name="FreeUniversal">
    <normal>/home/moien/tahoma.ttf</normal>
    <bold>/home/moien/tahoma.ttf</bold>
    <italic>/home/moien/tahoma.ttf</italic>
    <boldItalic>/home/moien/tahoma.ttf</boldItalic>
    <pdfEncoding>Identity-H</pdfEncoding>
    <pdfEmbedded>true</pdfEmbedded>
  </fontFamily>
</fontFamilies> 

Now I have another challenge to solve, making font URL relative!

like image 129
MoienGK Avatar answered Apr 01 '23 00:04

MoienGK