本文实例为大家分享了 java 实现pdf转 图片 的具体代码,供大家参考,具体内容如下
1.首先利用maven引入所需jar包
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupid>org.apache.pdfbox</groupid> <artifactid>fontbox</artifactid> <version> 2.0 . 1 </version> </dependency> <dependency> <groupid>org.apache.pdfbox</groupid> <artifactid>pdfbox</artifactid> <version> 2.0 . 1 </version> </dependency> |
2.这是本人自己写的一个工具类,有两个方法,一个是获取pdf总页码,一个是通过传过来的page把对应的pdf转成指定格式的图片,并通过流的方式响应给客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
public class pdftoimgutil {
private static logger logger = loggerfactory.getlogger(pdftoimgutil. class );
/** * 获取pdf总页数 * @throws ioexception */ public static int getpdfnum(string fileurl) throws ioexception { pddocument pddocument = null ; int pages = 0 ; try { pddocument = getpddocument(fileurl); pages = pddocument.getnumberofpages(); } catch (exception e) { e.printstacktrace(); logger.error(e.getmessage(),e); } finally { if (pddocument != null ) { pddocument.close(); } } return pages; }
/** * pdf转图片 根据页码一页一页转 * @throws ioexception * imgtype:转换后的图片类型 jpg,png */ public static void pdftoimg(outputstream sos,string fileurl, int page,string imgtype) throws ioexception { pddocument pddocument = null ; /* dpi越大转换后越清晰,相对转换速度越慢 */ int dpi = 100 ; try { pddocument = getpddocument(fileurl); pdfrenderer renderer = new pdfrenderer(pddocument); int pages = pddocument.getnumberofpages(); if (page <= pages && page > 0 ) { bufferedimage image = renderer.renderimagewithdpi(page,dpi); imageio.write(image, imgtype, sos); } } catch (exception e) { e.printstacktrace(); logger.error(e.getmessage(),e); } finally { if (pddocument != null ) { pddocument.close(); } }
}
private static pddocument getpddocument(string fileurl) throws ioexception { file file = new file(fileurl); fileinputstream inputstream = new fileinputstream(file); return pddocument.load(inputstream); }
} |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://blog.csdn.net/Ice166/article/details/81169591