我无法使用 itext 在 pdf 中打印中文日文字符。我正在使用 xmlWorker 在单个字符串中转换包含中文、日文和韩文字符的 HTML。但是尽管我使用 xmlFontProvider 注册了字体,但我在 pdf 中得到了空格。
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class ParseHtml11 {
public static final String DEST = "cyrillic.pdf";
public static final String HTML = "<html><head> <meta http-equiv='content-type' content='application/xhtml+xml; charset=UTF-8'/></head><body><h4 style='font-family: Arial Unicode MS, FreeSans; font-size:16px; font-weight: normal; ' >Здраво Kristijan!</h4><p>This is chinese language test 测试 </p></body></html>";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
new ParseHtml11().createPdf(DEST);
}
/**
* Creates a PDF with the words "Hello World"
* @param file
* @throws IOException
* @throws DocumentException
*/
public void createPdf(String file) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register("/Users/user/Downloads/MyFonts/FreeSans.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/THSarabunNew.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/Kh-Content.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/THSarabunNew Italic.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/THSarabunNew BoldItalic.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/THSarabunNew Bold.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/arial.ttf");
fontImp.register("/Users/user/Downloads/MyFonts/FreeSans.ttf");
fontImp.register( "/Users/user/Downloads/MyFonts/NotoSansCJKsc-Regular.otf");
fontImp.register( "/Users/user/Downloads/MyFonts/arialuni.ttf");
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream((HTML.toString().getBytes("UTF-8"))), null, Charset.forName("UTF-8"), fontImp);
// step 5
document.close();
}
}