java实现将pdf变成一张图片在页面显示
1.需求:
由于pdf传输到前台显示不了,因此要在后台将pdf转成图片,然后输出到页面上
使用的是pdfbox
2.在pom.xml中添加如下依赖:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
2.接口
// 设定输出的类型
private static final String JPG = "image/jpeg;charset=GB2312";
public static final float DEFAULT_DPI = 105;
/**
* 查看合同附件
*
* @param fileName
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = { "/viewPdf/{fileName:.+}" }, method = RequestMethod.GET)
public void viewPdf(@PathVariable String fileName, final HttpServletResponse request,
final HttpServletResponse response) throws Exception {
// String ext = StringUtils.substringAfterLast(fileName, ".");
String path = saveUploadContractAttachPath + fileName;
logger.debug(path);
File file = new File(path);
if (!file.exists()) {
return;
}
response.reset(); // 非常重要
response.setContentType(JPG);
// if ("pdf".equalsIgnoreCase(ext)) {
// response.setContentType(PDF);
// }
OutputStream out = response.getOutputStream();
// IOUtils.write(FileUtils.readFileToByteArray(file), out);
// 图像合并使用参数
int width = 0; // 总宽度
int[] singleImgRGB; // 保存一张图片中的RGB数据
int shiftHeight = 0;
BufferedImage imageResult = null;// 保存每张图片的像素值
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
// BufferedImage image = null;
for (int i = 0, len = pageCount; i < pageCount; i++) {
// image = renderer.renderImageWithDPI(i, 144);
// ImageIO.write(image, "jpg", file);
BufferedImage image = renderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
int imageHeight = image.getHeight();
int imageWidth = image.getWidth();
if (i == 0) {// 计算高度和偏移量
width = imageWidth;// 使用第一张图片宽度;
// 保存每页图片的像素值
imageResult = new BufferedImage(width, imageHeight * len, BufferedImage.TYPE_INT_RGB);
} else {
shiftHeight += imageHeight; // 计算偏移高度
}
singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
}
doc.close();
ImageIO.write(imageResult, "jpg", out);// 写图片
}