简体   繁体   中英

how to handle with writing to pdf file chinese characters

i am trying to get text from properties file that he is coded in utf-8 and write it in to a PDF file using document object in java .

Document document = new Document();
File file = new File(FILES_PATH + ".pdf");
FileOutputStream fos = new FileOutputStream(file);
PdfWriter.getInstance(document, fos);
.
.
.
pdfTable table;
document.add(table);
document.close();

when i get just the value from property is ignores Chinese characters . when i try to encode the string instead Chinese characters i get strange words or "?".

tried to code it in utf-8 , iso-8859-1 , gbk or gb3212.

need help that PDF file will be able to get Chinese characters

It will not work that way.

In order to display Unicode character in PDF, that is not in build-in PDF fonts, you need to specify custom font for the text frangment and create the separate fragment for each text fragment, that is covered by given font. You need also to embed the used fonts into PDF document (so please consider, if the licence for the fonts you use enables distributing them).

So each String could be rendered using many fonts. But iText has the class FontSelector , that does that task:

FontSelector selector = new FontSelector();

BaseFont bf1 = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
bf1.setSubset(true);
Font font1 = new Font(baseFont, 12, Font.BOLD);
selector.addFont(font1);
// ... do that with all fonts you need

Phrase ph = selector.process(TEXT);
document.add(new Paragraph(ph));

More complex example you can find in my article: Using dynamic fonts for international texts in iText

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