欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springMVC将PDF转换成图片

程序员文章站 2022-04-11 10:21:52
...

springMVC将PDF转换成图片

  1. maven代码
       <dependency>
           <groupId>org.apache.pdfbox</groupId>
           <artifactId>pdfbox</artifactId>
           <version>2.0.13</version>
       </dependency>
  1. java代码
@RequestMapping(value = "/file-to-img", method = RequestMethod.GET)
public ResponseEntity<byte[]> fileToImg(String pdfFile) throws IOException {
   
   if (StringUtils.isBlank(pdfFile)) {
   	return new ResponseEntity<>(HttpStatus.NOT_FOUND);
   }
   try (PDDocument pdDocument = PDDocument.load(new File(pdfFile)) {
   	PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
   	for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {
   		BufferedImage image = pdfRenderer.renderImageWithDPI(i, 96f);
   		if (image != null) {
   			images.add(image);
   		}
   	}
   }
   // 拼接图片
   int width = 0, height = 0;
   for (BufferedImage image : images) {
   		width = image.getWidth() > width ? image.getWidth() : width;
   		height += image.getHeight();
   }
   BufferedImage pdfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2d = pdfImage.createGraphics();
   height = 0;
   for (BufferedImage image : images) {
   		g2d.drawImage(image, (width - image.getWidth()) / 2, height, image.getWidth(), image.getHeight(), null);
   		height += image.getHeight();
   }
   g2d.dispose();
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.IMAGE_JPEG);
   try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
   		ImageIO.write(pdfImage, "jpg", os);
   		return new ResponseEntity<>(os.toByteArray(), headers, HttpStatus.OK);
   }
}