Getting Started on Web

Integrate into a Vanilla JavaScript Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Adding to Your Project

PSPDFKit for Web library files are distributed as an archive that can be installed as an npm module.

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web distribution to the assets directory in your project’s folder:

cp -R ./node_modules/pspdfkit/dist/ ./assets/
  1. 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 PDF 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 PSPDFKit.load():

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "Document.pdf",
	})
	.then(function(instance) {
		console.log("PSPDFKit loaded", instance);
	})
	.catch(function(error) {
		console.error(error.message);
	});
</script>

Here’s the full index.html file:

<!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.pdf",
      })
        .then(function(instance) {
          console.log("PSPDFKit loaded", instance);
        })
        .catch(function(error) {
          console.error(error.message);
        });
    </script>
  </body>
</html>

Serving Your Website

You’ll use the npm serve package as a simple HTTP server.

  1. Install the serve package:

yarn global add serve
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.

Next Steps

Integrate into a Vanilla JavaScript Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Adding to Your Project

PSPDFKit for Web library files are distributed as an archive that can be installed as an npm module.

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web distribution to the assets directory in your project’s folder:

cp -R ./node_modules/pspdfkit/dist/ ./assets/
  1. 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 PDF 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. Import pspdfkit into your application and initialize PSPDFKit for Web in JavaScript by calling PSPDFKit.load():

import "./assets/pspdfkit.js";

// We need to inform PSPDFKit where to look for its library assets, i.e. the location of the `pspdfkit-lib` directory.
const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;

PSPDFKit.load({
	baseUrl,
	container: "#pspdfkit",
	document: "<pdf-file-path>",
})
.then(instance => {
	console.log("PSPDFKit loaded", instance);
})
.catch(error => {
	console.error(error.message);
});
  1. Import index.js into your HTML page:

    <script type="module" src="index.js"></script>
    

Here’s the full index.html file:

<!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 type="module" src="index.js"></script>
  </body>
</html>

Serving Your Website

You’ll use the npm serve package as a simple HTTP server.

  1. Install the serve package:

yarn global add serve
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.

Next Steps

Integrate into a Vanilla JavaScript Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Adding to Your Project

PSPDFKit for Web library files are distributed as an archive that can be extracted manually.

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.3.tar.gz to your computer.

  2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to your project’s assets folder.

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

Integrating into Your Project

  1. Add the PDF 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 PSPDFKit.load():

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "Document.pdf",
	})
	.then(function(instance) {
		console.log("PSPDFKit loaded", instance);
	})
	.catch(function(error) {
		console.error(error.message);
	});
</script>

Here’s the full index.html file:

<!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.pdf",
      })
        .then(function(instance) {
          console.log("PSPDFKit loaded", instance);
        })
        .catch(function(error) {
          console.error(error.message);
        });
    </script>
  </body>
</html>

Serving Your Website

You’ll use the npm serve package as a simple HTTP server.

  1. Install the serve package:

yarn global add serve
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.

Next Steps

Integrate into a Vanilla JavaScript Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Adding to Your Project

PSPDFKit for Web library files are distributed as an archive that can be extracted manually.

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.3.tar.gz to your computer.

  2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to your project’s assets folder.

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

Integrating into Your Project

  1. Add the PDF 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. Import pspdfkit into your application and initialize PSPDFKit for Web in JavaScript by calling PSPDFKit.load():

import "./assets/pspdfkit.js";

// We need to inform PSPDFKit where to look for its library assets, i.e. the location of the `pspdfkit-lib` directory.
const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;

PSPDFKit.load({
	baseUrl,
	container: "#pspdfkit",
	document: "<pdf-file-path>",
})
.then(instance => {
	console.log("PSPDFKit loaded", instance);
})
.catch(error => {
	console.error(error.message);
});
  1. Import index.js into your HTML page:

    <script type="module" src="index.js"></script>
    

Here’s the full index.html file:

<!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 type="module" src="index.js"></script>
  </body>
</html>

Serving Your Website

You’ll use the npm serve package as a simple HTTP server.

  1. Install the serve package:

yarn global add serve
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.

Next Steps

Integrate into a React Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Creating a New Project

  1. Create a new React app using the Create React App tool:

yarn create react-app pspdfkit-react-example
npx create-react-app pspdfkit-react-example
  1. Change to the created project directory:

