Implement a WebViewer that Generates DOCX

This sample shows how to easily create DOCX documents 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.

1import './App.css';
2import { useEffect, useState } from 'react';
3import { Document, Packer, Paragraph, TextRun } from 'docx';
4import Viewer from './components/Viewer';
5import WebViewerContext from './context/webviewer.js';
6
7function App() {
8 const [instance, setInstance] = useState();
9
10 // generate DOCX document
11 const generateDocx = async () => {
12 const doc = new Document({
13 sections: [
14 {
15 properties: {},
16 children: [
17 new Paragraph({
18 children: [
19 new TextRun('Hello World'),
20 new TextRun({
21 text: 'Foo Bar',
22 bold: true,
23 }),
24 new TextRun({
25 text: '\tGithub is the best',
26 bold: true,
27 }),
28 ],
29 }),
30 ],
31 },
32 ],
33 });
34
35 const blob = await Packer.toBlob(doc);
36
37 return blob;
38 };
39
40 useEffect(() => {
41 const generateAndLoadDocument = async () => {
42 const docBlob = await generateDocx();
43 await instance.Core.documentViewer.loadDocument(docBlob, {
44 extension: 'docx',
45 });
46 };
47 if (instance) {
48 generateAndLoadDocument();
49 }
50 }, [instance]);
51
52 return (
53 <WebViewerContext.Provider value={{ instance, setInstance }}>
54 <div className='App'>
55 <Viewer />
56 </div>
57 </WebViewerContext.Provider>
58 );
59}
60
61export default App;
62

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales