本文实例为大家分享了java实现PDF转图片的具体代码,供大家参考,具体内容如下
1.首先利用maven引入所需jar包
org.apache.pdfbox fontbox2.0.1 org.apache.pdfbox pdfbox2.0.1
2.这是本人自己写的一个工具类,有两个方法,一个是获取PDF总页码,一个是通过传过来的page把对应的pdf转成指定格式的图片,并通过流的方式响应给客户端
public class PDFToImgUtil {
private static Logger logger = LoggerFactory.getLogger(PDFToImgUtil.class);
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;
}
public static void PDFToImg(OutputStream sos,String fileUrl,int page,String imgType) throws IOException {
PDdocument pddocument = null;
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);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



