【发布时间】:2021-01-07 11:27:21
【问题描述】:
我有一个使用 React 和 SpringBoot 进行合同管理的 Web 应用程序。用户应该能够添加新合同,然后将合同下载为 PDF 文件,以便他可以签署,然后上传已签署的合同.pdf。我完成了上传和下载的部分,使用 java 中的 MultipartFile,并将 pdf 存储在 MySql 数据库中。
PDF 是在 SpringBoot 服务器中使用 Thymeleaf 从 HTML 文件创建的。我不清楚的是如何将 PDF 文件转换为 MultipartFile,这样我就可以将它保存在数据库中。
而且我还想将文件转换为 PDF 而不是本地保存。 我使用了 iText HtmlConverter.convertToPdf(html, new FileOutputStream(name)); (com.itextpdf.html2pdf),我不知道如何从中获取 PDF 文件...然后转换为 MultipartFile。
这是我将数据从控制器传递到 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。 如果有人可以帮忙吗?
【问题讨论】:
标签: java spring-boot itext html2pdf