- 引入pdf操作相关pom
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
- 具体代码
@RequestMapping(params = "fileToImg")
public void fileToImg(String ossPath, HttpServletResponse response) {
//endpoint、accessKeyId、secretAccessKey需要改为自己的配置
OSS ossClient = new OSSClientBuilder().build(OssConfig.endpoint.getName(), OssConfig.accessKeyId.getName(), OssConfig.accessKeySecret.getName());
OSSObject object = ossClient.getObject(OssBucketEnum.BASEWEB.getBucketName(), ossPath);
try (PDDocument load = PDDocument.load(object.getObjectContent())) {
PDFRenderer pdfRenderer = new PDFRenderer(load);
int resolution = 300;
ImageType type = ImageType.RGB;
List<BufferedImage> bufferedImages = Lists.newArrayList();
for (int i = 0; i < load.getNumberOfPages(); i++) {
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, resolution, type);
bufferedImages.add(bufferedImage);
}
BufferedImage image = new BufferedImage(bufferedImages.stream().map(BufferedImage::getWidth).max(Comparator.naturalOrder()).orElse(0),
bufferedImages.stream().map(BufferedImage::getHeight).reduce(Integer::sum).orElse(0), BufferedImage.TYPE_INT_RGB);
//将多张图片拼接成一张长图
Graphics2D graphics = image.createGraphics();
//每张图片绘画的起始高度
int currentHeight = 0;
for (BufferedImage bufferedImage : bufferedImages) {
graphics.drawImage(bufferedImage, 0, currentHeight, null);
currentHeight += bufferedImage.getHeight();
}
graphics.dispose();
response.setContentType("image/png");
//返回文件名称处理
String ossFileName = ossPath.split("/")[1];
String fileName=URLUtil.encode(ossFileName.substring(0,ossFileName.lastIndexOf("."))+".png");
response.setHeader("Content-Disposition", "attachment; filename="+ fileName);
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
Optional.of(ossClient).ifPresent(OSS::shutdown);
}
}
标签:load,java,image,bufferedImage,BufferedImage,new,一整张,bufferedImages,图片
From: https://www.cnblogs.com/wyxazgye/p/18197487