Use FileOutputStream to Create a UTF-8 PDF File

4.4k views Asked by At

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

3

There are 3 answers

3
MoienGK On BEST ANSWER

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!

4
Stephen C On

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.

0
Nux On

Or you can just use the font extension that provides DejaVu fonts: https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports-fonts

Fonts in current version (6.21.0):

  • DejaVu: DejaVu Sans, DejaVu Sans Condensed, DejaVu Serif, DejaVu Serif Condensed, DejaVu Sans Mono
  • Other: SansSerif, Serif, Monospaced, JasperReports Icons, Pictonic

Then you can use the fonts in styles or use one of them as default. You don't need fonts.xml and all that stuff.

You just need dynamicreports-defaults.xml in your resources:

<DynamicReports>
      <!-- DEFAULT FONT -->
      <font fontName="DejaVu Sans" fontSize="10"/>
</DynamicReports>