cd pspdfkit-react-example

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib
  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as components/PdfViewerComponent.js:

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		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}/${process.env.PUBLIC_URL}`
		});
	})();

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

return (
	<div ref={containerRef} style={{ width: "100%", height: "100vh"}}/>
);
}
  1. Include the newly created component in App.js:

import PdfViewerComponent from './components/PdfViewerComponent';

function App() {
	return (
		<div className="App">
			<div className="PDF-viewer">
			<PdfViewerComponent
				document={"Document.pdf"}
			/>
			</div>
		</div>
	);
}

export default App;
  1. Your project structure should now look like this:

pspdfkit-react-example
├── public
│   ├── pspdfkit-lib
│   └── Document.pdf
├── src
│   ├── components
│   |   └── PdfViewerComponent.js
|   └── App.js
├── package.json
└── yarn.lock
  1. Start the app and run it in your default browser:

yarn start
npm start

Next Steps

Integrate into a React Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib
  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as components/PdfViewerComponent.js:

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		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}/${process.env.PUBLIC_URL}`
		});
	})();

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

return (
	<div ref={containerRef} style={{ width: "100%", height: "100vh"}}/>
);
}
  1. Include the newly created component in your app:

import PdfViewerComponent from './components/PdfViewerComponent';

// Add the PSPDFKit wrapper component to your `render` function.
function DocumentViewerComponent() {
	return (
		<div className="PDF-viewer">
			<PdfViewerComponent
				document={"Document.pdf"}
			/>
		</div>
	);
}
  1. Start the app and run it in your default browser:

yarn start
npm start

Next Steps

Integrate into an Angular Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Creating a New Project

  1. Install the Angular CLI:

yarn global add @angular/cli
npm install -g @angular/cli
  1. Create a new Angular application:

ng new my-app
  1. The Angular CLI will ask you information about the app configuration. Accept the defaults by repeatedly pressing the Enter key.

  2. Change to the created project directory:

cd my-app

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Add the following to angular.json under the assets option:

"assets": [
	"src/assets",
+	{
+		"glob": "**/*",
+		"input": "./node_modules/pspdfkit/dist/pspdfkit-lib/",
+		"output": "./assets/pspdfkit-lib/"
+	}
]

Angular will now copy the PSPDFKit library assets to the assets directory before running your app.

Displaying a PDF

  1. Add the PDF document you want to display to the src/assets directory. You can use our demo document as an example.

  2. Replace the contents of app.component.html with:

<div class="app">
	<!-- We'll mount the PSPDFKit UI to this element. -->
	<div id="pspdfkit-container" style="width: 100%; height: 100vh"></div>
</div>
  1. Replace the contents of app.component.ts with:

import { Component } from "@angular/core";
import PSPDFKit from "pspdfkit";

@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["app.component.css"]
})
export class AppComponent {
	title = "PSPDFKit for Web Angular Example";

	ngAfterViewInit() {
		PSPDFKit.load({
			// Use the assets directory URL as a base URL. PSPDFKit will download its library assets from here.
			baseUrl: location.protocol + "//" + location.host + "/assets/",
			document: "/assets/Document.pdf",
			container: "#pspdfkit-container",
		}).then(instance => {
			// For the sake of this demo, store the PSPDFKit for Web instance
			// on the global object so that you can open the dev tools and
			// play with the PSPDFKit API.
			(window as any).instance = instance;
		});
	}
}
  1. Start the app and open it in your default browser:

yarn start --open
npm start --open

Next Steps

Integrate into an Angular Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Add the following to angular.json under the assets option:

"assets": [
	"src/assets",
+	{
+		"glob": "**/*",
+		"input": "./node_modules/pspdfkit/dist/pspdfkit-lib/",
+		"output": "./assets/pspdfkit-lib/"
+	}
]

Angular will now copy the PSPDFKit library assets to the assets directory before running your app.

Displaying a PDF

  1. Add the PDF document you want to display to the src/assets directory. You can use our demo document as an example.

  2. Generate a new PDF viewer component:

ng generate component pdf-viewer
  1. Add an empty <div> element with a defined width and height to where PSPDFKit will be mounted:

<div class="pdf-viewer">
	<div id="pspdfkit-container" style="width: 100%; height: 100vh"></div>
</div>
  1. Initialize PSPDFKit in the PDF viewer component:

import { Component, OnInit } from '@angular/core';
import PSPDFKit from 'pspdfkit';

