'I want to convert base64 string of a Word doc to a base64 string of PDF in JavaScript/Angular 9

I am using the docx library to generate a Word document (.docx) on the client side (Angular 9). I also want to be able to save the file as a pdf. I can get a base64 string/uint8array/blob, but I believe this is different for different types of documents. Because when I save the file as a pdf it is corrupted. Is there a way to convert the base64 string of a word doc to base64 string of pdf in JavaScript?

Packer.toBase64String(doc).then((string) => {
    // Convert this bas64 encoded word string to base64 encoded pdf string
});

Alternatively, if we can convert the blob too, that is fine.

Packer.toBlob(doc).then((blob) => {
    //convert word blob to pdf blob
    saveAs(blob, 'example.pdf');
});


Solution 1:[1]

The short answer is no (not directly)

As you say they are totally different textual expansions of different types of compressed (encoded) "binary" sources.

Base64 is used to transfer a binary file without corruption due to Text Transfer (the TT in HTTPS) so a file can be reproduced from binary to text then transferred (we call that download, hence HTML PDF etc. are always downloaded from server to client) and converted back into binary. Similar for email attachments.

So the long winded answer to the question is

  • Use the OS base64 tool or AtoB.js to convert base64.txt to compressed binary.DocX or .PDF as required

  • Then use use a binary converter library to decompress and re-compress as either doc2pdf or pdf2doc

  • Then use base64 to expand it back again to transmittable text so that it can be re-compressed at the receiver back into binary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 K J