Convert a .docx document as a pdf document and attach to an email

1.4k Views Asked by At

I am currently running a cloud function to generate a .docx document and then deliver it to a user using nodemailer. Here is the code to generate the .docx file using docxtemplater:

  const file_name = 'template.docx';// this is the file saved in my firebase storage
  const templateRef = await admin.storage().bucket()
      .file(file_name);
  const template_content = (await templateRef.download())[0];
  const zip = new PizZip(template_content);

  let doc;
  try {
    doc = new Docxtemplater(zip, { linebreaks: true });
  } catch (error) {
    // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
    errorHandler(error);
  }

  doc.setData({
    name: data.name
  });

  try {
    doc.render();
  } catch (error) {
    errorHandler(error);
  }

  const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });

What I am trying to achieve now is to change that contentBuffer into a pdf file that can then be attached to an email. I tried using PDF make but it generated a blank pdf. Is there a way this can be done using any of the pdf Generators?

3

There are 3 best solutions below

0
On

From a quick search I've found this info in the Docxtemplater's docs:

Convert to PDF

It is not possible to convert docx to PDF with docxtemplater, ... There are many tools to do this conversion.

The first one is to use libreoffice headless, which permits you to generate a PDF from a docx document:

You just have to run:

libreoffice --headless --convert-to pdf --outdir . input.docx

This will convert the input.docx file into input.pdf file.

This also lists PDFtron and Aspose as another options if the results of the first one aren't good enough for your needs.

0
On

If you prefer a docker container that exposes an api for the conversion of docx to pdf, I can recommend Gotenberg. Of course, under the hood it is using similiar libraries which @Ido mentioned.

0
On

From cloud function, it's not possible to call LibreOffice. So I recommend you to use alternative to docxtemplater which include pdf generation. You can for example use Carbone