記錄 Apache PDFBox 的簡單使用,以及解決遇到的各種問題。
用 Apache PDFBox 來生成PDF文件,此文是簡單的一個Demo,並記錄首次使用時遇到的問題,更多高級用法,請參考官網。
1. Maven配置依賴
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.17</version>
</dependency>
2. 使用PDFBox API創建pdf對象
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream pageContent = new PDPageContentStream(doc, page);
pageContent.beginText();
//加載宋體ttf,支持中文
File fontFile = new File(this.getClass().getResource("/").getPath() + "fonts/SIMFANG.TTF");
PDType0Font font = PDType0Font.load(doc, fontFile);
pageContent.setFont(font, 20);
//行間距
pageContent.setLeading(20);
//新行的偏移量
pageContent.newLineAtOffset(45, PDRectangle.A4.getHeight() - 90);
pageContent.showText("字段名稱-1: 字段值");
pageContent.newLine();
pageContent.showText("字段名稱-2 : 111111111");
pageContent.newLine();
pageContent.endText();
//必須關
pageContent.close();
//保存本地
doc.save("/test/test.pdf");
//如果你要上傳到文件服務器,可以直接用下面這種方式獲取InputStream
//ByteArrayOutputStream out = new ByteArrayOutputStream();
//doc.save(out);
//ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
doc.close();
3. 生成PDF效果圖

4. 期間遇到的幾個問題以及解決方法
4.1 ('.notdef') is not available in this font Courier-Bold encoding: WinAnsiEncoding
U+59D3 ('.notdef') is not available in this font Courier-Bold encoding: WinAnsiEncoding
方式一、服務器安裝中文字體
請自行搜索.... 沒采用這種原因主要是嫌麻煩,需要在每台服務器去安裝,雖然可以搞個腳本之類批量進行安裝。
方式二、代碼手動加載宋體ttf文件
把ttf放到resource目錄下,打包到jar/war中
SIMFANG.TTF 可以在Windows系統的C盤上找到,如果是Mac用戶可以找Windows的要一個
File fontFile = new File(Objects.requireNonNull(this.getClass().getResource("/")).getPath() + "fonts/SIMFANG.TTF");
PDType0Font font = PDType0Font.load(doc, fontFile);
4.2 head is mandatory
由於打包時,ttf文件貌似被編譯了,也就是破壞了ttf的內容,導致解析ttf失敗。解決方法是不對ttf文件做編譯。
java.io.IOException: head is mandatory
at org.apache.fontbox.ttf.TTFParser.parseTables(TTFParser.java:182)
at org.apache.fontbox.ttf.TTFParser.parse(TTFParser.java:150)
at org.apache.fontbox.ttf.TTFParser.parse(TTFParser.java:87)
at org.apache.pdfbox.pdmodel.font.PDType0Font.load(PDType0Font.java:67)
方式一、 使用maven-assembly-plugin方式
<fileSet>
<directory>src/main/resources</directory>
<excludes>
<exclude>fonts/*</exclude> <!-- 打包時暫時排除掉 fonts/*.ttf-->
</excludes>
<outputDirectory>/conf</outputDirectory>
<filtered>true</filtered> <!-- 會做maven的properties的屬性替換 -->
</fileSet>
<fileSet>
<directory>src/main/resources</directory>
<includes>
<include>fonts/*</include> <!-- 單獨對fonts/*.ttl 做打包 -->
</includes>
<outputDirectory>/conf</outputDirectory>
<filtered>false</filtered> <!-- 不會做替換 -->
</fileSet>
方式二、使用maven-resources-plugin方式
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
