Blog Post

How to convert Word (DOC/DOCX) to PDF in React

Illustration: How to convert Word (DOC/DOCX) to PDF in React
Information

This article was first published in April 2023 and was updated in August 2024.

In this blog post, you’ll learn how to convert Word (DOC and DOCX) to PDF using React and Nutrient. Both DOC and DOCX files are converted to PDF in the client and don’t require any server-side processing.

Client-side Word-to-PDF conversion

To convert Office documents such as DOC or DOCX files to PDF, Nutrient Web SDK relies entirely on its own technology built from the ground up, and it doesn’t depend on third-party tools such as Microsoft Office. With Nutrient Web SDK, Word documents can be converted into PDF headlessly without a visual interface, or automatically as the document is loaded in the viewer.

  • Easily integrate client-side Word-to-PDF conversion in your app or workflow.

  • Open Word files in the viewer or convert directly in your workflow.

  • No MS interop or license required.

  • Doesn’t rely on third-party tools like LibreOffice.

  • We work directly with you to refine and improve conversion results.

Unlocking more capabilities with our Word viewer

By combining client-side Word-to-PDF conversion with our standalone viewer, you unlock all the document processing capabilities available with Nutrient Web SDK. Users can now view, collaborate on, edit, and sign Office files directly in the web browser.

  • Text editing — Edit text directly in the displayed Word document.

  • Page manipulation — Organize documents by adding, removing, or rearranging pages.

  • Annotations — Boost collaboration by adding text highlights, comments, or stamps.

  • Adding signatures — Draw, type, or upload a signature directly to a Word document.

Explore Demo

Requirements to get started

To get started, you’ll need:

  • The latest version of Node.js.

  • A package manager compatible with npm. This guide contains usage examples for Yarn and the npm client (installed with Node.js by default).

Setting up a new React project with Vite

  1. To get started, create a new React project using Vite:

# Using Yarn
yarn create vite pspdfkit-react-example --template react

# Using npm
npm create vite@latest pspdfkit-react-example -- --template react
  1. Navigate to your project directory:

cd pspdfkit-react-example

Adding Nutrient to your project

  1. First, install Nutrient as a dependency:

# Using Yarn
yarn add pspdfkit

# Using npm
npm install pspdfkit
  1. Next, copy the Nutrient Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib

This ensures Nutrient can access its assets from the public/pspdfkit-lib directory.

Information

Make sure your development server supports the application/wasm MIME type. This can be crucial for WebAssembly to function correctly.

Displaying a PDF in your React app

  1. Add a Word (DOC, DOCX) document you want to display to the public directory. You can use our demo document as an example.

  2. Create a new component to handle PDF rendering. In the src/components/ directory, create a file named PdfViewerComponent.jsx with the following content:

import { useEffect, useRef } from 'react';

export default function PdfViewerComponent(props) {
	const containerRef = useRef(null);

	useEffect(() => {
		const container = containerRef.current;
		let PSPDFKit, instance;

		(async function () {
			PSPDFKit = await import('pspdfkit');

			PSPDFKit.unload(container);

			instance = await PSPDFKit.load({
				container,
				document: props.document,
				baseUrl: `${window.location.protocol}//${
					window.location.host
				}/${import.meta.env.BASE_URL}`,
			});
		})();

		return () => PSPDFKit && PSPDFKit.unload(container);
	}, []);

	return (
		<div
			ref={containerRef}
			style={{ width: '100%', height: '100vh' }}
		/>
	);
}
  1. Convert the source document to a PDF with the exportPDF method:

(async function () {
	PSPDFKit = await import('pspdfkit');
	PSPDFKit.unload(container);

	instance = await PSPDFKit.load({
		container,
		document: props.document,
		baseUrl: `${window.location.protocol}//${window.location.host}/${import.meta.env.BASE_URL}`,
	});
+  instance.exportPDF();
})();
  1. Optionally, you can use the outputFormat flag to generate a PDF/A document. For more details, refer to the guide on converting PDF to PDF/A:

instance.exportPDF({
	outputFormat: {
		conformance: PSPDFKit.Conformance.PDFA_4F,
	},
});
  1. Next, save the resulting document. The exportPDF method returns a Promise that resolves into an ArrayBuffer containing the output PDF document. You can use this array buffer to download the PDF or store it:

