Blog Post

How to Open Word (DOC and DOCX) Files in the Browser with JavaScript

Illustration: How to Open Word (DOC and DOCX) Files in the Browser with JavaScript

In this blog post, you’ll learn how to open a Word file in the browser using JavaScript and PSPDFKit. You’ll have the option to open a DOC or DOCX file from a URL, a blob, an array buffer, local storage, or Base64 data.

Opening Office Documents in the Browser

PSPDFKit for Web lets you open Office documents in a web browser without you or your users needing any MS Office software, MS Office licenses, or third-party open source software. The technology works by first converting an Office document to PDF client-side and then opening the file directly in the browser.

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 Client-Side Viewer

By opening and displaying your Word file in PSPDFKit’s standalone viewer, you can unlock additional capabilities like annotating, form filling, editing, and signing Office files directly in the web browser.

  • Text editing — Edit text directly in the displayed Office 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 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>

Opening a Word Document from a Remote URL

To load a document from a remote URL in standalone mode, include the document URL within the configuration object passed to PSPDFKit.load():

PSPDFKit.load({
	document: documentUrl, // Pass the URL to your document here.
});

Opening a Word Document from a Blob

If you have a DOC file available as a blob, you can generate an object URL for it and pass it as the document:

const documentBlobObjectUrl = URL.createObjectURL(blob);

PSPDFKit.load({
	document: documentBlobObjectUrl,
}).then((instance) => {
	// Make sure to revoke the object URL once it's no longer needed to avoid unnecessary resource retention by the browser.
	URL.revokeObjectURL(documentBlobObjectUrl);
});

Furthermore, you can define the initial viewer settings in the same configuration object using the initialViewState property. For example, if you want to open the document on a specific page (e.g. page 8) with the thumbnails sidebar visible, you can do so like this:

const documentBlobObjectUrl = URL.createObjectURL(blob);

PSPDFKit.load({
	document: documentBlobObjectUrl,
	initialViewState: new PSPDFKit.ViewState({
		pageIndex: 8,
		sidebarMode: PSPDFKit.SidebarMode.THUMBNAILS,
	}),
}).then((instance) => {
	// Remember to revoke the object URL to release unnecessary resources held by the browser.
	URL.revokeObjectURL(documentBlobObjectUrl);
});

Opening a Word Document from an Array Buffer

PSPDFKit for Web Standalone provides the flexibility to open a Word document from an ArrayBuffer. The document data can be passed directly as an ArrayBuffer to the document property of the PSPDFKit.Configuration object that’s passed to the PSPDFKit.load() function:

PSPDFKit.load({
	document: myDocumentArrayBuffer,
});

Ensure you have the Word document data available as an ArrayBuffer before calling PSPDFKit.load(). The myDocumentArrayBuffer variable should contain the actual ArrayBuffer representing the document file.

By using this approach, you can open Word documents directly from an ArrayBuffer without the need for a document URL. PSPDFKit will handle the rendering and displaying of the document in the browser.

Opening a Word Document from Local Storage

In standalone mode, you might want to store a Word document in the browser’s local storage for persistence. Since local storage only accepts data as a string, you can encode a document using Base64 and save it.

First, export the document as an ArrayBuffer, and then encode it as a Base64 string:

const myDocumentArrayBuffer = await instance.exportPDF();
let base64EncodedDocument = '';
const len = myDocumentArrayBuffer.byteLength;
for (let i = 0; i < len; i++) {
	base64EncodedDocument += String.fromCharCode(
		myDocumentArrayBuffer[i],
	);
}
window.localStorage.setItem('document', base64EncodedDocument);

To load this document later, retrieve the Base64 string from local storage and pass it as a data URL in the configuration object for PSPDFKit.load():

const base64EncodedDocument = window.localStorage.getItem('document');
PSPDFKit.load({
	// `base64Decode` is a user function that decodes a Base64 string into an `ArrayBuffer`.
	document: `data:application/pdf;base64,${base64EncodedDocument}`,
});

Opening a Word Document from Base64 Data

If you need to open a Word document encoded as Base64 data, you can pass it as a data URL:

PSPDFKit.load({
	document: `data:application/pdf;base64,${base64EncodedDocument}`,
});

The Base64-encoded string can be constructed from a file in any of the different supported input formats.

You can also set the initial viewer settings in the same configuration object using the initialViewState property. For example, to open the document on page 8 with the thumbnails sidebar visible, do the following:

PSPDFKit.load({
	document: `data:application/pdf;base64,${base64EncodedDocument}`,
	initialViewState: new PSPDFKit.ViewState({
		pageIndex: 8,
		sidebarMode: PSPDFKit.SidebarMode.THUMBNAILS,
	}),
});

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.

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 open Word files in the browser using JavaScript and PSPDFKit. Whether you need to load documents from remote URLs, blobs, array buffers, local storage, or Base64 data, PSPDFKit provides flexible options to meet your requirements. You can customize the viewer settings, such as the initial page and sidebar visibility, to enhance the user experience.

With PSPDFKit, you can elevate your document handling capabilities and empower your users with efficient and intuitive document editing and annotation functionalities.

You can also integrate our JavaScript Word viewer using web frameworks like Angular, Vue.js, and React.js. To see a list of all web frameworks, start your free trial. Or, launch our demo to see our viewer in action.

FAQ

What is PSPDFKit for Web, and how does it enable opening Word files in the browser?

PSPDFKit for Web is a JavaScript library that converts Word files to PDF for viewing in the browser without needing MS Office software.

How do I load a Word document from a remote URL using PSPDFKit?

Use PSPDFKit.load() with the document URL in the configuration object to load a Word file from a remote URL.

Can I open a Word document from local storage or Base64 data with PSPDFKit for Web?

Yes, you can open documents stored in local storage or as Base64 data by passing them in the document property of the configuration object.

What additional capabilities does PSPDFKit’s viewer provide for Word documents?

The viewer allows text editing, page manipulation, annotations, and adding digital signatures to Word documents.

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