Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Created December 18, 2022 11:46
Show Gist options
  • Save leonidkuznetsov18/2cd260fcf5574ebbce3c08b015c45d11 to your computer and use it in GitHub Desktop.
Save leonidkuznetsov18/2cd260fcf5574ebbce3c08b015c45d11 to your computer and use it in GitHub Desktop.
Convert word to pdf
const doc = new jsPDF();
// Load the Word file as a Blob
const file = await fetch('path/to/word.docx').then(res => res.blob());
// Convert the Word file to a base64-encoded data URI
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const base64 = reader.result;
// Create a new Blob from the data URI
const dataURI = base64.split(',')[1];
const byteString = atob(dataURI);
const arrayBuffer = new ArrayBuffer(byteString.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
const wordFile = new Blob([arrayBuffer], { type: 'application/msword' });
// Use PDFJS to render the Word file as a PDF
PDFJS.getDocument(wordFile).then(pdf => {
// Add each page of the PDF to the jsPDF document
for (let i = 1; i <= pdf.numPages; i++) {
pdf.getPage(i).then(page => {
const viewport = page.getViewport({ scale: 1 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({ canvasContext: context, viewport: viewport }).then(() => {
doc.addImage(canvas.toDataURL('image/png'), 'png', 0, 0, viewport.width, viewport.height);
if (i < pdf.numPages) {
doc.addPage();
}
});
});
});
// Save the PDF
doc.save('word-to-pdf.pdf');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment