软件编程
位置:首页>> 软件编程>> java编程>> java实现PDF转图片的方法

java实现PDF转图片的方法

作者:Ice166  发布时间:2021-05-24 04:29:59 

标签:java,PDF,图片

本文实例为大家分享了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);
}

}

来源:https://blog.csdn.net/Ice166/article/details/81169591

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com