@Component({
	selector: 'pdf-viewer',
	templateUrl: './pdf-viewer.component.html',
	styleUrls: ['./pdf-viewer.component.css']
})
export class PdfViewerComponent implements OnInit {
	ngOnInit(): void {
		PSPDFKit.load({
			// Use the assets directory URL as a base URL. PSPDFKit will download its library assets from here.
			baseUrl: location.protocol + "//" + location.host + "/assets/",
			document: "/assets/Document.pdf",
			container: "#pspdfkit-container",
		}).then(instance => {
			// For the sake of this demo, store the PSPDFKit for Web instance
			// on the global object so that you can open the dev tools and
			// play with the PSPDFKit API.
			(window as any).instance = instance;
		});
	}
}
  1. Add the new viewer component. Here, we add it to the main application component:

<div class="app">
	<pdf-viewer></pdf-viewer>
</div>
  1. Start the app and open it in your default browser:

yarn start --open
npm start --open

Next Steps

Integrate into a Vue.js Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Installing the Vue.js CLI

First install the Vue.js command-line tool for managing your Vue.js projects:

yarn global add @vue/cli
npm install -g @vue/cli

Creating the Project

  1. Create a new Vue.js app:

vue create my-app
  1. Select Default ([Vue 2] babel, eslint) from the list.

Activity controller

  1. Select the package manager you want to use (we recommend Yarn).

  2. Change to the created project directory:

cd my-app

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

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

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as src/components/pspdfkit.vue:

<template>
	<div class="container" style="height: 100vh; width: 100vw;"></div>
</template>
<script>

import PSPDFKit from 'pspdfkit';

// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.
const baseUrl = `${window.location.protocol}//${window.location.host}/`;

/**
 * PSPDFKit for Web example component
 */
export default {
	name: 'PSPDFKit',
	/**
	 * The component receives these parameters:
	 * @documentUrl: string — URL of the document to be loaded.
	 * @baseUrl: string — URL from which the PSPDFKit library should get its payload and artifacts
	 */
	props: ["documentUrl"],
	_instance: null,
	/**
	* We wait until the template has been rendered to load the document into the library.
	*/
	mounted: function mounted() {
		this.load();
	},
	/**
	 * Our component has these two methods — one to trigger document loading, and the other to unload and clean up
	 * so the component is ready to load another document.
	 */
	methods: {
		load: function load() {
				PSPDFKit.load({
					baseUrl: baseUrl,
					document: this.documentUrl,
					container: ".container"
				})
		},
		unload: function unload() {
				if (this._instance) {
					PSPDFKit.unload(this._instance || ".container");
					this._instance = null;
				}
		}
	},
	/**
	 * We watch for `documentUrl` prop changes and trigger unloading and loading when there's a new document to load.
	 */
	watch: {
		documentUrl: function documentUrl() {
				this.unload();
				this.load();
		}
	},
	/**
	 * Clean up when the component is unmounted (not needed in this example).
	 */
	beforeDestroy: function beforeDestroy() {
		this.unload();
	}
}
</script>
  1. Include the newly created component in src/App.vue:

<template>
	<PSPDFKit
		documentUrl="Document.pdf"
	/>
</template>

<script>
import PSPDFKit from './components/pspdfkit.vue'

export default {
	name: 'App',
	components: {
		PSPDFKit
	}
}
</script>
  1. Start the app:

yarn serve
npm serve
  1. Open http://localhost:8080/ in your browser.

Next Steps

Integrate into a Vue.js Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

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

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as src/components/pspdfkit.vue:

<template>
	<div class="container" style="height: 100vh; width: 100vw;"></div>
</template>
<script>

import PSPDFKit from 'pspdfkit';

// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.
const baseUrl = `${window.location.protocol}//${window.location.host}/`;

/**
 * PSPDFKit for Web example component
 */
export default {
	name: 'PSPDFKit',
	/**
	 * The component receives these parameters:
	 * @documentUrl: string — URL of the document to be loaded.
	 * @baseUrl: string — URL from which the PSPDFKit library should get its payload and artifacts
	 */
	props: ["documentUrl"],
	_instance: null,
	/**
	* We wait until the template has been rendered to load the document into the library.
	*/
	mounted: function mounted() {
		this.load();
	},
	/**
	 * Our component has these two methods — one to trigger document loading, and the other to unload and clean up
	 * so the component is ready to load another document.
	 */
	methods: {
		load: function load() {
				PSPDFKit.load({
					baseUrl: baseUrl,
					document: this.documentUrl,
					container: ".container"
				})
		},
		unload: function unload() {
				if (this._instance) {
					PSPDFKit.unload(this._instance || ".container");
					this._instance = null;
				}
		}
	},
	/**
	 * We watch for `documentUrl` prop changes and trigger unloading and loading when there's a new document to load.
	 */
	watch: {
		documentUrl: function documentUrl() {
				this.unload();
				this.load();
		}
	},
	/**
	 * Clean up when the component is unmounted (not needed in this example).
	 */
	beforeDestroy: function beforeDestroy() {
		this.unload();
	}
}
</script>
  1. Include the PSPDFKit component in your app:

