将html转换为->pdf->转换为多部分文件springboot和thymeleaf

oknrviil  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(555)

我有一个合同管理的网络应用与React和springboot。用户应该能够添加一个新的合同,然后下载pdf文件的合同,这样他就可以签署它,然后上传合同.pdf签署。我做了上传和下载部分,使用java中的multipartfile,并将pdf存储在mysql数据库中。
pdf是在springboot服务器中用thymeleaf从html文件创建的。我不清楚的是如何将pdf文件转换为多部分文件,这样我就可以将它保存在db中。
我还想把文件转换成pdf格式,而不是保存在本地。我使用了itext htmlconverter.converttopdf(html,newfileoutputstream(name))(我不知道如何从中提取pdf文件…然后转换为多部分文件。
在这个服务中,我将数据从控制器传递到html文件,然后将其转换为pdf

  1. @Service
  2. public class PdfContentBuilder {
  3. private TemplateEngine templateEngine;
  4. @Autowired
  5. public PdfContentBuilder(TemplateEngine templateEngine) {
  6. this.templateEngine = templateEngine;
  7. }
  8. public String buildContract(Contract contract) {
  9. Context context = new Context();
  10. context.setVariable("data_contract", contract.getData());
  11. context.setVariable("number", contract.getNumber());
  12. return templateEngine.process("contract", context);
  13. }
  14. public void generatePdfFromHtml(String html, String name) throws IOException {
  15. //here I would need to return a MultipartFile
  16. HtmlConverter.convertToPdf(html, new FileOutputStream(name));
  17. }
  18. }

这里我试着生成pdf

  1. public MultipartFile createPDF(Contract contract){
  2. contract.setNumber(25314);
  3. Date myDate2 = new Date(System.currentTimeMillis());
  4. contract.setData(myDate2);
  5. String htmlString = pdfContentBuilder.buildContractTerti(contract);
  6. try {
  7. //here I don't know how to take the PDF as file and not save it local
  8. pdfContentBuilder.generatePdfFromHtml(htmlString, "filename-contract.pdf");
  9. return pdfMultipartFile;
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. return pdfMultipartFile;
  13. }
  14. }

我搜索了htmlconverter.converttopdf,但是没有一个版本返回一个文件,所有版本都返回void。如果有人能帮忙,好吗?

kx5bkwkv

kx5bkwkv1#

先将pdf写入字节数组,然后存储在文件中并创建响应:

  1. public byte[] generatePdfFromHtml(String html, String name) throws IOException {
  2. ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  3. HtmlConverter.convertToPdf(html, buffer);
  4. byte[] pdfAsBytes = buffer.toByteArray();
  5. try (FileOutputStream fos = new FileOutputStream(name)) {
  6. fos.write(pdfAsBytes);
  7. }
  8. return pdfAsBytes.
  9. }

对于下载,使用httpentity而不是multipartfile,例如。

  1. HttpHeaders header = new HttpHeaders();
  2. header.setContentType(MediaType.APPLICATION_PDF);
  3. header.set(HttpHeaders.CONTENT_DISPOSITION,
  4. "attachment; filename=" + fileName.replace(" ", "_"));
  5. header.setContentLength(documentBody.length);
  6. HttpEntity pdfEntity = new HttpEntity<byte[]>(pdfAsBytes, header);
展开查看全部

相关问题