java实现PDF转图片 java实现PDF转图片的方法
Ice166 人气:21.首先利用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); } }
加载全部内容