<template>
	<PSPDFKit
		documentUrl="Document.pdf"
	/>
</template>

<script>
import PSPDFKit from './components/pspdfkit.vue'

export default {
	name: 'PdfViewerComponent',
	components: {
		PSPDFKit
	}
}
</script>
  1. Start the app:

yarn serve
npm serve
  1. Open http://localhost:8080/ in your browser.

Next Steps

Integrate into a Svelte Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Creating a New Project

  1. Create a new Svelte app using the degit tool with the Svelte template:

npx degit sveltejs/template my-svelte-project
  1. Change to the created project directory:

cd my-svelte-project
  1. Install the dependencies:

yarn install
npm install

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib
  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as src/PdfViewerComponent.svelte:

  <script>
      import { afterUpdate, onMount, onDestroy, beforeUpdate } from 'svelte';
      import PSPDFKit from 'pspdfkit'

      let currentDocument
      let container
      let instance

      export let document

      async function load() {
          currentDocument = document
          instance = await PSPDFKit.load({
              baseUrl: `${window.location.protocol}//${window.location.host}/`,
              container: container,
              document: document
          })
      }

      function unload() {
          PSPDFKit.unload(instance)
          instance = null
      }

      onMount(() => {
          load()
      })

      afterUpdate(() => {
          if (document !== currentDocument) {
              unload()
              load()
          }
      })

      onDestroy(() => {
          unload()
      })

  </script>
  <body>
      <div bind:this={container} style="height: 100vh; width: 100vw;"></div>
  </body>
  1. Include the newly created component in App.svelte:

  <script>
    import Pspdfkit from './Pspdfkit.svelte';
  </script>

  <main>
    <Pspdfkit document='Document.pdf'/>
  </main>
  1. Start the app:

yarn run dev
npm run dev
  1. Open http://localhost:5000 in your browser.

Next Steps

Integrate into a Svelte Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib
  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as src/PdfViewerComponent.svelte:

  <script>
      import { afterUpdate, onMount, onDestroy, beforeUpdate } from 'svelte';
      import PSPDFKit from 'pspdfkit'

      let currentDocument
      let container
      let instance

      export let document

      async function load() {
          currentDocument = document
          instance = await PSPDFKit.load({
              baseUrl: `${window.location.protocol}//${window.location.host}/`,
              container: container,
              document: document
          })
      }

      function unload() {
          PSPDFKit.unload(instance)
          instance = null
      }

      onMount(() => {
          load()
      })

      afterUpdate(() => {
          if (document !== currentDocument) {
              unload()
              load()
          }
      })

      onDestroy(() => {
          unload()
      })

  </script>
  <body>
      <div bind:this={container} style="height: 100vh; width: 100vw;"></div>
  </body>
  1. Include the PSPDFKit component in your app:

  <script>
    import Pspdfkit from './Pspdfkit.svelte';
  </script>

  <main>
    <Pspdfkit document='Document.pdf'/>
  </main>
  1. Start the app:

yarn run dev
npm run dev
  1. Open http://localhost:5000 in your browser.

Next Steps

Integrate into a PWA Project

In this guide, you’ll configure your PSPDFKit project for deployment as a progressive web app (PWA).

It will tick the majority of the boxes of the baseline PWA checklist. We’ve already built a more advanced implementation of this example, which you can try live on our website.

If you’ve never heard about PWAs and want to find out more about them, we highly recommend you check out the dedicated site from Google. You can also read our blog post on PWAs.

Prerequisites

This guide assumes you’ve already configured PSPDFKit for your specific framework. If you haven’t, select your framework from the list above and configure PSPDFKit. Then return to this guide.

Our PWA must be served by a web server over HTTPS, so please make sure your server is configured to serve pages in HTTPS. In development, however, we don’t need HTTPS since browsers treat localhost as a secure origin.

A Note about Progressive Enhancement

By definition, PWAs are progressive, meaning they’re inclusive and they rely heavily on progressive enhancement. When building a PWA, it’s good to always keep this in mind and provide a basic experience for every user of the application.

Richer features should be built on top of an always-working barebones implementation. We highly recommend using feature detection to provide progressive enhancement so that applications won’t break in older browsers that don’t support a specific feature.

Opening a PDF File

