繁体   English   中英

将 HTML 转换为 -> PDF -> 转换为 MULTIPARTFILE SpringBoot 和 Thymeleaf

[英]Convert HTML to -> PDF ->to MULTIPARTFILE SpringBoot and Thymeleaf

我有一个 web 应用程序,带有 React 和 SpringBoot 合同管理。 用户应该能够添加新合同,然后将合同下载为 PDF 文件,以便他可以签署它,然后上传合同。pdf 签署。 我使用 java 中的 MultipartFile 完成了上传和下载部分,并将 pdf 存储在 MySql 数据库中。

PDF 是在 SpringBoot 服务器中从 HTML 文件和 Thymeleaf 创建的。 我不清楚如何将 PDF 文件转换为 MultipartFile,因此我可以将其保存在数据库中。

而且我想将文件转换为 PDF 而不是本地保存。 我使用了 iText HtmlConverter.convertToPdf(html, new FileOutputStream(name)); (com.itextpdf.html2pdf),我不知道如何从中获取 PDF 文件......然后转换为 MultipartFile。

这是我将数据从 controller 传递到 HTML 文件然后将其转换为 PDF 的服务

@Service
public class PdfContentBuilder {

    private TemplateEngine templateEngine;

    @Autowired
    public PdfContentBuilder(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    public String buildContract(Contract contract) {

        Context context = new Context();
        context.setVariable("data_contract", contract.getData());
        context.setVariable("number", contract.getNumber());

        return templateEngine.process("contract", context);
    }

    public void generatePdfFromHtml(String html, String name) throws IOException  {
        
        //here I would need to return a MultipartFile
        HtmlConverter.convertToPdf(html, new FileOutputStream(name));
    }
}

在这里我尝试生成 PDF

public MultipartFile createPDF(Contract contract){
    
    contract.setNumber(25314);
    Date myDate2 = new Date(System.currentTimeMillis());
    contract.setData(myDate2);


    String htmlString = pdfContentBuilder.buildContractTerti(contract);
    try {
        //here I don't know how to take the PDF as file and not save it local
        pdfContentBuilder.generatePdfFromHtml(htmlString, "filename-contract.pdf");

        return pdfMultipartFile;

    } catch (Exception e) {
        e.printStackTrace();
        return pdfMultipartFile;
    }
}

我搜索了 HtmlConverter.convertToPdf 但没有一个版本返回文件,所有版本都返回 void。 如果有人可以帮忙,好吗?

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

public byte[] generatePdfFromHtml(String html, String name) throws IOException  {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();              
  HtmlConverter.convertToPdf(html, buffer);
  byte[] pdfAsBytes = buffer.toByteArray();
  try (FileOutputStream fos = new FileOutputStream(name)) {
   fos.write(pdfAsBytes);
  }
  return pdfAsBytes.
}

对于下载使用 HttpEntity 而不是 MultipartFile,例如

HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(documentBody.length);

HttpEntity pdfEntity = new HttpEntity<byte[]>(pdfAsBytes, header);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM