将pdf格式的文件转换成图片
1 public class PdfToImage { 2 3 private static String UPLOAD_DIR = "upload" + File.separator; 4 5 /** 6 * 获取上传的文件 7 * @param uploadPath 8 * @param file 9 * @return 10 */ 11 private static File getUploadCalendarFile(String uploadPath,MultipartFile file) 12 { 13 File path = new File(uploadPath); 14 if(!path.exists()) 15 path.mkdirs(); 16 String fileName = file.getOriginalFilename(); 17 String ext = fileName.substring(fileName.lastIndexOf(".")); 18 String uploadfileName = UUID.randomUUID().toString(); 19 uploadfileName = uploadfileName.replace("-", ""); 20 uploadfileName = uploadfileName + ext; 21 String pdfpath = uploadPath+uploadfileName; 22 File convFile = new File( pdfpath); 23 try { 24 file.transferTo(convFile); 25 } catch (IllegalStateException e) { 26 e.printStackTrace(); 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 return convFile; 31 } 32 /** 33 * 34 * @param pdfPath:pdf的路径 35 * @param filePath:存放图片的路径 36 * @return 37 */ 38 public static String getPdfToImagePath(HttpServletRequest request,MultipartFile mulfile) { 39 try { 40 ServletContext contx = request.getSession().getServletContext(); 41 String savePath = contx.getRealPath("/") + UPLOAD_DIR; 42 File pdfPath = getUploadCalendarFile(savePath,mulfile); 43 if(null != pdfPath && pdfPath.exists()) 44 { 45 String pdfUploadName = pdfPath.getName(); 46 pdfUploadName = pdfUploadName.substring(0,pdfUploadName.lastIndexOf(".")); 47 //如果图片存放的路径不存在,则创建 48 String imgPicPaths = savePath + File.separator + pdfUploadName; 49 File file = new File(imgPicPaths); 50 if(!file.exists()) 51 file.mkdirs(); 52 //将pdf 转换成多张图片,图片名称按数字进行保存 53 int iImageCount = convertPdfToImage(pdfPath,imgPicPaths); 54 //如果正确读取pdf,图片的个数根据pdf的页数来判断 55 if(iImageCount > 0) 56 { 57 //读取filePath,图片路径下的第一张图片 58 String firstImg = imgPicPaths + File.separator + "1.png"; 59 File fileFirst=new File(firstImg); 60 if(fileFirst.exists()) 61 { 62 String outPath = savePath + File.separator + pdfUploadName + ".png"; 63 //将生成的多张图片合并 64 File oneImgPath = mergeImage(firstImg,iImageCount,imgPicPaths,outPath); 65 if(null != oneImgPath && oneImgPath.exists()) 66 { 67 //将生成的图片进行大小限制:设定宽度最大为900 68 ImageFixSizeUtil.compressImage(outPath, outPath, CalendarImgSizeEnum.MAXLENGTH.getiValue()); 69 return outPath; 70 } 71 } 72 }else 73 { 74 if(file.exists() && file.isDirectory()) 75 { 76 //删除目录文件夹 77 FileUtils.deleteDirectory(file); 78 if(pdfPath.exists()) 79 pdfPath.delete(); 80 } 81 } 82 } 83 84 } catch (Exception e) { 85 e.printStackTrace(); 86 } 87 return null; 88 } 89 90 /** 91 * 读取pdf文件, 生成图片,然后将图片合并 92 * 93 * @return 94 */ 95 private static int convertPdfToImage(File pdfPath, String filePath) { 96 97 RandomAccessFile raf; 98 try { 99 raf = new RandomAccessFile(pdfPath, "r"); 100 FileChannel channel = raf.getChannel(); 101 MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); 102 PDFFile pdffile = new PDFFile(buf); 103 int iImageNum = 0; 104 for (int i = 1; i <= pdffile.getNumPages(); i++) { 105 PDFPage page = pdffile.getPage(i); 106 Rectangle rect = new Rectangle(0, 0, ((int) page.getBBox().getWidth()), ((int) page.getBBox().getHeight())); 107 Image img = page.getImage(rect.width, rect.height, rect, 108 null, // null 109 true, // fill background with white 110 true // block until drawing is done 111 ); 112 BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB); 113 tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, null); 114 FileOutputStream out = new FileOutputStream(filePath + File.separator + i + ".png"); // 输出到文件流 115 ImageIO.write(tag, "png", out); 116 tag.flush(); 117 out.flush(); 118 out.close(); 119 iImageNum += 1; 120 } 121 channel.close(); 122 raf.close(); 123 unmap(buf);// 如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法 124 //生成图片后,清除pdf文件 125 if(pdfPath.exists()) 126 pdfPath.delete(); 127 return iImageNum; 128 } catch (FileNotFoundException e) { 129 e.printStackTrace(); 130 } catch (IOException e) { 131 e.printStackTrace(); 132 }finally { 133 if(pdfPath.exists()){ 134 pdfPath.delete(); 135 } 136 } 137 return 0; 138 } 139 140 /** 141 * 将生成的图片合并成一张图片 142 * 143 * @param firstImg 144 * @param iPageSize 145 * @param imgPath 146 * @param outPath 147 * @throws IOException 148 */ 149 private static File mergeImage(String firstImg, int iPageSize, String imgPath, String outPath) throws IOException { 150 // 读取第一张图片 151 File fileOne = new File(firstImg); 152 BufferedImage ImageOne = ImageIO.read(fileOne); 153 int width = ImageOne.getWidth();// 图片宽度 154 int height = ImageOne.getHeight();// 图片高度 155 int iYHeight = 0; 156 // 从图片中读取RGB 157 int[] ImageArrayOne = new int[width * height]; 158 ImageArrayOne = ImageOne.getRGB(0, 0, width, height, ImageArrayOne, 0, width); 159 // 生成新图片 160 BufferedImage ImageNew = new BufferedImage(width, height * iPageSize, BufferedImage.TYPE_INT_RGB); 161 ImageNew.setRGB(0, 0, width, height, ImageArrayOne, 0, width);// 设置左半部分的RGB 162 ImageOne.flush(); 163 164 for (int i = 2; i <= iPageSize; i++) { 165 File fileTwo = new File(imgPath + File.separator + String.valueOf(i) + ".png"); 166 BufferedImage ImageTwo = ImageIO.read(fileTwo); 167 int[] ImageArrayTwo = new int[width * height]; 168 ImageArrayTwo = ImageTwo.getRGB(0, 0, width, height, ImageArrayTwo, 0, width); 169 ImageTwo.flush(); 170 iYHeight = (i - 1) * height; 171 ImageNew.setRGB(0, iYHeight, width, height, ImageArrayTwo, 0, width);// 设置右半部分的RGB 172 } 173 ImageNew.flush(); 174 File outFile = new File(outPath); 175 ImageIO.write(ImageNew, "png", outFile);// 写图片 176 //清空文件夹中内容 177 File file = new File(imgPath); 178 //删除目录 179 FileUtils.deleteDirectory(file); 180 return outFile; 181 } 182 183 184 /** 185 * 如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法 186 * 187 * @param buffer 188 */ 189 @SuppressWarnings({ "unchecked", "rawtypes" }) 190 private static void unmap(final Object buffer) { 191 AccessController.doPrivileged(new PrivilegedAction() { 192 public Object run() { 193 try { 194 Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]); 195 getCleanerMethod.setAccessible(true); 196 sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]); 197 cleaner.clean(); 198 } catch (Exception e) { 199 e.printStackTrace(); 200 } 201 return null; 202 } 203 }); 204 } 205 }
版权声明:本文为fuhengheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。