0.前言
可根据需要选择图片质量
1.maven依赖
1 <dependency> 2 <groupId>org.apache.pdfbox</groupId> 3 <artifactId>pdfbox</artifactId> 4 <version>2.0.8</version> 5 </dependency>
2.File工具类
1 import org.apache.commons.codec.binary.Base64; 2 import org.slf4j.Logger; 3 import org.slf4j.LoggerFactory; 4 import java.io.*; 5 import java.math.BigInteger; 6 import java.security.MessageDigest; 7 import java.security.NoSuchAlgorithmException; 8 import java.util.HashMap; 9 import java.util.LinkedHashMap; 10 import java.util.Map; 11 12 public class FileHelper { 13 private static Logger logger = LoggerFactory.getLogger(FileHelper.class); 14 15 /*** 16 * 获取文件基本信息 17 * 18 * @param filePath 19 * @return 20 */ 21 public static Map<String, String> getFileInfo(String filePath) { 22 Map<String, String> fileInfos = new LinkedHashMap<String, String>(); 23 File file = new File(filePath); 24 fileInfos.put("FileName", file.getName()); 25 fileInfos.put("FileLength", String.valueOf(file.length())); 26 return fileInfos; 27 } 28 29 /*** 30 * 获取文件的Bytes 31 * 32 * @param filePath 33 * @return 34 * @throws IOException 35 */ 36 public static byte[] getBytes(String filePath) { 37 File file = new File(filePath); 38 FileInputStream fis = null; 39 byte[] buffer = null; 40 try { 41 fis = new FileInputStream(file); 42 buffer = new byte[(int) file.length()]; 43 fis.read(buffer); 44 fis.close(); 45 } catch (FileNotFoundException e) { 46 e.printStackTrace(); 47 logger.info("获取文件字节流失败:" + e.getMessage()); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 logger.info("获取文件字节流失败:" + e.getMessage()); 51 } finally { 52 try { 53 fis.close(); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 logger.info("FileInputStream 关闭时发生异常:" + e.getMessage()); 57 } 58 } 59 return buffer; 60 } 61 62 /** 63 * 根据byte数组生产文件 64 * 65 * @param fileName 66 * String 文件路径 67 * @throws IOException 68 * @return byte[] 文件内容 69 */ 70 public static Map<String, String> saveFileByStream(byte[] bytes, String folder, String fileName) { 71 Map<String, String> fileResult = new HashMap<String, String>(); 72 BufferedOutputStream bos = null; 73 FileOutputStream fos = null; 74 File file = null; 75 try { 76 File dir = new File(folder); 77 if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在 78 dir.mkdirs(); 79 } 80 file = new File(folder + File.separator + fileName); 81 fos = new FileOutputStream(file); 82 bos = new BufferedOutputStream(fos); 83 bos.write(bytes); 84 fileResult.put("errCode", "0"); 85 fileResult.put("msg", "保存签署后文件成功"); 86 } catch (Exception e) { 87 e.printStackTrace(); 88 logger.info("保存签署后文件失败:" + e.getMessage()); 89 fileResult.put("errCode", "0"); 90 fileResult.put("msg", "保存签署后文件成功"); 91 } finally { 92 if (bos != null) { 93 try { 94 bos.close(); 95 } catch (IOException e1) { 96 e1.printStackTrace(); 97 logger.info("保存签署后文件失败:" + e1.getMessage()); 98 } 99 } 100 if (fos != null) { 101 try { 102 fos.close(); 103 } catch (IOException e1) { 104 e1.printStackTrace(); 105 logger.info("保存签署后文件失败:" + e1.getMessage()); 106 } 107 } 108 } 109 return fileResult; 110 } 111 112 /*** 113 * 获取文件MD5值 114 * 115 * @param filePath 116 * @return 117 * @throws IOException 118 */ 119 public static String getFileMD5(String filePath) { 120 FileInputStream fis = null; 121 BigInteger bigInt = null; 122 try { 123 File file = new File(filePath); 124 fis = new FileInputStream(file); 125 MessageDigest md = MessageDigest.getInstance("MD5"); 126 byte[] buffer = new byte[1024]; 127 int length = -1; 128 while ((length = fis.read(buffer, 0, 1024)) != -1) { 129 md.update(buffer, 0, length); 130 } 131 bigInt = new BigInteger(1, md.digest()); 132 fis.close(); 133 } catch (FileNotFoundException e) { 134 e.printStackTrace(); 135 logger.info(e.getMessage()); 136 } catch (NoSuchAlgorithmException e) { 137 e.printStackTrace(); 138 logger.info(e.getMessage()); 139 } catch (IOException e) { 140 e.printStackTrace(); 141 logger.info(e.getMessage()); 142 } 143 return bigInt.toString(16); 144 } 145 146 /*** 147 * 创建文件夹 148 * 149 * @param folderPath 150 * @return 151 */ 152 public static boolean createDirectory(String folderPath) { 153 boolean isSuccess = false; 154 File file = new File(folderPath); 155 if (!file.exists() && !file.isDirectory()) { 156 file.mkdir(); 157 isSuccess = true; 158 } else { 159 isSuccess = true; 160 } 161 return isSuccess; 162 } 163 164 /*** 165 * 根据图片路径将图片转成Base64数据 166 * 167 * @return Base64数据 168 */ 169 public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 170 171 InputStream in = null; 172 byte[] data = null; 173 // 读取图片字节数组 174 try { 175 in = new FileInputStream(imgFilePath); 176 data = new byte[in.available()]; 177 in.read(data); 178 in.close(); 179 } catch (IOException e) { 180 logger.info("上传的印章图片转sealData错误:" + e.getMessage()); 181 e.printStackTrace(); 182 } 183 // 对字节数组Base64编码 184 byte[] en = Base64.encodeBase64(data); 185 return new String(en);// 返回Base64编码过的字节数组字符串 186 } 187 188 }
3.Pdf工具类
1 import org.apache.pdfbox.pdmodel.PDDocument; 2 import org.apache.pdfbox.rendering.PDFRenderer; 3 import org.slf4j.Logger; 4 import org.slf4j.LoggerFactory; 5 import javax.imageio.ImageIO; 6 import java.awt.image.BufferedImage; 7 import java.io.File; 8 import java.io.IOException; 9 10 public class PDFHelper { 11 private static Logger logger = LoggerFactory.getLogger(PDFHelper.class); 12 /*** 13 * PDF文件转PNG图片,全部页数 14 * 15 * @param PdfFilePath 16 * @param dpi 17 * @return 18 */ 19 public static void pdfToImage(String PdfFilePath, String dstImgFolder, int dpi) { 20 File file = new File(PdfFilePath); 21 PDDocument pdDocument; 22 try { 23 String imgPDFPath = file.getParent(); 24 int dot = file.getName().lastIndexOf('.'); 25 String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名 26 String imgFolderPath = null; 27 if (dstImgFolder.equals("")) { 28 imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径 29 } else { 30 imgFolderPath = dstImgFolder + File.separator + imagePDFName; 31 } 32 33 if (FileHelper.createDirectory(imgFolderPath)) { 34 pdDocument = PDDocument.load(file); 35 PDFRenderer renderer = new PDFRenderer(pdDocument); 36 /* dpi越大转换后越清晰,相对转换速度越慢 */ 37 int pages = pdDocument.getNumberOfPages(); 38 StringBuffer imgFilePath = null; 39 for (int i = 0; i < pages; i++) { 40 String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName; 41 imgFilePath = new StringBuffer(); 42 imgFilePath.append(imgFilePathPrefix); 43 imgFilePath.append("_"); 44 imgFilePath.append(String.valueOf(i + 1)); 45 imgFilePath.append(".png"); 46 File dstFile = new File(imgFilePath.toString()); 47 BufferedImage image = renderer.renderImageWithDPI(i, dpi); 48 ImageIO.write(image, "png", dstFile); 49 } 50 System.out.println("PDF文档转PNG图片成功!"); 51 52 } else { 53 logger.info("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败"); 54 } 55 56 } catch (IOException e) { 57 logger.info("PDF文档转PNG图片异常:" + e.getMessage()); 58 e.printStackTrace(); 59 } 60 } 61 }
4.测试
1 @Test 2 public void pdfToPng() { 3 4 String PdfFilePath = "F:/test.pdf"; 5 String dstImgFolder = "F:/b";//b目录需要事先创建好 6 int dpi = 150; 7 PDFHelper.pdfToImage(PdfFilePath,dstImgFolder,dpi); 8 9 }