资源描述:
《pdf与图片互相转换代码》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、所需jar包importjava.awt.Rectangle;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.lang.reflect.Method;importjava.nio.MappedByteBuffer;importjava.nio.channels.Fi
2、leChannel;importjava.security.AccessController;importjava.security.PrivilegedAction;importcom.lowagie.text.Document;importcom.lowagie.text.DocumentException;importcom.lowagie.text.pdf.PdfWriter;importcom.sun.image.codec.jpeg.JPEGCodec;importcom.sun.image.codec.jpeg.JPEGEncodeParam;importcom.sun.im
3、age.codec.jpeg.JPEGImageEncoder;importcom.sun.pdfview.PDFFile;importcom.sun.pdfview.PDFPage;publicclassTestPdf{publicstaticvoidmain(String[]args)throwsException{PdfToImg();ImgToPdf();}/***将pdf转成img*/publicstaticvoidPdfToImg(){try{Filefile=newFile("c://PDFbox使用教程.pdf");RandomAccessFileraf=newRandom
4、AccessFile(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().getWid
5、th()),((int)page.getBBox().getHeight()));java.awt.Imageimg=page.getImage(rect.width,rect.height,rect,null,//nullfortheImageObservertrue,//fillbackgroundwithwhitetrue//blockuntildrawingisdone);BufferedImagetag=newBufferedImage(rect.width,rect.height,BufferedImage.TYPE_INT_RGB);tag.getGraphics().dra
6、wImage(img,0,0,rect.width,rect.height,null);FileOutputStreamout=newFileOutputStream("c:\"+i+".jpg");//输出到文件流JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);JPEGEncodeParamparam2=encoder.getDefaultJPEGEncodeParam(tag);param2.setQuality(1f,false);//1f是提高生成的图片质量encoder.setJPEGEncodeParam(pa
7、ram2);encoder.encode(tag);//JPEG编码out.close();}channel.close();raf.close();unmap(buf);//如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();