To read the PDF, you’ll need a helper to read the selected file from disk using the FileReader API:

function registerFilePicker(element, callback) { ... }
/* ./src/app.js */

function registerFilePicker(element, callback) {
  function handler(event) {
    if (event.target.files.length == 0) {
      event.target.value = null;
      return;
    }
    var pdfFile = event.target.files[0];
    if (pdfFile.type !== "application/pdf") {
      alert("Invalid file type, please load a PDF.");
      return;
    }

    var reader = new FileReader();
    reader.addEventListener("load", function(event) {
      var pdf = event.target.result;
      callback(pdf, pdfFile);
    });
    reader.addEventListener("error", function(error) {
      alert(error.message);
    });
    reader.readAsArrayBuffer(pdfFile);
    event.target.value = null;
  }

  element.addEventListener("change", handler);

  return function() {
    element.removeEventListener("change", handler);
  };
}

callback is a function that gets the pdf in the ArrayBuffer format so that you can load it directly with PSPDFKit. It also gets the selected File object.

Once you have this helper, you can add the code to initialize PSPDFKit for Web:

./src/app.js
var pspdfkitInstance = null;
var filePicker = document.querySelector('input[type="file"]');

registerFilePicker(filePicker, function(pdf, fileInfo) {
	if (pspdfkitInstance) {
		PSPDFKit.unload(pspdfkitInstance);
	}

	PSPDFKit.load({
		document: pdf,
		container: ".PSPDFKit-container",
		// See https://pspdfkit.com/api/web/PSPDFKit.Configuration.html#enableServiceWorkerSupport
		enableServiceWorkerSupport: true
	}).then(function(instance) {
		pspdfkitInstance = instance;
	});
});

Our advanced PWA example allows us to load PDF files from a remote server, and it uses IndexedDB to cache them locally for offline use. It also uses the History API to easily load files via URL.

Adding Caching and Offline Capabilities with Service Workers

One of the most important features of PWAs is the ability to load fast and to work on slow network conditions, or even offline. To achieve this, you can use a service worker to cache the application shell and, when available, use the network only to fetch necessary data.

The service worker is a script you register in the application shell. It runs in the background, separate from a webpage. It can intercept and handle network requests, allowing you to cache responses programmatically.

In case you’re not familiar with service workers, we highly recommend you read this excellent introductory blog post.

Now, create the ./serviceWorker.js file:

/* ./serviceWorker.js */

console.log("Hello from the Service Worker");

Then, register it in your application shell:

<!-- ./src/index.html -->

<!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
      />
      <title>PSPDFKit PWA</title>

+      <script>
+        if ('serviceWorker' in navigator) {
+          window.addEventListener('load', function () {
+            navigator.serviceWorker.register('./serviceWorker.js')
+          })
+        }
+      </script>

This uses feature detection to determine whether service workers are supported and to register your serviceWorker.js when the feature is available.

You can now start your application and try it out in a web browser. In the Application tab of Chrome Dev Tools, you’ll see that your service worker has been registered and is active!

Chrome Developers Tools: Application Tab. Shows the registered Service Worker.

For local development, it’s a good idea to check the Update on reload option so that the service worker is updated every time the page reloads. You can clear the service worker storage any time from this panel using the Clear storage view.

A Note about the Service Worker API

The Service Worker API is low level, flexible, and powerful. Because of this, it usually requires some boilerplate code to do common tasks like activate the service worker, intercept requests and cache responses, clear the cache, and precache files.

To simplify those tasks, Google developed Workbox, an open source library that abstracts away all the complexity and makes building PWAs easy. Before deploying to production, we recommend using Workbox to manage your service workers.

Workbox can help with doing more than precaching, and it allows you to configure how each resource should be cached and how routes should be handled.

Complex applications will likely need to use the network to fetch data before they can render content in the app shell. In those cases, it’s important to choose the correct caching strategy for your data.

Please refer to the Workbox website to learn more about how to handle advanced use cases.

Final Touches

Now that your app has offline capabilities, you only need to add a web app manifest to make the application recognizable by the web browser and to describe how the app should behave when installed on users’ devices.

The web app manifest is a file whose name is manifest.json. It contains metadata like the name of the app, the paths to icons and their sizes, the start URL, and the theme color. Now you’ll create a basic one for your PWA:

touch ./src/manifest.json
{
  "name": "PSPDFKit for Web PWA",
  "short_name": "PSPDFKit",
  "icons": [
    {
      "src": "images/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "images/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "background_color": "#0089AA",
  "theme_color": "#0089AA"
}

Finally, you need to register the manifest in the app pages — in your case, index.html:

<!-- ./src/index.html -->

<title>PSPDFKit PWA</title>
<script>
  if ("serviceWorker" in navigator) {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register('./serviceWorker.js')
    })
  }
