本文實例為大家分享了java實現PDF轉圖片的具體代碼,供大家參考,具體內容如下
1.首先利用maven引入所需jar包
<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轉成指定格式的圖片,并通過流的方式響應給客戶端
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); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選