Blog Post

Build a Powerful JavaScript Document Viewer and Editor

Hulya Masharipov
Illustration: Build a Powerful JavaScript Document Viewer and Editor

Managing documents within web applications is essential for organizations across various industries, including healthcare, engineering, finance, and more. This tutorial guides you through setting up a robust JavaScript-based document viewer and editor using the PSPDFKit Document Authoring SDK. You’ll learn how to handle Microsoft Word (DOCX) files directly in your browser, without the need for external software.

Introducing the PSPDFKit Document Authoring SDK

PSPDFKit’s Document Authoring SDK offers a comprehensive solution for building an advanced document viewer and editor within your web application. With a familiar WYSIWYG (what you see is what you get) interface, similar to Google Docs or Microsoft Word, the SDK allows users to open, edit, and export complex documents, maintaining perfect fidelity across browsers and when exported to PDF or DOCX. This makes it an ideal tool for handling documents accurately and efficiently.

Key Benefits of Using the Document Authoring SDK

Below, we’ve outlined a few key benefits of using the Document Authoring SDK.

A Familiar and Intuitive Editing Experience

The SDK provides a page-based layout for rich text editing that resembles the interfaces of popular document editing tools. This familiarity helps users quickly adapt to the editor, enhancing productivity and user satisfaction. With advanced features like complex tables, floating images, headers, footers, and sophisticated numbering, it goes beyond the capabilities of standard text areas and other rich text libraries.

Perfect Fidelity and Consistency across Platforms

One of the standout features of the Document Authoring SDK is its ability to ensure documents look exactly the same across all browsers and when exported in PDF or DOCX formats. This is particularly important for industries that require precision, such as legal, finance, and publishing. The SDK is the only product on the market that guarantees 100 percent WYSIWYG fidelity in PDF exports, streamlining workflows and reducing errors caused by document inconsistencies.

Seamless Integration and Customization

The SDK is designed with our fully customizable Baseline UI, allowing developers to easily integrate it into any web application and customize it to fit their specific needs. This flexibility ensures that the document viewer and editor align with the overall design and functionality of your platform, providing a consistent user experience.

Getting Started with the Document Authoring SDK

In this tutorial, you’ll learn how to set up the PSPDFKit Document Authoring SDK to create a powerful JavaScript-based document viewer and editor that supports DOCX files. You’ll use Vite as your development environment to ensure a fast and efficient setup.

Step 1 — Creating a New Vite Project

First, create a new Vite project. Vite offers a modern development experience with fast project setup:

npm create vite@latest my-document-app
cd my-document-app

Select vanilla for the framework and JavaScript for the variant. This command sets up a new Vite project in the specified directory.

Step 2 — Installing the PSPDFKit Document Authoring SDK

Next, install the PSPDFKit Document Authoring SDK, which provides the tools needed to implement the document editor and viewer:

npm install @pspdfkit/document-authoring

The SDK leverages WebAssembly (Wasm) to deliver high performance, enabling in-browser document editing without the need for server-side processing.

Step 3 — Integrating the Document Editor and Viewer

To integrate the editor and viewer into your project, follow the steps outlined below.

  1. In index.html, create a <div> element where the editor will be rendered:

<div
	id="editor"
	style="position: relative; width: 100%; height: 100vh; border: 1px solid #dcdcdc;"
></div>
  1. In main.js, add the following JavaScript code to import the PSPDFKit library and set up the editor:

import { createDocAuthSystem } from '@pspdfkit/document-authoring';

(async () => {
	const docAuthSystem = await createDocAuthSystem();
	const editor = await docAuthSystem.createEditor(
		document.getElementById('editor'),
		{
			document: await docAuthSystem.createDocumentFromPlaintext(
				'Hello world!',
			),
		},
	);
})();

This code initializes the document authoring system, creates an editor instance, and loads a sample document.

Step 4 — Running the Vite Development Server

Start the Vite development server to view your editor in action:

npm run dev

Open your browser and go to the provided local URL to see the JavaScript document editor and viewer in operation.

Working with DOCX Files

The PSPDFKit Document Authoring SDK supports importing and exporting DOCX files, allowing for seamless document handling.

Importing DOCX Files

To load a DOCX file into your editor, use the importDOCX method:

// Assuming the `docAuthSystem` instance is initialized.

const document = await docAuthSystem.importDOCX(
	await fetch('/document.docx'),
);

const editor = await docAuthSystem.createEditor(
	document.getElementById('editor'),
	{ document },
);

This code fetches a DOCX file from the specified URL and loads it into the editor.

To see this in action, you can try out the demo to experience the document loading and editing functionality directly.

Explore Demo

Exporting DOCX Files

To export the current document as a DOCX file, use the exportDOCX method:

// Assuming the `editor` instance is initialized.

const currentDoc = editor.currentDocument();
const doc = await currentDoc.exportDOCX();

The exported DOCX file is returned as an ArrayBuffer, which you can then save or use as needed.

