Generation
Generate DOCX from a Blob with WebViewer
This sample shows how to easily create DOCX documents from a Blob in JavaScript, view them in the browser, and convert and download as a PDF.
WebViewer provides a slick out-of-the-box responsive UI that enables you to view, annotate and manipulate PDFs and other document types inside any web project.
Click the button below to view the full project in GitHub.
import './App.css';
import { useEffect, useState } from 'react';
import { Document, Packer, Paragraph, TextRun } from 'docx';
import Viewer from './components/Viewer';
import WebViewerContext from './context/webviewer.js';
function App() {
const [instance, setInstance] = useState();
// generate DOCX document
const generateDocx = async () => {
const doc = new Document({
sections: [
{
properties: {},
children: [
new Paragraph({
children: [
new TextRun('Hello World'),
new TextRun({
text: 'Foo Bar',
bold: true,
}),
new TextRun({
text: '\tGithub is the best',
bold: true,
}),
],
}),
],
},
],
});
const blob = await Packer.toBlob(doc);
return blob;
};
useEffect(() => {
const generateAndLoadDocument = async () => {
const docBlob = await generateDocx();
await instance.Core.documentViewer.loadDocument(docBlob, {
extension: 'docx',
enableOfficeEditing: true, // Enable Office Editing for the loaded document
filename: 'blob_generated.docx', // Set the filename for the document viewer
});
};
if (instance) {
generateAndLoadDocument();
}
}, [instance]);
return (
<WebViewerContext.Provider value={{ instance, setInstance }}>
<div className='App'>
<Viewer />
</div>
</WebViewerContext.Provider>
);
}
export default App;