</script>

+<link rel="manifest" href="./manifest.json">

You can verify the manifest in the Application tab of Chrome Dev Tools:

Manifest file in the dev tools.

The web app manifest also makes it possible to display an App Install Banner or an Add to Home Screen dialog. You can follow the guidelines from Google to learn how to create and display one.

Limitations

Disk Quota

Web browsers define quotas either per origin (Chrome and Opera) or per API (e.g. IndexedDB, service workers). When storing files via web APIs, it’s a good idea to keep this in mind and ideally monitor the disk quota status to avoid failures. Apps can check how much quota they’re using with the Quota Management API. We highly recommend you check out this research report on browser storage from HTML5 Rocks.

Precached PSPDFKit Assets

In this guide, you saw how to precache all the PSPDFKit for Web assets, including the JavaScript fallback pspdfkit.asm.js. However, when the target browser supports WebAssembly, it’d be better to exclude this file from the precache manifest and vice versa: When the target browser doesn’t support WebAssembly, you shouldn’t precache the WASM module pspdfkit.wasm. For production applications, we recommend generating separate manifests and service workers and serving them conditionally.

Conclusion

Hopefully the above information demonstrated how easy it is to integrate PSPDFKit for Web and make a simple PWA to display PDF documents. This is possible thanks to Workbox, which provides a simple yet powerful abstraction on top of the Service Worker API.

The PWA built in this guide meets all the requirements of a baseline PWA, however, it’s just a proof of concept that shouldn’t be used in production.

We also built a more comprehensive and advanced example where PDF documents can be fetched from a remote server and are stored locally in IndexedDB for offline use. The advanced example also uses the History API to provide a unique working URL for every PDF document, along with a connectivity status indicator.

If you want to learn more about progressive web apps, we highly encourage you to check out the following resources:

Integrate into an Electron Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Creating a New Project

  1. Initialize a new npm workspace in an empty directory:

yarn init -y
npm init -y
  1. Install Electron as a dev dependency:

yarn add --dev electron
npm install --save-dev electron
  1. Modify your package.json to add the start script:

{
	"name": "PSPDFKit Electron Example",
	"version": "1.0.0",
	"main": "index.js",
	"license": "MIT",
	"devDependencies": {
		"electron": "^11.3.0"
	},
	"scripts": {
		"start": "electron ."
	}
}

Adding PSPDFKit

PSPDFKit for Electron is installed as an npm package. This will add a pspdfkit dependency to your application’s package.json:

yarn add pspdfkit
npm install --save pspdfkit

Displaying a PDF

  1. Add the PDF document you want to display to the assets directory. You can use our demo document as an example.

  2. Create an index.html file to set up a mount target in the HTML file of your renderer process:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<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>
			// Invoke the JavaScript for the renderer process.
			require("./renderer.js");
		</script>
	</body>
</html>
  1. Load PSPDFKit in the JavaScript file of your renderer process:

const PSPDFKit = require("pspdfkit");

PSPDFKit.load({
container: "#pspdfkit",
document: `assets/Document.pdf`,
})
.then(function (instance) {
	console.log("PSPDFKit loaded", instance);
})
.catch(function (error) {
	console.error(error.message);
});
  1. Create the main JavaScript file:

const { app, BrowserWindow, protocol } = require('electron')

// Make sure to enable access to the local file system. This is required
// in order to load PDF files and PSPDFKit dependencies from the local
// file system.
protocol.registerSchemesAsPrivileged([
	{ scheme: "file", privileges: { secure: true, standard: true } }
]);

// Keep a global reference of the window object. If you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
	mainWindow = new BrowserWindow({
		width: 800,
		height: 600,
		webPreferences: {
			nodeIntegration: true,
			enableRemoteModule: true,
			contextIsolation: false
		}
	})

	mainWindow.loadFile("index.html");

	// Emitted when the window is closed.
	mainWindow.on("closed", function() {
		// Dereference the window object to allow it to be garbage collected.
		mainWindow = null;
	});
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

app.on('activate', () => {
	if (BrowserWindow.getAllWindows().length === 0) {
		createWindow()
	}
})
  1. Your project should have the following structure now:

pspdfkit-electron-example
├── assets
|   └── Document.pdf
├── package.json
├── index.js
├── renderer.js
└── index.html
  1. Start the app:

