java使用renderer将pdf按页转换为图片
项目中遇到了需要把用户上传的word,execl,ppt每页截图保存。需要先用到jacob把资源转换为pdf,在通过pdf-renderer把每页截图下来。
首先下载相关jar包:下载地址
importjava.awt.Image;
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.FileChannel;
importjava.security.AccessController;
importjava.security.PrivilegedAction;
//如果com.sun.image找不到,就是Eclipse默认把这些受访问限制的API设成了ERROR。只要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的DeprecatedandrestrictedAPI中的Forbiddenreferences(accessrules)选为Warning就可以编译通过
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;
publicclasspdfToImage{
publicstaticvoidmain(String[]args){
Stringinstructiopath="E:/临时文件1.pdf";
Stringpicturepath="E:/临时文件1/";
changePdfToImg(instructiopath,picturepath);
}
publicstaticintchangePdfToImg(Stringinstructiopath,Stringpicturepath){
intcountpage=0;
try{
//instructiopath="D:/instructio/2015-05-16/Android4编程入门经典.pdf"
//picturepath="D:/instructio/picture/2015-05-16/";
Filefile=newFile(instructiopath);
RandomAccessFileraf=newRandomAccessFile(file,"r");
FileChannelchannel=raf.getChannel();
MappedByteBufferbuf=channel.map(FileChannel.MapMode.READ_ONLY,
0,channel.size());
PDFFilepdffile=newPDFFile(buf);
//创建图片文件夹
Filedirfile=newFile(picturepath);
if(!dirfile.exists()){
dirfile.mkdirs();
}
//获得图片页数
countpage=pdffile.getNumPages();
for(inti=1;i<=pdffile.getNumPages();i++){
PDFPagepage=pdffile.getPage(i);
Rectanglerect=newRectangle(0,0,((int)page.getBBox()
.getWidth()),((int)page.getBBox().getHeight()));
intn=2;
/**图片清晰度(n>0且n<7)【pdf放大参数】*/
Imageimg=page.getImage(rect.width*n,rect.height*n,
rect,/**放大pdf到n倍,创建图片。*/
null,/**nullfortheImageObserver*/
true,/**fillbackgroundwithwhite*/
true/**blockuntildrawingisdone*/
);
BufferedImagetag=newBufferedImage(rect.width*n,
rect.height*n,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img,0,0,rect.width*n,
rect.height*n,null);
/**
*Fileimgfile=newFile("D:\\work\\mybook\\FilesNew\\img\\"+
*i+".jpg");if(imgfile.exists()){
*if(imgfile.createNewFile()){System.out.println("创建图片:"+
*"D:\\work\\mybook\\FilesNew\\img\\"+i+".jpg");}else{
*System.out.println("创建图片失败!");}}
*/
FileOutputStreamout=newFileOutputStream(picturepath+"/"+i
+".png");
/**输出到文件流*/
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParamparam2=encoder.getDefaultJPEGEncodeParam(tag);
param2.setQuality(1f,true);
/**1f~0.01f是提高生成的图片质量*/
encoder.setJPEGEncodeParam(param2);
encoder.encode(tag);
/**JPEG编码*/
out.close();
}
channel.close();
raf.close();
/*unmap(buf);*///pdf转化成图片后,释放MappedByteBuffer资源。调用unmap(buf);无效。
/**如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法*/
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returncountpage;
}
@SuppressWarnings("unchecked")
publicstaticvoidunmap(finalObjectbuffer){
AccessController.doPrivileged(newPrivilegedAction(){
publicObjectrun(){
try{
MethodgetCleanerMethod=buffer.getClass().getMethod(
"cleaner",newClass[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleanercleaner=(sun.misc.Cleaner)getCleanerMethod
.invoke(buffer,newObject[0]);
cleaner.clean();
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
});
}
}
成功释放MappedByteBuffer资源
Methodm=FileChannelImpl.class.getDeclaredMethod("unmap",
MappedByteBuffer.class);
m.setAccessible(true);
m.invoke(FileChannelImpl.class,buf);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。