Blog Post

How to Convert Word (DOC/DOCX) to PDF in JavaScript

Illustration: How to Convert Word (DOC/DOCX) to PDF in JavaScript

In this blog post, you’ll learn how to convert Word (DOC and DOCX) to PDF using JavaScript and PSPDFKit. 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, PSPDFKit for Web 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 PSPDFKit for Web, 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.

For both manual and npm installations, it’s important to note that the assets must be copied to a public folder. Make sure your server has the Content-Type: application/wasm MIME typeset, as explained in our troubleshooting guide.

To serve the files, you need to use an npm package like serve as a simple HTTP server.

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 PSPDFKit for Web. 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:

Adding PSPDFKit to Your Project

  1. Install the pspdfkit package from npm. If you prefer, you can also download PSPDFKit for Web manually:

npm install pspdfkit
  1. For PSPDFKit for Web to work, it’s necessary to copy the directory containing all the required library files (artifacts) to the assets folder. Use the following command to do this:

cp -R ./node_modules/pspdfkit/dist/ ./assets/

Make sure your assets directory contains the pspdfkit.js file and a pspdfkit-lib directory with the library assets.

Integrating into Your Project

  1. Add the DOC or DOCX document you want to display to your project’s directory. You can use our demo document as an example.

  2. Add an empty <div> element with a defined width and height to where PSPDFKit will be mounted:

<div id="pspdfkit" style="width:100%; height: 100vh;"></div>
  1. Include pspdfkit.js in your HTML page:

<script src="assets/pspdfkit.js"></script>
  1. Initialize PSPDFKit for Web in JavaScript by calling the load() method.

This method takes a configuration object as its parameter. The configuration object specifies the location of the document on the page, the path to the source document, and the optional license key:

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
	 	document: "document.docx" // Add the path to your document here.
	 	licenseKey: "YOUR_LICENSE_KEY" // Remove this line if you're using the free trial.
	})
</script>

This code will load document.docx into the element with the ID pspdfkit.

  1. Convert the source document to a PDF with the exportPDF method:

<script>
	PSPDFKit.load({
		container: '#pspdfkit',
		document: 'document.docx', // Add the path to your document here.
	})
		.then(function (instance) {
			return instance.exportPDF();
		})
		.catch(function (error) {
			console.error(error.message);
		});
</script>
  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:

// The `PSPDFKit.load()` call is omitted for brevity.
.then(function(instance) {
    return 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:

.then(function (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);
}

You can see the full index.html file below:

<!DOCTYPE html>
<html>
	<head>
		<title>My App</title>
		<!-- Provide proper viewport information so that the layout works on mobile devices. -->
		<meta
			name="viewport"
			content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
		/>
	</head>
	<body>
		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="width:100%; height: 100vh"></div>

		<script src="assets/pspdfkit.js"></script>
		<script>
			PSPDFKit.load({
				container: '#pspdfkit',
				document: 'document.docx', // Add the path to your document here.
			})
				.then(function (instance) {
					return instance.exportPDF({
						outputFormat: {
							conformance: PSPDFKit.Conformance.PDFA_4F,
						},
					});
				})
				.then(function (buffer) {
					const blob = new Blob([buffer], {
						type: 'application/pdf',
					});
					const objectUrl = window.URL.createObjectURL(blob);
					downloadPdf(objectUrl);
					window.URL.revokeObjectURL(objectUrl);
				})
				.catch(function (error) {
					console.error(error.message);
				});

			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);
			}
		</script>
	</body>
</html>

Serving Your Website

You’ll use the npm serve package to serve your project.

  1. Install the serve package:

npm install --global serve
  1. Serve the contents of the current directory:

serve -l 8080 .
  1. Navigate to http://localhost:8080 to view the website. The output.pdf file will be downloaded automatically.

A Note about Fonts

When you convert an Office document with custom fonts to a PDF, PSPDFKit for Web might not have access to these fonts due to licensing constraints. In this case, PSPDFKit typically replaces unavailable fonts with their equivalents — like Arial with Noto.

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 JavaScript guides:

Conclusion

In this blog post, you learned how to convert Word (DOC and DOCX) to PDF using JavaScript with the PSPDFKit SDK. It also discussed the benefits of using PSPDFKit for Web Standalone to render Office documents in the browser. We hope you found this information helpful.

If you’re looking for a way to render Office documents in your web application, then PSPDFKit for Web Standalone is a great option. It’s a powerful and flexible library that can help you provide your users with a seamless and enjoyable experience.

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.

Author
Hulya Karakaya Technical Writer

Hulya is a frontend web developer and technical writer at PSPDFKit 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 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
DESIGN  |  Baseline UI • Web

Part VI — A Glimpse into Our Baseline UI Customization Approach

DESIGN  |  Baseline UI • Web

Part V — Mastering the Baseline UI Theme: An In-Depth Exploration

DESIGN  |  Baseline UI • Web

Part IV — Building Consistency: A Guide to Design Tokens in Baseline UI