我在React和SpringBoot上有一个关于合同管理的Web应用程序。用户应该能够添加新合同,然后将合同下载为PDF文件,以便他可以对其进行签名,然后上载已签名的pdf。我使用Java的MultipartFile完成了上载和下载的部分,并将pdfs存储在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。如果有人可以帮助,请?
首先将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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句