首页>代码>SpringBoot Html转PDF SpringBoot转换网页为PDF>/springboot-pdf-master/src/main/java/com/example/demo/controller/PrintPdfController.java
package com.example.demo.controller; import com.example.demo.model.PdfFileRequest; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author Simon */ @Controller @RequestMapping("/print") public class PrintPdfController { @Value("${pdf.source.html}") private String pdfSourceHtml; @Value("${pdf.name}") private String pdfName; public String getPdfSourceHtml() { return pdfSourceHtml; } public void setPdfSourceHtml(String pdfSourceHtml) { this.pdfSourceHtml = pdfSourceHtml; } public String getPdfName() { return pdfName; } public void setPdfName(String pdfName) { this.pdfName = pdfName; } private final RestTemplate restTemplate; public PrintPdfController(RestTemplateBuilder restTemplateBuilder) { this.restTemplate = restTemplateBuilder.build(); } @RequestMapping(value = "/pdf", method = RequestMethod.GET) public void createPdfFromUrl(HttpServletResponse response) { PdfFileRequest fileRequest = new PdfFileRequest(); fileRequest.setFileName(pdfName); fileRequest.setSourceHtmlUrl(pdfSourceHtml); byte[] pdfFile = restTemplate.postForObject("http://localhost:8080/api/pdf", fileRequest, byte[].class ); writePdfFileToResponse(pdfFile, pdfName, response); } private void writePdfFileToResponse(byte[] pdfFile, String fileName, HttpServletResponse response) { try (InputStream in = new ByteArrayInputStream(pdfFile)) { response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); OutputStream out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); response.flushBuffer(); } catch (IOException ex) { throw new RuntimeException("Error occurred when creating PDF file", ex); } } }


citybird LV4
2024年11月20日
develop LV10
2024年6月2日
f22m1a2b2 LV17
2024年5月31日
taoshen95 LV16
2024年5月15日
2716804680 LV9
2024年4月20日
2317696509 LV6
2023年12月15日
chenlie LV2
2023年11月13日
内心向阳 LV4
2023年11月7日
13043860zj LV16
2023年10月31日
pizizhang
2023年10月20日
暂无贡献等级