instance.exportPDF().then((buffer) => {
	const blob = new Blob([buffer], { type: 'application/pdf' });
	const objectUrl = window.URL.createObjectURL(blob);
	downloadPdf(objectUrl);
	window.URL.revokeObjectURL(objectUrl);
});

function downloadPdf(blob) {
	const a = document.createElement('a');
	a.href = blob;
	a.style.display = 'none';
	a.download = 'output.pdf';
	a.setAttribute('download', 'output.pdf');
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
}

Here’s the full code for the PdfViewerComponent:

import { useEffect, useRef } from 'react';

export default function PdfViewerComponent(props) {
	const containerRef = useRef(null);

	useEffect(() => {
		const container = containerRef.current;
		let instance, PSPDFKit;
		(async function () {
			try {
				PSPDFKit = await import('pspdfkit');

				PSPDFKit.unload(container); // Ensure there's only one PSPDFKit instance.

				const instance = await PSPDFKit.load({
					// Container where PSPDFKit should be mounted.
					container,
					// The document to open.
					document: props.document,
					// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.

					baseUrl: `${window.location.protocol}//${
						window.location.host
					}/${import.meta.env.BASE_URL}`,
				});

				instance.exportPDF().then((buffer) => {
					const blob = new Blob([buffer], {
						type: 'application/pdf',
					});
					const objectUrl = window.URL.createObjectURL(blob);
					downloadPdf(objectUrl);
					window.URL.revokeObjectURL(objectUrl);
				});
			} catch (error) {
				console.error('The document could not be signed.', error);
			}
		})();

		return () => PSPDFKit && PSPDFKit.unload(container);
	}, []);

	return (
		<div
			ref={containerRef}
			style={{ width: '100%', height: '100vh' }}
		/>
	);

	function downloadPdf(blob) {
		const a = document.createElement('a');
		a.href = blob;
		a.style.display = 'none';
		a.download = 'output.pdf';
		a.setAttribute('download', 'output.pdf');
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	}
}
  1. Integrate this component into your app by updating the src/App.jsx file:

import PdfViewerComponent from './components/PdfViewerComponent';

function App() {
	return (
		<div className="App" style={{ width: '100vw' }}>
			<div className="PDF-viewer">
				<PdfViewerComponent document={'document.docx'} />
			</div>
		</div>
	);
}

export default App;

Ensure your project structure looks like this:

pspdfkit-react-example/
├── public/
│   ├── pspdfkit-lib/
│   └── document.docx
├── src/
│   ├── components/
│   │   └── PdfViewerComponent.jsx
│   └── App.jsx
├── package.json
└── yarn.lock
  1. Start your development server:

# Using Yarn
yarn dev

# Using npm
npm run dev

The output.pdf file will be downloaded automatically.

A note about fonts

In client-side web applications for Microsoft Office-to-PDF conversion, Nutrient addresses font licensing constraints through font substitutions, typically replacing unavailable fonts with their equivalents — like Arial with Noto. For precise font matching, you can provide your own fonts, embed them into source files, or designate paths to your .ttf fonts for custom solutions.

Adding even more capabilities

Once you’ve deployed your viewer, you can start customizing it to meet your specific requirements or easily add more capabilities. To help you get started, here are some of our most popular React.js guides:

Conclusion

In this blog post, you learned how to convert Word documents to PDF in React with the Nutrient SDK.

If you’re looking for a way to render Office documents in your web application, Nutrient offers a React Office viewer. It’s a powerful and flexible library that enables you to open, view, edit, annotate, and sign documents directly in a web browser.

To get started, you can either:

  • Start your free trial to test out the library and see how it works in your application.

  • Launch our demo to see the viewer in action.

FAQ

Here are a few frequently asked questions about converting Word to PDF in React.

How can I convert Word (DOC/DOCX) to PDF in React?

You can use Nutrient Web SDK to convert Word documents to PDF client side without server-side processing.

How do I add Nutrient to my React project?

Install Nutrient using yarn add pspdfkit or npm install pspdfkit. Then copy the library assets to the public directory.

Can I add annotations or signatures to the PDF?

Yes, Nutrient allows text editing, page manipulation, annotations, and adding signatures to the PDF.

How do I download the converted PDF?

The exportPDF method returns a promise with an ArrayBuffer, which you can use to create a downloadable Blob object.

Author
Hulya Masharipov Technical Writer

Hulya is a frontend web developer and technical writer at Nutrient who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

Related products
Share post
Free trial Ready to get started?
Free trial