終於到了生成自定義證書圖片的最后一步,pdf轉圖片我選擇使用pdfbox庫,以下是工具類:
package com.x.certificate.pdf; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; /** * 用於pdf文件的格式轉換 * @author xuhaojin * @version [版本號, 2020年3月22日] */ public class PdfConverter { public static File toImageUsingPdfbox(String pdfPath, String imagePath, String imageExt) { File out = null; try (PDDocument document = PDDocument.load(new File(pdfPath));) { File imagePathFile = new File(getPath(imagePath)); if (!imagePathFile.exists()) { imagePathFile.mkdirs(); } PDFRenderer pdfRender = new PDFRenderer(document); BufferedImage image = pdfRender.renderImage(0, 2); out = new File(imagePath); ImageIO.write(image, imageExt, out); document.close(); } catch (Exception e) { e.printStackTrace(); } return out; } public static String getPath(String pathName) { if (pathName.endsWith("\\") || pathName.endsWith("/")) { return pathName; } if (pathName.contains("\\")) { return pathName.substring(0, pathName.lastIndexOf('\\') + 1); } return pathName.substring(0, pathName.lastIndexOf('/') + 1); } public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); String pdfPath = "C:\\Users\\a1579\\Desktop\\custom.pdf"; String imagePath = "C:\\Users\\a1579\\Desktop\\custom.jpg"; toImageUsingPdfbox(pdfPath, imagePath, "jpg"); System.out.println("所用時間:" + (System.currentTimeMillis() - startTime) + "ms"); } }
其中使用了pdfbox 2.0.15版本,在<code>BufferedImage image = pdfRender.renderImage(0, 2);</code>這句設置了兩個關鍵參數,第一個是要轉換pdf的頁數,因為我的證書只有一頁,所以只設置0就可以了;第二個參數是設置圖片的scale(規模,清晰度),單位浮點型float,默認值為1(1=72DPI),值設置的越大越清晰,我們希望生成的圖片越清晰越好,但是當我將這個值設置為20時,生成圖片用了10秒左右!,jpg圖片達到了2點多Mb,比原圖還要大,我不得不把清晰度改小一點,即要滿足程序速度和文件大小,還要滿足清晰度,我最終設置為了2。
最終生成圖片效果custom.jpg:
這個圖片只是為了演示,如果實際使用,還需要調節文字位置(docx模板文本框大小、位置),和每一塊的文字大小、字體等內容細節。