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

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

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

kx5bkwkv

kx5bkwkv1#

先将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);

相关问题