Working with PDF Files

The PSPDFKit Document Authoring SDK also supports exporting documents to PDF without additional setup. Use the exportPDF method:

// Assuming the `editor` instance is initialized.

const currentDoc = editor.currentDocument();
const doc = await currentDoc.exportPDF();

This method returns the PDF file as an ArrayBuffer, allowing you to handle it as required.

First-Class JSON Support with DocJSON

DocJSON is the internal format used by the PSPDFKit Document Authoring SDK for high portability and integration with modern web technologies. It retains key features of existing formats while being more compatible with JSON-based workflows.

Working with DocJSON in the Editor

DocJSON is used when loading and saving documents. It’s designed for easy customization and integration.

Loading DocJSON:

// Assuming the `docAuthSystem` instance is initialized.

const document = await docAuthSystem.loadDocument(
	await fetch('./document.json').then((response) => response.json()),
);

const editor = await docAuthSystem.createEditor(
	document.getElementById('editor'),
	{ document },
);

Saving DocJSON:

// Assuming the `editor` instance is initialized.

const currentDoc = editor.currentDocument();

const docObj = await currentDoc.saveDocument();
console.log('JS object', docObj);

const docJSON = await currentDoc.saveDocumentJSONString();
console.log('JSON string', docJSON);

Here, the document is saved as both a JavaScript object and a JSON string.

Example DocJSON Format

Here’s a simple example of a DocJSON document:

{
	"type": "https://pspdfkit.com/document-authoring/persistence/container",
	"version": 1,
	"container": {
		"document": {
			"body": {
				"sections": [
					{
						"elements": [
							{
								"type": "p",
								"elements": [
									{
										"type": "r",
										"text": "Hello world!"
									}
								]
							}
						]
					}
				]
			}
		}
	}
}

The example illustrates the basic structure of a DocJSON document. This JSON format is designed to represent documents in a straightforward manner, with formatting styles and page setups being optional and defaulting to standard settings if not specified.

In this example, the JSON format is version 1 and organizes documents as a body containing sections. Each section includes various elements, which can be of different types and include inline content.

Specifically, this document consists of a single paragraph with one text run displaying “Hello world!”. Unlike HTML, where elements can be nested, DocJSON represents inline elements like text runs as a flat sequence.

Conclusion

Setting up a JavaScript-based DOCX editor and viewer with the PSPDFKit Document Authoring SDK and Vite is efficient and effective. This solution enables seamless handling of DOCX files directly in the browser, eliminating the need for external tools.

The SDK supports DocJSON for easy integration and customization, making it a versatile choice for web development needs.

To explore more features or discuss how the SDK can fit your specific requirements, contact our Sales team for further assistance. Try the demo to see the SDK in action and get started with your document editing and viewing solution today!

FAQ

Here are a few frequently asked questions about our Document Authoring SDK.

What is the PSPDFKit Document Authoring SDK, and what are its main features?

The PSPDFKit Document Authoring SDK is a comprehensive toolkit for building a document viewer and editor directly within web applications. It offers a WYSIWYG (what you see is what you get) interface, similar to popular tools like Google Docs and Microsoft Word, allowing users to open, edit, and export DOCX documents with perfect fidelity. Key features include support for complex tables, floating images, headers, footers, sophisticated numbering, and 100 percent accurate PDF exports.

How does the Document Authoring SDK ensure 100 percent fidelity for DOCX and PDF exports?

The SDK guarantees perfect fidelity by rendering documents exactly the same way across all browsers and when exporting to DOCX or PDF. It uses advanced rendering algorithms and internal document representations to maintain accurate formatting, layout, and styles, ensuring the exported documents look identical to their in-browser versions.

Can I customize the Document Authoring SDK’s UI to match my application’s design?

Yes, the SDK comes with our fully customizable Baseline UI. Developers can easily modify the appearance and behavior of the editor to fit the specific design and functionality of their web applications, ensuring a consistent user experience across the platform.

Does the SDK support importing and exporting both DOCX and PDF files?

The SDK supports importing DOCX files and exporting documents in both DOCX and PDF formats. This makes it versatile for various use cases where you need to handle DOCX input and PDF output.

What is DocJSON, and how is it used in the PSPDFKit Document Authoring SDK?

DocJSON is the internal format used by the PSPDFKit Document Authoring SDK for document editing and storage. It offers high portability and is designed for easy integration with modern web technologies. DocJSON retains key features of traditional document formats while allowing seamless integration with JSON-based workflows.

Author
Hulya Masharipov 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
Document Authoring

Product Page
Guides
Example Projects

Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
TUTORIALS  |  How To • JavaScript • PDF Editor

Top JavaScript PDF Editors for Your Web Applications

TUTORIALS  |  API • Python • How To

How to Convert DOCX to WebP Using Python

TUTORIALS  |  iOS • How To • PDF • Swift • Signing

How to Sign a PDF on iOS with PSPDFKit's Signature Library