其他分享
首页 > 其他分享> > Spring Boot 通过RestTemplat返回pdf转图片

Spring Boot 通过RestTemplat返回pdf转图片

作者:互联网

Springboot 通过 RestTemplat 返回 pdf转图片

开发环境:

需求:前端发送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/

标签:Spring,resp,Boot,new,filename,responseEntity,pdf,path
来源: https://www.cnblogs.com/galenblog/p/16305382.html