Apache pdfbox java.io.IOException: The TrueType font null does not contain a 'cmap' table 问题解决

尝试使用Apache pdfbox 添加中文到pdf中,发现出现The TrueType font null does not contain a 'cmap' table,主要原因是遍历pdf页数时调用PDDocument#save 导致清空fontsToSubset,所以报错。

 

 

/**
*错误代码
*/
public
void addPDFEachPageFont(File file) throws IOException{
PDDocument docs = PDDocument.load(file);
Resource resource = new ClassPathResource("fonts/FZYTK.TTF");
PDFont font = PDType0Font.load(docs, resource.getInputStream());
for (int i = 0; i < docs.getNumberOfPages(); i++) {
PDPage page = docs.getPage(i);
PDPageContentStream contentStream = new PDPageContentStream(docs, page, PDPageContentStream.AppendMode.APPEND, false, true);
contentStream.beginText(); contentStream.setFont(font, 12);
contentStream.newLineAtOffset(156, 129);
contentStream.showText(context);
contentStream.endText();
contentStream.close();
docs.save(file); // 在循环中遍历,导致清空fontsToSubset出现报错
}
docs.close
}
/**
* 正确写法  
*/
public void addPDFEachPageFont(File file) throws IOException{
PDDocument docs = PDDocument.load(file);
Resource resource = new ClassPathResource("fonts/FZYTK.TTF");
PDFont font = PDType0Font.load(docs, resource.getInputStream());
for (int i = 0; i < docs.getNumberOfPages(); i++) {
PDPage page = docs.getPage(i);
PDPageContentStream contentStream = new PDPageContentStream(docs, page, PDPageContentStream.AppendMode.APPEND, false, true);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(156, 129);
contentStream.showText(context);
contentStream.endText();
contentStream.close();
}
docs.save(file);
docs.close
}

 

源码解析

遍历所有的字体,进行font.subset() 之后,会清空fontsToSubset。然后再保存到原先的pdf文件中。

字体文件是windwos10 中C:\Windows\Fonts\方正舒体

 

posted @ 2023-02-07 19:39  u清  阅读(741)  评论(0编辑  收藏  举报