yarn start
npm start

Next Steps

Integrate into an Electron Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Adding PSPDFKit

PSPDFKit for Electron is installed as an npm package. This will add a pspdfkit dependency to your application’s package.json:

yarn add pspdfkit
npm install --save pspdfkit

Displaying a PDF

  1. Add the PDF document you want to display to the assets directory. You can use our demo document as an example.

  2. Set up a mount target in the HTML file of your renderer process:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<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>
			// Invoke the JavaScript for the renderer process.
			require("./renderer.js");
		</script>
	</body>
</html>
  1. Load PSPDFKit in the JavaScript file of your renderer process:

const PSPDFKit = require("pspdfkit");

PSPDFKit.load({
container: "#pspdfkit",
document: `assets/Document.pdf`,
})
.then(function (instance) {
	console.log("PSPDFKit loaded", instance);
})
.catch(function (error) {
	console.error(error.message);
});
  1. Make sure you’ve enabled the file protocol in your main process:

// Enables access to the local file system. This is required in order
// to load PDF files and PSPDFKit dependencies from the local file system.
protocol.registerSchemesAsPrivileged([
	{ scheme: "file", privileges: { secure: true, standard: true } }
]);
  1. Enable node integration and remote modules, and disable context isolation. You can do this by passing an additional argument when initializing the browser window:

// Keep a global reference of the window object. If you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
	// Create the browser window.
	mainWindow = new BrowserWindow({
		webPreferences: {
			// Enables `require()` to import modules at runtime when running on Electron.
			nodeIntegration: true,
			// Enables access to `electron.remote` from the renderer process.
			enableRemoteModule: true,
			// Enables `require()` to import modules from the renderer process.
			contextIsolation: false
		}
		// ...
	});
}
  1. Start the app:

yarn start
npm start

Next Steps

Integrate into a Next.js Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Creating a New Project

  1. Create a new Next.js app using the create-next-app tool:

yarn create next-app pspdfkit-next-js-example
npx create-next-app pspdfkit-next-js-example
  1. Change to the created project directory:

cd pspdfkit-next-js-example

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib
  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Create a React component wrapper for the PSPDFKit library and save it with the name components/PdfViewerComponent.js:

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		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}/}`
		});
	})();

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

return (
	<div ref={containerRef} style={{ width: "100%", height: "100vh"}}/>
);
}
  1. Add the newly created component to pages/index.js:

import PdfViewerComponent from '../components/PdfViewerComponent'

export default function Home() {
	return (
		<PdfViewerComponent
			document={"Document.pdf"}
		/>
	)
}
  1. Your project structure should now look like this:

pspdfkit-next-js-example
├── components
│   └── PdfViewerComponent.js
├── package.json
├── pages
│   └── index.js
├── public
│   ├── Document.pdf
│   └── pspdfkit-lib
└── yarn.lock
  1. Start the app:

yarn dev
npm dev
  1. Navigate to http://localhost:3000 to view the website.

Next Steps

Integrate into a Next.js Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install --save pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib
  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Create a React component wrapper for the PSPDFKit library and save it with the name components/PdfViewerComponent.js:

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		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}/}`
		});
	})();

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

return (
	<div ref={containerRef} style={{ width: "100%", height: "100vh"}}/>
);
}
  1. Add the newly created component to your page’s render function:

import PdfViewerComponent from '../components/PdfViewerComponent'

export default function PdfViewer() {
	return (
		<PdfViewerComponent
			document={"Document.pdf"}
		/>
	)
}
  1. Start the app:

yarn dev
npm dev
  1. Navigate to http://localhost:3000 to view the website.

Next Steps

Integrate into an ASP.NET Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

  • Visual Studio 2019 or above

Creating a New Project

  1. Open Visual Studio and select New Solution in the File > New Solution… menu to create a new project for your application:

visual-studio-new-solution

  1. Choose the ASP.NET MVC Project template:

visual-studio-template

  1. When prompted, choose your app name (PSPDFKitExample) and use the default options:

visual-studio-project-name

  1. Finish the project creation by confirming the next dialog steps.

Adding PSPDFKit

PSPDFKit for Web library files are distributed as an archive that can be extracted manually:

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.3.tar.gz to your computer.

  2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to the Content/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

Integrate PSPDFKit directly in your app’s index view, Views/Home/Index.cshtml:

  1. Include pspdfkit.js. The path is relative to the wwwroot directory:

