您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)java怎么實現(xiàn)pdf文件截圖的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
具體如下:
最近做的一個網(wǎng)站中,有個需求是上傳pdf文件,顯示pdf的封頁,點擊封頁之后進(jìn)行在線閱讀,這里使用的是PDFRender對pdf進(jìn)行截圖。
public static boolean createScreenShoot(String source, String target) { File file = new File(source); if (!file.exists()) { System.err.println("路徑[" + source + "]對應(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; }
另外如果需要在線顯示pdf的話,需要設(shè)置響應(yīng)頭
response.setContentType("application/pdf");
關(guān)于“java怎么實現(xiàn)pdf文件截圖的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。