@Test
public void testPdf2JPG() {
PDDocument pdDocument = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
File file = new File("/Users/hanfeng/Downloads/11.pdf");
if (file.isFile()) {
pdDocument = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* dpi越大转换后越清晰,相对转换速度越慢 */
int pages = pdDocument.getNumberOfPages();
BufferedImage destImage = null;
int startHeight = 0;
for (int i = 0; i < pages; i++) {
logger.info("开始截取并上传第" + i + "张图片");
BufferedImage image = renderer.renderImageWithDPI(i, 200);
int width = image.getWidth();
int height = image.getHeight();
logger.info("width:{}, height:{}", width, height);
if (Objects.isNull(destImage)) {
destImage = new BufferedImage(width, height * pages, BufferedImage.TYPE_INT_RGB);
}
int[] imageArrange = new int[width * height];
imageArrange = image.getRGB(0, 0, width, height, imageArrange,
0, width);
destImage.setRGB(0, startHeight, width, height, imageArrange, 0, width);
startHeight += height;
}
byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(destImage, JPG, byteArrayOutputStream);
File dstFile = new File("/Users/hanfeng/Downloads/" + IdGen.uuid() + "." + JPG);//输出磁盘目录
ImageIO.write(destImage, JPG, dstFile);//输出磁盘
//
// ResultDO<String> result = ZaUploadManager.uploadFile(UploadConstant.Systype.CLS, UploadConstant.FileNamespace.SECONDHAND_CAR,
// byteArrayOutputStream.toByteArray(), IdGen.uuid() + "." + JPG, "bss");
// if (result.isSuccess() == false) {
// throw new BizException("文件上传失败[" + result.getMsg() + "]");
// }
//
// logger.info("上传图片返回的消息:" + result.getMsg() + "---上传图片返回的地址:" + result.getModule());
}
} catch (Exception e) {
logger.error("pdf文件转图片出错:", e);
} finally {
try {
if (!Objects.isNull(byteArrayOutputStream)) {
byteArrayOutputStream.close();
}
if (!Objects.isNull(pdDocument)) {
pdDocument.close();
}
} catch (IOException e) {
logger.error("error:{}", e);
}
}
}