本文實例為大家分享了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