我无法使用itext在pdf中打印中文日文字符。 我正在使用xmlWorker将包含中文,日文和韩文字符的HTML转换为单个字符串。但是我在pdf中获得了空格,尽管我使用xmlFontProvider注册了字体。
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();
}
}