1. 程式人生 > 其它 >Spring Boot 通過RestTemplat返回pdf轉圖片

Spring Boot 通過RestTemplat返回pdf轉圖片

Springboot 通過 RestTemplat 返回 pdf轉圖片

開發環境:

  • java 8
  • spring boot 2.x
  • 前後端分離

需求:前端傳送pdf檔案路徑來,後端獲取檔案並返回前端

廢話不多說,直接開幹

1、引用依賴

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.16</version>
</dependency>

2、控制層處理

@GetMapping("/readPdfFileImg")
public void readPdfFileImg(HttpServletResponse resp, String path) throws Exception {
	Assert.isTrue(StringUtils.isNotEmpty(path),"檔案路徑不能為空!");
	RestTemplate restTemplate = new RestTemplate();
	ResponseEntity responseEntity = restTemplate.getForEntity(path,byte[].class);
	byte[] body = (byte[]) responseEntity.getBody();
	Assert.isTrue(responseEntity.getStatusCodeValue() == HttpStatus.OK.value(),"返回狀態不對。"+responseEntity.getStatusCodeValue());
	InputStream inputStream = new ByteArrayInputStream(body);
	// pdf轉圖片
	PDDocument doc = PDDocument.load(inputStream);
	PDFRenderer renderer = new PDFRenderer(doc);
	int pageCount = doc.getNumberOfPages();
	for (int i = 0; i < pageCount; i++) {
		// dpi,圖片畫素點,dpi越高圖片體積越大,216很清晰,105體積穩定
		BufferedImage image = renderer.renderImageWithDPI(i, 216);
		// 格式為JPG
		ImageIO.write(image, "jpg", resp.getOutputStream());
	}
	String filename = path.substring(path.lastIndexOf("/")+1).replaceAll(".pdf",".jpg");
	resp.setContentType("image/jpeg;charset=UTF-8");
	resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
    }

5、通過PostMan測試

前端請求url:localhost:8080/test/readPdfFileImg?path=http://127.0.0.1:8080/statics/2022/123456.pdf/