java如何将pdf转换成image
本文实例为大家分享了java将pdf转换image的具体代码,供大家参考,具体内容如下
首先使用了使用了apache的PDFBox组件1.8.4版本
packagepdf; importjava.awt.image.BufferedImage; importjava.io.File; importjava.io.IOException; importjava.util.Date; importjava.util.List; importjavax.imageio.ImageIO; importorg.apache.pdfbox.pdmodel.PDDocument; importorg.apache.pdfbox.pdmodel.PDPage; publicclassPDFBox{ @SuppressWarnings("rawtypes") publicstaticvoidmain(String[]args)throwsIOException{ Stringp=System.getProperty("user.dir")+"/"+"zk.pdf"; PDDocumentdoc=PDDocument.load(p); intpageCount=doc.getNumberOfPages(); System.out.println(pageCount); Datestart=newDate(); try{ Listpages=doc.getDocumentCatalog().getAllPages(); for(inti=0;i"+(i+1)); } }catch(Exceptione){ e.printStackTrace(); }finally{ if(doc!=null){ doc.close(); } } Dateend=newDate(); System.out.println(end.getTime()-start.getTime()); System.out.println("over"); } }
但是其问题在于问题:
当PDF文档为180M大小时直接报解析异常
当PDF页数为500多页时处理非常慢
其后尝试使用了pdf-renderer1.0.5版本
packagepdf; importjava.awt.Image; importjava.awt.Rectangle; importjava.awt.image.BufferedImage; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.RandomAccessFile; importjava.nio.MappedByteBuffer; importjava.nio.channels.FileChannel; importcom.sun.image.codec.jpeg.JPEGCodec; importcom.sun.image.codec.jpeg.JPEGEncodeParam; importcom.sun.image.codec.jpeg.JPEGImageEncoder; importcom.sun.pdfview.PDFFile; importcom.sun.pdfview.PDFPage; publicclassPDFRenderer{ publicstaticvoidmain(String[]args)throwsIOException{ StringpdfRealePath=System.getProperty("user.dir")+"/"+"zk.pdf"; Filefile=newFile(pdfRealePath); RandomAccessFileraf=newRandomAccessFile(file,"r"); FileChannelchannel=raf.getChannel(); MappedByteBufferbuf=channel.map(FileChannel.MapMode.READ_ONLY, 0,channel.size()); PDFFilepdffile=newPDFFile(buf); for(inti=1;i<=pdffile.getNumPages();i++){ PDFPagepage=pdffile.getPage(i); Rectanglerect=newRectangle(0,0,((int)page.getBBox() .getWidth()),((int)page.getBBox().getHeight())); Imageimg=page.getImage(rect.width,rect.height,rect,null,true,true); BufferedImagetag=newBufferedImage(rect.width,rect.height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(img,0,0,rect.width,rect.height,null); FileOutputStreamout=newFileOutputStream("img"+File.separator+(i+1)+".jpg");//输出到文件流 JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out); JPEGEncodeParamparam2=encoder.getDefaultJPEGEncodeParam(tag); param2.setQuality(1f,false);//1f是提高生成的图片质量 encoder.setJPEGEncodeParam(param2); encoder.encode(tag);//JPEG编码 out.close(); System.out.println("imageinthepage-->"+(i+1)); } } }
但是其问题在于问题:当pdf的版本不为1.4时,直接报错:Expected'xref'atstartoftable
pdfbox与pdfrenderer相比较来说,转换的效率要低得多。200页左右的pdf花费的时间是后者的6倍左右。同时,对于中文字体的支持存在些问题。
但是对于却不存在pdf版本不同无法转换的问题。
pdfrenderer不能转换1.4以上版本,查找了解决办法但是没有找到。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。