简体   繁体   中英

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);

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!

A FileOutputStream is completely agnostic of the "stuff" that gets written to it. It just writes bytes. If characters are being eliminated or mangled, then this is being caused by whatever is generating the bytes to be written to the stream.

In this case, my money would be on the way that you have configured / used the jasperBuilder object prior to running this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM