引入pdfbox使用的jar
pdfbox-2.0.8.jar,maven依赖如图:
org.apache.pdfbox pdfbox 2.0.8
切图:按页切图并生成对应的png格式的图片,输出至相应的目录下
/** * pdf切割成图片 * @param url1 //源文件路径 * @param url2 //切割后图片存储路径 * @param contractId //合同模板id * @throws IOException */public static void cutting(String url1, String url2, String contractId) throws IOException{ //将pdf按页生成图片 File file = new File(url1); Rectangle tempReader = null; PdfReader pdfReader = null; PDDocument doc = null; try { String urls = url2+contractId+"/"; File files = new File(urls); if(!files.exists()){ files.mkdirs(); } // 读入PDF pdfReader = new PdfReader(url1); // 计算PDF页码数 int pageCount = pdfReader.getNumberOfPages(); System.out.println(pageCount); doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); // 循环每个页码 for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { tempReader = pdfReader.getPageSize(i); int height = (int)tempReader.getHeight(); int width = (int)tempReader.getWidth(); System.out.println(height+"..."+width); BufferedImage image = renderer.renderImageWithDPI(i-1, 96); // Windows native DPI BufferedImage tempImage = resize(image,width,height); ImageIO.write(tempImage, "PNG", new File(urls+contractId+"_"+i+".png")); } } catch (IOException e) { e.printStackTrace(); }finally{ if(null!=doc){ doc.close(); } if(null!=pdfReader){ pdfReader.close(); } } }
调用重绘图片方法resize(image,width,height)
//限制pdf转换成图片时的大小private static BufferedImage resize(BufferedImage source, int targetW, int targetH) { int type=source.getType(); BufferedImage target=null; double sx=(double)targetW/source.getWidth(); double sy=(double)targetH/source.getHeight(); if(sx>sy){ sx=sy; targetW=(int)(sx*source.getWidth()); }else{ sy=sx; targetH=(int)(sy*source.getHeight()); } if(type==BufferedImage.TYPE_CUSTOM){ ColorModel cm=source.getColorModel(); WritableRaster raster=cm.createCompatibleWritableRaster(targetW, targetH); boolean alphaPremultiplied=cm.isAlphaPremultiplied(); target=new BufferedImage(cm,raster,alphaPremultiplied,null); }else{ target=new BufferedImage(targetW, targetH,type); } Graphics2D g=target.createGraphics(); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy)); g.dispose(); return target; }