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