How can I test if my font is rendered correctly in pdf?

前端 未结 1 587
难免孤独
难免孤独 2020-11-27 07:44

When using different fonts in jasper report, you need to use font-extensions.

However if the font is not rendered correctly is there a way that I ca

相关标签:
1条回答
  • 2020-11-27 08:34

    Since jasper report use the itext library the easiest way to test if your font will be rendered correctly in pdf is to test it directly with itext.

    Example program*, adapted from iText: Chapter 11: Choosing the right font

    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Font;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.pdf.BaseFont;
    import com.lowagie.text.pdf.ColumnText;
    import com.lowagie.text.pdf.PdfWriter;
    
    public class FontTest {
    
        /** The resulting PDF file. */
        public static final String RESULT = "fontTest.pdf";
        /** the text to render. */
        public static final String TEST = "Test to render this text with the turkish lira character \u20BA";
    
        public void createPdf(String filename) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
            document.open();
            BaseFont bf = BaseFont.createFont(
                "pathToMyFont/myFont.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font font = new Font(bf, 20);
            ColumnText column = new ColumnText(writer.getDirectContent());
            column.setSimpleColumn(36, 730, 569, 36);
            column.addElement(new Paragraph(TEST, font));
            column.go();
            document.close();
        }
    
        public static void main(String[] args) throws IOException, DocumentException {
            new FontTest().createPdf(RESULT);
        }
    }
    

    Some notes (seen in example):

    • To render special characters use it's encoded value example \u20BA to avoid problems of encoding type on your file.
    • Consider to always use Unicode encoding, this is recommended approach in the newer PDF standard (PDF/A, PDF/UA) and gives you the possibility to mix different encoding types, with the only dis-advantage of slightly larger file size.

    Conclusion:

    If your font is rendered correctly in the "fontTest.pdf", you have a problem with your font-extensions in jasper report.

    If you font is not rendered correctly in the "fontTest.pdf", there is nothing you can do in jasper reports, you need to find another font.


    *Latest jasper-reports distribution use a special version itext-2.1.7, the imports in this version is com.lowagie.text, if you are using later version the imports are com.itextpdf.text as in adapted example.

    0 讨论(0)
提交回复
热议问题