<script src="/Content/pspdfkit/pspdfkit.js>"></script>
  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. Initialize PSPDFKit for Web by calling PSPDFKit.load():

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "/Content/Document.pdf",
	})
		.then(function(instance) {
			console.log("PSPDFKit loaded", instance);
		})
		.catch(function(error) {
			console.error(error.message);
		});
</script>

Here’s the full Views/Home/Index.cshtml:

Views/Home/Index.cshtml
<!-- Include PSPDFKit library -->
<script src="/Content/pspdfkit/pspdfkit.js>"></script>

<!-- Element where PSPDFKit will be mounted. -->
<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

<!-- Initialize PSPDFKit. -->
<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "/Content/Document.pdf",
	})
		.then(function (pspdfkitInstance) {
			console.log("PSPDFKit loaded", pspdfkitInstance);
		})
		.catch(function (error) {
			console.error(error.message);
		});
</script>

Displaying the PDF

  1. Add the PDF document you want to display to the wwwroot directory. You can use our demo document as an example.

  2. Select Run > Start Debugging. This will start your app and open it in your default browser.

Next Steps

Integrate into an ASP.NET Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Creating a New Project

  1. Create a new ASP.NET Core Web App (Model-View-Controller):

dotnet new mvc -o pspdfkit-example
  1. Change to the created project directory:

cd pspdfkit-example

Adding PSPDFKit

PSPDFKit for Web library files are distributed as an archive that can be extracted manually:

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.3.tar.gz to your computer.

  2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to the wwwroot/lib/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

Integrate PSPDFKit directly in your app’s index view, Views/Home/Index.cshtml:

  1. Include pspdfkit.js. The path is relative to the wwwroot directory:

<script src="/lib/pspdfkit/pspdfkit.js>"></script>
  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. Initialize PSPDFKit for Web by calling PSPDFKit.load():

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "/Document.pdf",
	})
		.then(function(instance) {
			console.log("PSPDFKit loaded", instance);
		})
		.catch(function(error) {
			console.error(error.message);
		});
</script>

Here’s the full Views/Home/Index.cshtml:

Views/Home/Index.cshtml
<!-- Include PSPDFKit library -->
<script src="/lib/pspdfkit/pspdfkit.js>"></script>

<!-- Element where PSPDFKit will be mounted. -->
<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

<!-- Initialize PSPDFKit. -->
<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "/Document.pdf",
	})
		.then(function (pspdfkitInstance) {
			console.log("PSPDFKit loaded", pspdfkitInstance);
		})
		.catch(function (error) {
			console.error(error.message);
		});
</script>

Displaying the PDF

  1. Add the PDF document you want to display to the wwwroot directory. You can use our demo document as an example.

  2. Start the app and run it in your default browser:

dotnet watch run

Next Steps

Integrate into an ASP.NET Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

  • Visual Studio 2019 or above

Adding PSPDFKit

PSPDFKit for Web library files are distributed as an archive that can be extracted manually:

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.3.tar.gz to your computer.

  2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to the Content/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

Integrate PSPDFKit in your view:

  1. Include pspdfkit.js. The path is relative to the wwwroot directory:

<script src="/Content/pspdfkit/pspdfkit.js>"></script>
  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. Initialize PSPDFKit for Web by calling PSPDFKit.load():

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "/Content/Document.pdf",
	})
		.then(function(instance) {
			console.log("PSPDFKit loaded", instance);
		})
		.catch(function(error) {
			console.error(error.message);
		});
</script>

Displaying the PDF

  1. Add the PDF document you want to display to the wwwroot directory. You can use our demo document as an example.

  2. Select Run > Start Debugging. This will start your app and open it in your default browser.

Next Steps

Integrate into an ASP.NET Project

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit UI.

Requirements

Adding PSPDFKit

PSPDFKit for Web library files are distributed as an archive that can be extracted manually:

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.3.tar.gz to your computer.

  2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to the wwwroot/lib/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

Integrate PSPDFKit in your view:

  1. Include pspdfkit.js. The path is relative to the wwwroot directory:

<script src="/lib/pspdfkit/pspdfkit.js>"></script>
  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. Initialize PSPDFKit for Web by calling PSPDFKit.load():

<script>
	PSPDFKit.load({
		container: "#pspdfkit",
		document: "/Document.pdf",
	})
		.then(function(instance) {
			console.log("PSPDFKit loaded", instance);
		})
		.catch(function(error) {
			console.error(error.message);
		});
</script>

Displaying the PDF

  1. Add the PDF document you want to display to the wwwroot directory. You can use our demo document as an example.

  2. Start the app and run it in your default browser:

dotnet watch run

Next Steps