Character encoding issues in PDF generation
Czech characters such as "Č" and "Ć" were displayed incorrectly when generating PDFs. This problem stems from a variety of factors, including character encoding and font selection.
Encoding Notes
First of all, it is important to distinguish between the Cyrillic and Latin alphabets used in Central and Eastern European languages. Code pages 1250 and 1251 represent different character encodings for these regions.
Text Encoding Practice
Unicode is the recommended text encoding standard for modern applications. However, saving the code file in plain text may cause data corruption if the encoding is accidentally changed. Consider using u notation to represent special characters instead of including them directly in your code.
Font selection
Helvetica is not suitable for rendering Czech characters. Arial or FreeSans are better choices. Additionally, setting the embed parameter to true ensures that fonts are included in the PDF for consistent rendering across different systems.
Font encoding
When using embedded fonts, you can specify the font encoding. Cp1250 specifies code page 1250 encoding, producing a single-byte representation for each character. Alternatively, IDENTITY_H represents Unicode encoding, which uses multiple bytes per character. For modern standards such as PDF/A and PDF/UA, Unicode encoding is recommended.
Example
The following code demonstrates a solution using FreeSans fonts in Cp1250 and IDENTITY_H encodings:
<code class="language-java">public static void createPdf(String dest) throws IOException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(dest)); document.open(); // Cp1250 编码 Font f1 = FontFactory.getFont("resources/fonts/FreeSans.ttf", "Cp1250", true); Paragraph p1 = new Paragraph("测试字母 \u010c,\u0106,\u0160,\u017d,\u0110", f1); document.add(p1); // Unicode 编码 Font f2 = FontFactory.getFont("resources/fonts/FreeSans.ttf", BaseFont.IDENTITY_H, true); Paragraph p2 = new Paragraph("测试字母 \u010c,\u0106,\u0160,\u017d,\u0110", f2); document.add(p2); document.close(); }</code>
Conclusion
Handling international characters in PDF generation is not an easy task. Proper handling of character encoding and font selection is critical to accurate representation of text.
The above is the detailed content of How Can I Correctly Display Czech Characters (Č, Ć, etc.) When Generating PDFs?. For more information, please follow other related articles on the PHP Chinese website!