Solution 1 :

write the pdf to a byte array first, then store in file and create response:

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)) {
  return pdfAsBytes.

For download use HttpEntity instead of MultipartFile, e.g.

HttpHeaders header = new HttpHeaders();
                   "attachment; filename=" + fileName.replace(" ", "_"));

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

Problem :

I have an web app with React and SpringBoot on contract management. The user should be able to add a new contract and then download the contract as PDF file so he can sign it and then upload the contract.pdf signed. I did the part of upload and download, using MultipartFile from java, and storing the pdfs in MySql DataBase.

The PDF is created in the SpringBoot server from HTML file with Thymeleaf. What is unclear to me is how to transform the PDF file to MultipartFile, so I would be able to save it in the DB.

And also I would like to transform the file to PDF and not save it localy.
I used iText HtmlConverter.convertToPdf(html, new FileOutputStream(name)); (com.itextpdf.html2pdf ) and I don’t know how to take the PDF file from it…and then transform to MultipartFile.

This is the Service where I pass the data from controller to HTML file and then transform it to PDF

public class PdfContentBuilder {

    private TemplateEngine templateEngine;

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

And here I try to generate the PDF

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

    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) {
        return pdfMultipartFile;

I searched about HtmlConverter.convertToPdf but none of it’s versions return a file, all versions returns void.
If someone can help, please?