java实现PDF转图片的方法
作者:Ice166
这篇文章主要为大家详细介绍了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);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
