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);
	}
	
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值