本文實(shí)例講述了java實(shí)現(xiàn)pdf文件截圖的方法。分享給大家供大家參考,具體如下:
最近做的一個(gè)網(wǎng)站中,有個(gè)需求是上傳pdf文件,顯示pdf的封頁(yè),點(diǎn)擊封頁(yè)之后進(jìn)行在線(xiàn)閱讀,這里使用的是PDFRender對(duì)pdf進(jìn)行截圖。
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
|
public static boolean createScreenShoot(String source, String target) { File file = new File(source); if (!file.exists()) { System.err.println( "路徑[" + source + "]對(duì)應(yīng)的pdf文件不存在!" ); return false ; } try { RandomAccessFile raf = new RandomAccessFile(file, "r" ); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0 , channel.size()); PDFFile pdffile = new PDFFile(buf); int num = pdffile.getNumPages(); for ( int i = 1 ; i < num; i++){ PDFPage page = pdffile.getPage( 1 ); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle( 0 , 0 , ( int ) page.getBBox() .getWidth(), ( int ) page.getBBox().getHeight()); // generate the image Image img = page.getImage(rect.width, rect.height, // width & rect, // clip rect null , // null for the ImageObserver true , // fill background with white true // block until drawing is done ); BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(img, 0 , 0 , rect.width, rect.height, null ); FileOutputStream out = new FileOutputStream(target+i+ "jpg" ); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); // JPEG編碼 out.close(); } return true ; } catch (Exception e){ e.printStackTrace(); return true ; } |
另外如果需要在線(xiàn)顯示pdf的話(huà),需要設(shè)置響應(yīng)頭
1
|
response.setContentType( "application/pdf" ); |
附:pdfRender.jar點(diǎn)擊此處本站下載。
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.csdn.net/yangnianbing110/article/details/32702437