How to convert docx to PDF in Angular 15 using "docxjs"?

2.3k Views Asked by At

I'm using https://docx.js.org/api/ to create some docx file and download but I don't find how to convert this to PDF

This is how is working right now.

public download(data: any): void {
    const documentCreator = new DocumentCreator();
    const doc = documentCreator.create(data);

    Packer.toBlob(doc).then((blob) => {
      console.log(blob);
      saveAs(
        blob,
        `Contrato ${data.place} ${_moment(data.dateEvent).format('LL')}.docx`
      );
      console.log('Document created successfully');
      this.closeModalExport();
    });
  }

export class DocumentCreator {
  // tslint:disable-next-line: typedef
  public create(diary): Document {
   //Some paragraph and texts
return document;
  }
}

But how can I do to convert the blob to pdf?

I tried to convert directly and changed the type of the blob but didn't work

let pdf = new Blob([blob], {type: 'application/pdf'});
saveAs(
        pdf,
        `Contrato ${data.place} ${_moment(data.dateEvent).format('LL')}.pdf`
      );
2

There are 2 best solutions below

1
On

Unfortunately, the docx.js library does not provide a built-in feature to convert the docx file to a PDF. You will need to use a separate library or API to perform the conversion.

0
On

Generally it is difficult to convert between binary formats without using files, here is an endpoint from the quoted question API, on the Left. The layout is good if a bit "Spartan" (joke, its a Roman Font). On the right is a single line conversion using Windows own command line native print to PDF, where fidelity is lost as a Sans Serif font has sadly been substituted.

enter image description here

Thus the simplest way to get a similar convert from DocX to PDF is use a DocX reader / writer that maintains both layouts and styles. Thus the most universal (Apart from real MS Office or its interop) is Open Office / Libre Office as a poor mans second best suite.

Practically all methods of pdf production, require file system, even in memory, but certainly there is no such thing as a blob to blob conversion without going via a DocX reader and PDF writer.

An API may be able to accept blob convert and decompress to File.docX print to compressed FILE.PDF and convert and then decompress by convert to blob. (takes some time)

There are many offering such a service for example https://github.com/unoconv/unoconv

HOWEVER

again here is the comparison between an online Word and Libre Office conversion look close at the details

enter image description here

Libre Office has no bullet points, the layout has been altered to 2 pages not 1, yes the file is small but that's alarming why? especially as all new fonts have been added as replacements to the intended font. !