Get Started with Our Free Trial

Information

As of July 2021, our products no longer require a trial license key.

Illustration of rocket lift off

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.

If you prefer a video tutorial, watch our step-by-step Getting Started with PSPDFKit video guide.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this 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>

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.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.

Getting Started Video Guide

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.

If you prefer a video tutorial, watch our step-by-step Getting Started with PSPDFKit video guide.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this 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: "document.pdf"
})
.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>

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 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.

Getting Started Video Guide

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.

If you prefer a video tutorial, watch our step-by-step Getting Started with PSPDFKit video guide.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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-2022.5.1.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.

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this 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>

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.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.

Getting Started Video Guide

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.

If you prefer a video tutorial, watch our step-by-step Getting Started with PSPDFKit video guide.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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-2022.5.1.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.

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this 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: "document.pdf"
})
.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>

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 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.

Getting Started Video Guide

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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the src/components/ folder, create the PdfViewerComponent.js file with the following content. This adds a component wrapper for the PSPDFKit library:

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. In the src folder, replace the contents of the App.js file with the following. This includes the newly created component in your app:

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
pspdfkit-react-example
├── public
│   ├── pspdfkit-lib
│   └── document.pdf
├── src
│   ├── components
│   |   └── PdfViewerComponent.js
|   └── App.js
├── package.json
└── package-lock.json
  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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the src/components/ folder, create the PdfViewerComponent.js file with the following content. This adds a component wrapper for the PSPDFKit library:

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. In your app, add the following below the lines beginning with import. This includes the newly created component in your app:

import PdfViewerComponent from './components/PdfViewerComponent';

function DocumentViewerComponent() {
	return (
		<div className="PDF-viewer">
			<PdfViewerComponent
				document={"document.pdf"}
			/>
		</div>
	);
}
  1. Add the following to the rendering function in your app:

DocumentViewerComponent()
  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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

  2. In the angular.json file, add the following to 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. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the src/assets directory. You can use this demo document as an example.

  2. In the src/app/ folder, replace the contents of the app.component.html file with the following:

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

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. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

  2. In the angular.json file, add the following to 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. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the src/assets directory. You can use this demo document as an example.

  2. Generate a new PDF viewer component:

ng generate component pdf-viewer
  1. In the src/app/pdf-viewer folder, replace the contents of the pdf-viewer.component.html file with the following:

<div class="pdf-viewer">
	<div id="pspdfkit-container" style="width: 100%; height: 100vh"></div>
</div>
  1. In the src/app/pdf-viewer folder, replace the contents of the pdf-viewer.component.ts file with the following. This initializes 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. In the src/app/ folder, add the following to the app.component.html file in the place where you want to add the PDF viewer:

<pdf-viewer></pdf-viewer>
  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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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 3) ([Vue 3] babel, eslint) from the list.

Activity controller

  1. Select the package manager you want to use (Yarn is recommended).

  2. Change to the created project directory:

cd my-app

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit
  1. Create a new directory under public called js:

mkdir -p public/js
  1. Copy the PSPDFKit for Web library assets to the public/js directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/js/pspdfkit-lib
  1. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the src/components/ folder, create the PSPDFKitContainer.vue file with the following content. This adds a component wrapper for the PSPDFKit library:

<template>
  <div class="pdf-container"></div>
</template>

<script>
import PSPDFKit from "pspdfkit";

/**
 * PSPDFKit for Web example component.
 */
export default {
  name: 'PSPDFKit',
  /**
	 * The component receives `pdfFile` as a prop, which is type of `String` and is required.
	 */
  props: {
    pdfFile: {
      type: String,
      required: true,
    },
  },
  /**
	* We wait until the template has been rendered to load the document into the library.
	*/
  mounted() {
    this.loadPSPDFKit().then((instance) => {
      this.$emit("loaded", instance);
    });
  },
  /**
	 * We watch for `pdfFile` prop changes and trigger unloading and loading when there's a new document to load.
	 */
  watch: {
    pdfFile(val) {
      if (val) {
        this.loadPSPDFKit();
      }
    },
  },
  /**
	 * Our component has the `loadPSPDFKit` method. This unloads and cleans up the component and triggers document loading.
	 */
  methods: {
    async loadPSPDFKit() {
      PSPDFKit.unload(".pdf-container");
      return PSPDFKit.load({
        // access the pdfFile from props
        document: this.pdfFile,
        container: ".pdf-container",
      });
    },
  },

  /**
	 * Clean up when the component is unmounted so it's ready to load another document (not needed in this example).
	 */
  beforeUnmount() {
    PSPDFKit.unload(".pdf-container");
  },
};
</script>


<style scoped>
.pdf-container {
  height: 100vh;
}
</style>
  1. In the src folder, replace the contents of the App.vue file with the following. This includes the newly created component in your app:

<template>
  <div id="app">
    <label for="file-upload" class="custom-file-upload">
    Open PDF
    </label>
    <input id="file-upload" type="file" @change="openDocument" class="btn" />
    <PSPDFKitContainer :pdfFile="pdfFile" @loaded="handleLoaded" />
  </div>
</template>

<script>
import PSPDFKitContainer from "@/components/PSPDFKitContainer";

export default {
  data() {
    return {
      pdfFile: this.pdfFile || "/document.pdf",
    };
  },
  /**
   * Render the `PSPDFKitContainer` component.
   */
  components: {
    PSPDFKitContainer,
  },
  /**
   * Our component has two methods — one to check when the document is loaded, and the other to open the document.
   */
  methods: {
    handleLoaded(instance) {
      console.log("PSPDFKit has loaded: ", instance);
      // Do something.
    },

    openDocument(event) {
      // To access the Vue.js instance data properties, use `this` keyword.
      if (this.pdfFile && this.pdfFile.startsWith('blob:')) {
        window.URL.revokeObjectURL(this.pdfFile);
      }
      this.pdfFile = window.URL.createObjectURL(event.target.files[0]);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

body {
  margin: 0;
}

input[type="file"] {
    display: none;
}

.custom-file-upload {
    border: 1px solid #ccc;
    border-radius: 4px;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    background:#4A8FED;
    padding:10px;
    color:#fff;
    font:inherit;
    font-size: 16px;
    font-weight: bold;
}

</style>
  1. Start the app:

yarn serve
npm run serve
  1. Open http://localhost:8080/ in your browser to view the website.

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 pspdfkit
  1. Create a new directory under public called js:

mkdir -p public/js
  1. Copy the PSPDFKit for Web library assets to the public/js directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/js/pspdfkit-lib
  1. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the src/components/ folder, create the PSPDFKitContainer.vue file with the following content. This adds a component wrapper for the PSPDFKit library:

<template>
  <div class="pdf-container"></div>
</template>

<script>
import PSPDFKit from "pspdfkit";

/**
 * PSPDFKit for Web example component.
 */
export default {
  name: 'PSPDFKit',
  /**
	 * The component receives `pdfFile` as a prop, which is type of `String` and is required.
	 */
  props: {
    pdfFile: {
      type: String,
      required: true,
    },
  },
  /**
	* We wait until the template has been rendered to load the document into the library.
	*/
  mounted() {
    this.loadPSPDFKit().then((instance) => {
      this.$emit("loaded", instance);
    });
  },
  /**
	 * We watch for `pdfFile` prop changes and trigger unloading and loading when there's a new document to load.
	 */
  watch: {
    pdfFile(val) {
      if (val) {
        this.loadPSPDFKit();
      }
    },
  },
  /**
	 * Our component has the `loadPSPDFKit` method. This unloads and cleans up the component and triggers document loading.
	 */
  methods: {
    async loadPSPDFKit() {
      PSPDFKit.unload(".pdf-container");
      return PSPDFKit.load({
        // access the pdfFile from props
        document: this.pdfFile,
        container: ".pdf-container",
      });
    },
  },

  /**
	 * Clean up when the component is unmounted so it's ready to load another document (not needed in this example).
	 */
  beforeUnmount() {
    PSPDFKit.unload(".pdf-container");
  },
};
</script>


<style scoped>
.pdf-container {
  height: 100vh;
}
</style>
  1. In the src folder, add the newly created component to the App.vue file in the following way:

<template>
  <div id="app">
    <label for="file-upload" class="custom-file-upload">
    Open PDF
    </label>
    <input id="file-upload" type="file" @change="openDocument" class="btn" />
    <PSPDFKitContainer :pdfFile="pdfFile" @loaded="handleLoaded" />
  </div>
</template>

<script>
import PSPDFKitContainer from "@/components/PSPDFKitContainer";

export default {
  data() {
    return {
      pdfFile: this.pdfFile || "/document.pdf",
    };
  },
  /**
   * Render the `PSPDFKitContainer` component.
   */
  components: {
    PSPDFKitContainer,
  },
  /**
   * Our component has two methods — one to check when the document is loaded, and the other to open the document.
   */
  methods: {
    handleLoaded(instance) {
      console.log("PSPDFKit has loaded: ", instance);
      // Do something.
    },

    openDocument(event) {
      // To access the Vue.js instance data properties, use `this` keyword.
      if (this.pdfFile && this.pdfFile.startsWith('blob:')) {
        window.URL.revokeObjectURL(this.pdfFile);
      }
      this.pdfFile = window.URL.createObjectURL(event.target.files[0]);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

body {
  margin: 0;
}

input[type="file"] {
    display: none;
}

.custom-file-upload {
    border: 1px solid #ccc;
    border-radius: 4px;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    background:#4A8FED;
    padding:10px;
    color:#fff;
    font:inherit;
    font-size: 16px;
    font-weight: bold;
}

</style>
  1. Start the app:

yarn serve
npm run serve
  1. Open http://localhost:8080/ in your browser 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.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the pages folder, replace the contents of the index.js file with the following:

import React, { useEffect, useRef } from "react";

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

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

    (async function () {
      PSPDFKit = await import("pspdfkit");
      
      if (PSPDFKit) {
        PSPDFKit.unload(container);
      }
      
      await PSPDFKit.load({
        container,
        document: "/document.pdf",
        baseUrl: `${window.location.protocol}//${window.location.host}/`,
      });
    })();

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

  return (
      <div ref={containerRef} style={{ height: "100vh" }} />
  );
}
  1. Your project structure should now look like this:

pspdfkit-next-js-example
├── pages
│   └── index.js
├── public
│   ├── document.pdf
│   └── pspdfkit-lib
└── next.config.js
  1. Start the app:

yarn dev
npm run dev
  1. Open http://localhost:3000 in your browser 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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the pages folder, add the following code to the index.js file below the lines beginning with import:

import React, { useEffect, useRef } from "react";

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

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

    (async function () {
      PSPDFKit = await import("pspdfkit");
      
      if (PSPDFKit) {
        PSPDFKit.unload(container);
      }
      
      await PSPDFKit.load({
        container,
        document: "/document.pdf",
        baseUrl: `${window.location.protocol}//${window.location.host}/`,
      });
    })();

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

  return (
      <div ref={containerRef} style={{ height: "100vh" }} />
  );
}
  1. Start the app:

yarn dev
npm run dev
  1. Open http://localhost:3000 in your browser to view the website.

Next Steps

Integrate into a TypeScript 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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

Run the following command to install TypeScript globally:

npm install -g typescript

Creating a New Project

  1. Run the following command to initialize a new npm workspace in an empty directory:

yarn init -y
npm init -y
  1. In the root folder of your application, create a tsconfig.json file with the following content:

{
	"compilerOptions": {
		"removeComments": true,
		"preserveConstEnums": true,
		"module": "commonjs",
		"target": "es5",
		"sourceMap": true,
		"noImplicitAny": true,
		"esModuleInterop": true
	},
	"include": ["src/**/*"]
}

Adding PSPDFKit and Configuring webpack

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

yarn add pspdfkit
npm install pspdfkit
  1. Run the following command to install the necessary dependencies for webpack, create a config directory, and place your webpack configuration file inside it:

npm i -D webpack webpack-cli webpack-dev-server ts-loader typescript html-webpack-plugin cross-env copy-webpack-plugin clean-webpack-plugin

mkdir config && touch config/webpack.js
  1. In the config folder, add the following code to the webpack.js file:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const filesToCopy = [
	// PSPDFKit files.
	{
		from: './node_modules/pspdfkit/dist/pspdfkit-lib',
		to: './pspdfkit-lib',
	},
	// Application CSS.
	{
		from: './src/index.css',
		to: './index.css',
	},
	// Example PDF.
	{
		from: './assets/document.pdf', 
		to: './document.pdf', 
	},
];

/**
 * webpack main configuration object.
 */
const config = {
	entry: path.resolve(__dirname, '../src/index.ts'),
	mode: 'development',
	devtool: 'inline-source-map',
	output: {
		path: path.resolve(__dirname, '../dist'),
		filename: '[name].js',
	},
	resolve: {
		extensions: ['.ts', '.tsx', '.js'],
	},
	module: {
		rules: [
			// All files with a `.ts` or `.tsx` extension will be handled by `ts-loader`.
			{
				test: /\.tsx?$/,
				loader: 'ts-loader',
				exclude: /node_modules/,
			},
		],
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: './src/index.html',
		}),

		// Copy the WASM/ASM and CSS files to the `output.path`.
		new CopyWebpackPlugin({ patterns: filesToCopy }),
	],

	optimization: {
		splitChunks: {
			cacheGroups: {
				// Creates a `vendor.js` bundle that contains external libraries (including `pspdfkit.js`).
				vendor: {
					test: /node_modules/,
					chunks: 'initial',
					name: 'vendor',
					priority: 10,
					enforce: true,
				},
			},
		},
	},
};

module.exports = config;

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the assets directory. You can use this demo document as an example.

  2. In the src folder, create an index.html file with the following content. This adds an empty <div> element where PSPDFKit is loaded:

<!DOCTYPE html>
<html>
	<head>
		<title>PSPDFKit for Web — TypeScript example</title>
		<link rel="stylesheet" href="index.css" />
	</head>
	<body>
		<div class="container"></div>
	</body>
</html>
  1. In the src folder, create an index.css file with the following content. This declares the height of the PSPDFKit element:

.container {
	height: 100vh;
}
  1. In the src folder, create an index.ts file with the following content:

import PSPDFKit from 'pspdfkit';

function load(document: string) {
	console.log(`Loading ${document}...`);
	PSPDFKit.load({
		document,
		container: '.container',
	})
		.then((instance) => {
			console.log('PSPDFKit loaded', instance);
		})
		.catch(console.error);
}

load('document.pdf'); // Pass your PDF file.
  1. Your project structure should now look like this:

pspdfkit-typescript-example
├── assets
│   └── document.pdf
├── config
│   └── webpack.js
├── src 
│   ├── index.css
│   ├── index.html
│   └── index.ts
├── package-lock.json
├── package.json
└── tsconfig.json

Running the Project

  1. Run the following command to install the serve package:

yarn global add serve
npm install --global serve
  1. Add the following to the scripts section of the package.json file:

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --config config/webpack.js",
    "prestart": "npm run build",
    "dev": "tsc",
    "start": "serve -l 8080 ./dist"
},
  1. Run the following command to start the project:

yarn start
npm start
  1. Open http://localhost:8080 in your browser to view the website.

Next Steps

Integrate into a TypeScript 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 and Configuring webpack

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

yarn add pspdfkit
npm install pspdfkit
  1. Run the following command to install the necessary dependencies for webpack, create a config directory, and place your webpack configuration file inside it:

npm i -D webpack webpack-cli webpack-dev-server ts-loader typescript html-webpack-plugin cross-env copy-webpack-plugin clean-webpack-plugin

mkdir config && touch config/webpack.js
  1. In the config folder, add the following code to the webpack.js file:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const filesToCopy = [
	// PSPDFKit files.
	{
		from: './node_modules/pspdfkit/dist/pspdfkit-lib',
		to: './pspdfkit-lib',
	},
	// Application CSS.
	{
		from: './src/index.css',
		to: './index.css',
	},
	// Example PDF.
	{
		from: './assets/document.pdf', 
		to: './document.pdf', 
	},
];

/**
 * webpack main configuration object.
 */
const config = {
	entry: path.resolve(__dirname, '../src/index.ts'),
	mode: 'development',
	devtool: 'inline-source-map',
	output: {
		path: path.resolve(__dirname, '../dist'),
		filename: '[name].js',
	},
	resolve: {
		extensions: ['.ts', '.tsx', '.js'],
	},
	module: {
		rules: [
			// All files with a `.ts` or `.tsx` extension will be handled by `ts-loader`.
			{
				test: /\.tsx?$/,
				loader: 'ts-loader',
				exclude: /node_modules/,
			},
		],
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: './src/index.html',
		}),

		// Copy the WASM/ASM and CSS files to the `output.path`.
		new CopyWebpackPlugin({ patterns: filesToCopy }),
	],

	optimization: {
		splitChunks: {
			cacheGroups: {
				// Creates a `vendor.js` bundle that contains external libraries (including `pspdfkit.js`).
				vendor: {
					test: /node_modules/,
					chunks: 'initial',
					name: 'vendor',
					priority: 10,
					enforce: true,
				},
			},
		},
	},
};

module.exports = config;

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the assets directory. You can use this demo document as an example.

  2. In the src folder, create an index.html file with the following content. This adds an empty <div> element where PSPDFKit is loaded:

<!DOCTYPE html>
<html>
	<head>
		<title>PSPDFKit for Web — TypeScript example</title>
		<link rel="stylesheet" href="index.css" />
	</head>
	<body>
		<div class="container"></div>
	</body>
</html>
  1. In the src folder, create an index.css file with the following content. This declares the height of the PSPDFKit element:

.container {
	height: 100vh;
}
  1. In the src folder, create an index.ts file with the following content:

import PSPDFKit from 'pspdfkit';

function load(document: string) {
	console.log(`Loading ${document}...`);
	PSPDFKit.load({
		document,
		container: '.container',
	})
		.then((instance) => {
			console.log('PSPDFKit loaded', instance);
		})
		.catch(console.error);
}

load('document.pdf'); // Pass your PDF file.

Running the Project

  1. Run the following command to install the serve package:

yarn global add serve
npm install --global serve
  1. Add the following to the scripts section of the package.json file:

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --config config/webpack.js",
    "prestart": "npm run build",
    "dev": "tsc",
    "start": "serve -l 8080 ./dist"
},
  1. Run the following command to start the project:

yarn start
npm start
  1. Open http://localhost:8080 in your browser to view the website.

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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the src folder, create a PdfViewerComponent.svelte file with the following content. This adds a component wrapper for the PSPDFKit library:

<script>
  import { afterUpdate, onMount, onDestroy } 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;" />
</body>
  1. In the src folder, replace the contents of the App.svelte file with the following. This includes the newly created component in your app:

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

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

yarn run dev
npm run dev
  1. Open http://localhost:8080 in your browser to view the website.

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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the src folder, create a PdfViewerComponent.svelte file with the following content. This adds a component wrapper for the PSPDFKit library:

<script>
  import { afterUpdate, onMount, onDestroy } 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;" />
</body>
  1. In the src folder, add the newly created component to the App.svelte file in the following way:

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

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

yarn run dev
npm run dev
  1. Open http://localhost:8080 in your browser to view the website.

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.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

Creating a New Project

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

yarn init -y
npm init -y
  1. Install Electron and electron-packager as dev dependencies:

yarn add --dev electron electron-packager
npm install --dev electron electron-packager
  1. In the package.json file in the root folder of your application, add "start": "electron ." to the scripts section. The end result will be similar to the following:

{
	"name": "pspdfkit-electron-example",
	"version": "1.0.0",
	"main": "index.js",
	"license": "MIT",
	"devDependencies": {
		"electron": "^19.0.0",
		"electron-packager": "^15.5.1"
	},
	"scripts": {
		"start": "electron ."
	}
}

Adding PSPDFKit

  1. 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 pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

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

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the root folder of your application, create an index.html file with the following content:

<!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 for Electron Example App</title>

    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        background: #f6f7fa;
      }

      header {
        display: none;
      }

      #root {
        width: 100vw;
        height: 100vh;
      }

    </style>
  </head>

  <body>
    <header></header>
    <div id="root"></div>

    <script src="./public/pspdfkit.js"></script>

    <script type="module">
      
      let instance = null;

      
      async function load(document) {
        if (instance) {
          PSPDFKit.unload(instance);
          hasUnsavedAnnotations = false;
          instance = null;
        }

        const configuration = {
          document,
          container: "#root",
          electronAppName: "pspdfkit-electron-example",
          // Add when using a license key
          // licenseKey: "LICENSE KEY GOES HERE",
        };

        instance = await PSPDFKit.load(configuration);
      }

      window.onload = () => load("./public/document.pdf");
    </script>
  </body>
</html>
  1. In the root folder of your application, create a preload.js file with the following content. This script runs before the main renderer process:

const { contextBridge } = require("electron");

const {
  documentExport,
  documentImport,
  askUserToDiscardChanges,
} = require("./lib/modals");

// Use the recommended, safe way of selectively exposing the capabilities
// of the Node.js API to the browser context.

// Electron helpers exposed in the browser context as `window.electron`.
contextBridge.exposeInMainWorld("electron", {
  processPlatform: () => process.platform,
  documentExport,
  documentImport,
  askUserToDiscardChanges,
});
  1. In the root folder of your application, create an index.js file with the following content. This is the main JavaScript file that gets access to the preload script inside the BrowserWindow constructor’s webPreferences option:

const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require("url");

function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, "index.html"),
      protocol: "file:",
      slashes: true,
    })
  );
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})
  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

  1. 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 pspdfkit
  1. Copy the PSPDFKit for Web library assets to the public directory:

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

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. In the root folder of your application, add the following to the index.html file in the place where you want to add the PDF viewer:

<!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 for Electron Example App</title>

    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        background: #f6f7fa;
      }

      header {
        display: none;
      }

      #root {
        width: 100vw;
        height: 100vh;
      }

    </style>
  </head>

  <body>
    <header></header>
    <div id="root"></div>

    <script src="./public/pspdfkit.js"></script>

    <script type="module">
      
      let instance = null;

      
      async function load(document) {
        if (instance) {
          PSPDFKit.unload(instance);
          hasUnsavedAnnotations = false;
          instance = null;
        }

        const configuration = {
          document,
          container: "#root",
          electronAppName: "pspdfkit-electron-example",
          // Add when using a license key
          // licenseKey: "LICENSE KEY GOES HERE",
        };

        instance = await PSPDFKit.load(configuration);
      }

      window.onload = () => load("./public/document.pdf");
    </script>
  </body>
</html>
  1. Make sure you’ve enabled the file protocol in your main process:

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

yarn start
npm start

Next Steps

Integrate into a Nuxt.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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

Using create-nuxt-app

  1. To get started, use create-nuxt-app to create a new Nuxt.js project:

yarn create nuxt-app pspdfkit-app
npm init nuxt-app pspdfkit-app
  1. This will ask you some questions. Choose the default options by pressing Enter. Once you answer all the questions, it’ll install the dependencies and create a new Nuxt.js project.

Nuxt.js terminal

  1. Change to the created project directory:

cd pspdfkit-app

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

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

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib static/pspdfkit-lib
  1. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the static directory. You can use this demo document as an example.

  2. In the components folder, create a PSPDFKitContainer.vue file with the following content. This creates a component wrapper for the PSPDFKit library:

<template>
  <div class="pdf-container"></div>
</template>

<script>
/**
 * PSPDFKit for Web example component.
 */
export default {
  name: "PSPDFKit",
  /**
   * The component receives `pdfFile` as a prop, which is type of `String` and is required.
   */
  props: {
    pdfFile: {
      type: String,
      required: true,
    },
  },
  PSPDFKit: null,
  /**
   * Wait until the template has been rendered to load the document into the library.
   */
  mounted() {
    this.loadPSPDFKit().then((instance) => {
      this.$emit("loaded", instance);
    });
  },
  /**
   * Watch for `pdfFile` prop changes and trigger unloading and loading when there's a new document to load.
   */
  watch: {
    pdfFile(val) {
      if (val) {
        this.loadPSPDFKit();
      }
    },
  },
  /**
   * Our component has the `loadPSPDFKit` method. This unloads and cleans up the component and triggers document loading.
   */
  methods: {
    async loadPSPDFKit() {
      import("pspdfkit")
        .then((PSPDFKit) => {
          this.PSPDFKit = PSPDFKit;
          PSPDFKit.unload(".pdf-container");
          return PSPDFKit.load({
            document: this.pdfFile,
            container: ".pdf-container",
            baseUrl: "http://localhost:3000/",
          });
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
};
</script>

<style scoped>
.pdf-container {
  height: 100vh;
}
</style>
  1. In the pages folder, replace the contents of the index.vue file with the following. This includes the newly created component in your app:

<template>
  <div id="app">
    <label for="file-upload" class="custom-file-upload"> Open PDF </label>
    <input id="file-upload" type="file" @change="openDocument" class="btn" />
    <PSPDFKitContainer :pdfFile="pdfFile" @loaded="handleLoaded" />
  </div>
</template>

<script>
import PSPDFKitContainer from "../components/PSPDFKitContainer.vue";

export default {
  name: "app",
  /**
   * Render the `PSPDFKitContainer` component.
   */
  components: {
    PSPDFKitContainer,
  },

  data() {
    return {
      pdfFile: this.pdfFile || "/document.pdf",
    };
  },

  /**
   * Our component has two methods — one to check when the document is loaded, and the other to open the document.
   */
  methods: {
    handleLoaded(instance) {
      console.log("PSPDFKit has loaded: ", instance);
      // Do something.
    },

    openDocument(event) {
      if (this.pdfFile && this.pdfFile.startsWith("blob:")) {
        window.URL.revokeObjectURL(this.pdfFile);
      }
      this.pdfFile = window.URL.createObjectURL(event.target.files[0]);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

body {
  margin: 0;
}

input[type="file"] {
  display: none;
}

.custom-file-upload {
  border: 1px solid #ccc;
  border-radius: 4px;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
  background: #4a8fed;
  padding: 10px;
  color: #fff;
  font: inherit;
  font-size: 16px;
  font-weight: bold;
}
</style>
  1. Start the app:

yarn dev
npm run dev
  1. Open http://localhost:3000/ in your browser to view the website.

Next Steps

Integrate into a Nuxt.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 pspdfkit
  1. Copy the PSPDFKit for Web library assets to the static directory:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib static/pspdfkit-lib
  1. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the static directory. You can use this demo document as an example.

  2. In the components folder, create a PSPDFKitContainer.vue file with the following content. This creates a component wrapper for the PSPDFKit library:

<template>
  <div class="pdf-container"></div>
</template>

<script>
/**
 * PSPDFKit for Web example component.
 */
export default {
  name: "PSPDFKit",
  /**
   * The component receives `pdfFile` as a prop, which is type of `String` and is required.
   */
  props: {
    pdfFile: {
      type: String,
      required: true,
    },
  },
  PSPDFKit: null,
  /**
   * Wait until the template has been rendered to load the document into the library.
   */
  mounted() {
    this.loadPSPDFKit().then((instance) => {
      this.$emit("loaded", instance);
    });
  },
  /**
   * Watch for `pdfFile` prop changes and trigger unloading and loading when there's a new document to load.
   */
  watch: {
    pdfFile(val) {
      if (val) {
        this.loadPSPDFKit();
      }
    },
  },
  /**
   * Our component has the `loadPSPDFKit` method. This unloads and cleans up the component and triggers document loading.
   */
  methods: {
    async loadPSPDFKit() {
      import("pspdfkit")
        .then((PSPDFKit) => {
          this.PSPDFKit = PSPDFKit;
          PSPDFKit.unload(".pdf-container");
          return PSPDFKit.load({
            document: this.pdfFile,
            container: ".pdf-container",
            baseUrl: "http://localhost:3000/",
          });
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
};
</script>

<style scoped>
.pdf-container {
  height: 100vh;
}
</style>
  1. In the pages folder, add the newly created component to the index.vue file in the following way:

<template>
  <div id="app">
    <label for="file-upload" class="custom-file-upload"> Open PDF </label>
    <input id="file-upload" type="file" @change="openDocument" class="btn" />
    <PSPDFKitContainer :pdfFile="pdfFile" @loaded="handleLoaded" />
  </div>
</template>

<script>
import PSPDFKitContainer from "../components/PSPDFKitContainer.vue";

export default {
  name: "app",
  /**
   * Render the `PSPDFKitContainer` component.
   */
  components: {
    PSPDFKitContainer,
  },

  data() {
    return {
      pdfFile: this.pdfFile || "/document.pdf",
    };
  },

  /**
   * Our component has two methods — one to check when the document is loaded, and the other to open the document.
   */
  methods: {
    handleLoaded(instance) {
      console.log("PSPDFKit has loaded: ", instance);
      // Do something.
    },

    openDocument(event) {
      if (this.pdfFile && this.pdfFile.startsWith("blob:")) {
        window.URL.revokeObjectURL(this.pdfFile);
      }
      this.pdfFile = window.URL.createObjectURL(event.target.files[0]);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

body {
  margin: 0;
}

input[type="file"] {
  display: none;
}

.custom-file-upload {
  border: 1px solid #ccc;
  border-radius: 4px;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
  background: #4a8fed;
  padding: 10px;
  color: #fff;
  font: inherit;
  font-size: 16px;
  font-weight: bold;
}
</style>
  1. Start the app:

yarn dev
npm run dev
  1. Open http://localhost:3000/ in your browser 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 Web Application (Model-View-Controller) template:

visual-studio-template

  1. Choose .NET 5.0 for the target framework:

visual-studio-target-framework

  1. When prompted, choose your app name (PSPDFKit_ASPNETExample) 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-2022.5.1.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 directory in your project.

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

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the troubleshooting section of our guides.

Integrating PSPDFKit

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

To clean out the UI, go to the Views/Shared/_Layout.cshtml file and keep only the @RenderBody() property:

<!DOCTYPE html>
<html lang="en">
<head>
    @* ... *@ 
    <title>@ViewData["Title"] - PSPDFKit_ASPNETExample</title>
</head>
<body>
   @RenderBody()
</body>
</html>
  1. Include pspdfkit.js. The path is relative to the wwwroot directory:

<script src="/lib/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.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. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this 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-aspnet-example
  1. Change to the created project directory:

cd pspdfkit-aspnet-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-2022.5.1.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 directory in your project.

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

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the troubleshooting section of our guides.

Integrating PSPDFKit

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

To clean out the UI, go to the Views/Shared/_Layout.cshtml file and keep only the @RenderBody() property:

<!DOCTYPE html>
<html lang="en">
<head>
    @* ... *@ 
    <title>@ViewData["Title"] - PSPDFKit_ASPNETExample</title>
</head>
<body>
   @RenderBody()
</body>
</html>
  1. Include pspdfkit.js. The path is relative to the wwwroot directory:

<script src="/lib/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.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. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this 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-2022.5.1.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 directory in your project.

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

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the troubleshooting section of our guides.

Integrating PSPDFKit

Integrate PSPDFKit in your view, Views/Home/Index.cshtml.

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

<script src="/lib/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. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this 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-2022.5.1.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 directory in your project.

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

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the troubleshooting section of our guides.

Integrating PSPDFKit

Integrate PSPDFKit in your view, Views/Home/Index.cshtml.

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

<script src="/lib/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. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this demo document as an example.

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

dotnet watch run

Next Steps

Integrate into a Blazor Server 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 Blazor Server App project template:

visual-studio-template

  1. Choose .NET 5.0 for the target framework:

visual-studio-template

  1. When prompted, choose your app name (PSPDFKit_BlazorServer) 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-2022.5.1.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 wwwroot folder.

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

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this demo document as an example.

  2. To clean out the UI, go to the Shared/MainLayout.razor component and keep only the @Body property:

@inherits LayoutComponentBase
@Body
  1. Go to the Home route located under the Pages/Index.razor file, and replace the contents of the file with the following:

@page "/"
@inject IJSRuntime JS

<div id='container' style='background: gray; width: 100vw; height: 100vh; margin: 0 auto;'></div>

@code {

    protected override async void OnAfterRender(bool firstRender)
    {
      if (firstRender) {
        await JS.InvokeVoidAsync("loadPDF", "#container", "document.pdf");
      }
    }
}
  1. Load the PSPDFKit SDK to Pages/_Host.cshtml before the </body> tag:

@* Include pspdfkit.js in your Pages/_Host.cshtml file *@
 <script src="pspdfkit.js"></script>

 @* Initialize PSPDFKit for Web in Blazor Server by calling PSPDFKit.load(): *@
 <script>
   function loadPDF(container, document) {
      PSPDFKit.load({
         container: container,
         document: document
      })
   }
 </script>

Serving Your Website

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

Next Steps

Integrate into a Blazor Server 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 Blazor project:

dotnet new blazorserver -o PSPDFKit_BlazorServer
  1. Change to the created project directory:

cd PSPDFKit_BlazorServer

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-2022.5.1.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 wwwroot folder.

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

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this demo document as an example.

  2. To clean out the UI, go to the Shared/MainLayout.razor component and keep only the @Body property:

@inherits LayoutComponentBase
@Body
  1. Go to the Home route located under the Pages/Index.razor file, and replace the contents of the file with the following:

@page "/"
@inject IJSRuntime JS

<div id='container' style='background: gray; width: 100vw; height: 100vh; margin: 0 auto;'></div>

@code {

    protected override async void OnAfterRender(bool firstRender)
    {
      if (firstRender) {
        await JS.InvokeVoidAsync("loadPDF", "#container", "document.pdf");
      }
    }
}
  1. Load the PSPDFKit SDK to Pages/_Host.cshtml before the </body> tag:

@* Include pspdfkit.js in your Pages/_Host.cshtml file *@
    <script src="pspdfkit.js"></script>

   @* Initialize PSPDFKit for Web in Blazor Server by calling PSPDFKit.load(): *@
    <script>
        function loadPDF(container, document) {
            PSPDFKit.load({
                container: container,
                document: document
            })
        }
    </script>

Serving Your Website

  1. Start the app in the root directory of your project:

dotenv watch run

Next Steps

Integrate into a Blazor WebAssembly 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 Blazor WebAssembly App project template:

visual-studio-template

  1. Choose .NET 5.0 for the target framework:

visual-studio-template

  1. When prompted, choose your app name (PSPDFKit_BlazorWASM) 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-2022.5.1.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 wwwroot folder.

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

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this demo document as an example.

  2. To clean out the UI, go to the Shared/MainLayout.razor component and keep only the @Body property:

@inherits LayoutComponentBase
@Body
  1. Go to the Home route located under the Pages/Index.razor file, and replace the contents of the file with the following:

@page "/"
@inject IJSRuntime JS

<div id='container' style='background: gray; width: 100vw; height: 100vh; margin: 0 auto;'></div>

@code {

    protected override async void OnAfterRender(bool firstRender)
    {
      if (firstRender) {
        await JS.InvokeVoidAsync("loadPDF", "#container", "document.pdf");
      }
    }
}
  1. Load the PSPDFKit SDK loading code to wwwroot/index.html before the </body> tag:

<script src="pspdfkit.js"></script>
    <!-- Initialize PSPDFKit for Web in Blazor WASM by calling PSPDFKit.load(): -->
    <script>
      function loadPDF(container, document) {
        PSPDFKit.load({
          container,
          document,
        });
      }
    </script>

Serving Your Website

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

Next Steps

Integrate into a Blazor WebAssembly 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 Blazor project:

dotnet new blazorwasm -o PSPDFKit_BlazorWASM
  1. Change to the created project directory:

cd PSPDFKit_BlazorWASM

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-2022.5.1.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 wwwroot folder.

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

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the wwwroot directory. You can use this demo document as an example.

  2. To clean out the UI, go to the Shared/MainLayout.razor component and keep only the @Body property:

@inherits LayoutComponentBase
@Body
  1. Go to the Home route located under the Pages/Index.razor file, and replace the contents of the file with the following:

@page "/"
@inject IJSRuntime JS

<div id='container' style='background: gray; width: 100vw; height: 100vh; margin: 0 auto;'></div>

@code {

    protected override async void OnAfterRender(bool firstRender)
    {
      if (firstRender) {
        await JS.InvokeVoidAsync("loadPDF", "#container", "document.pdf");
      }
    }
}
  1. Load the PSPDFKit SDK loading code to wwwroot/index.html before the </body> tag:

<script src="pspdfkit.js"></script>
    <!-- Initialize PSPDFKit for Web in Blazor WASM by calling PSPDFKit.load(): -->
    <script>
      function loadPDF(container, document) {
        PSPDFKit.load({
          container,
          document,
        });
      }
    </script>

Serving Your Website

  1. Start the app in the root directory of your project:

dotenv watch run

Next Steps

Integrate into a jQuery 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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this demo document as an example.

  2. In the index.html file in the root folder of your application, 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. Add the jQuery CDN to your HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  1. Include pspdfkit.js in your HTML page:

<script src="assets/pspdfkit.js"></script>
  1. Initialize PSPDFKit for Web in jQuery 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 lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- 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"
    />
    <title>PDF Viewer in jQuery</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <!-- Element where PSPDFKit will be mounted. -->
    <div id="pspdfkit" style="width: 100%; height: 100vh"></div>

    <!-- Google jQuery CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <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. Open http://localhost:8080 in your browser to view the website.

Next Steps

Integrate into a jQuery 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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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 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.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this demo document as an example.

  2. In the index.html file in the root folder of your application, 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. Add the jQuery CDN to your HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  1. Import pspdfkit into your application, and initialize PSPDFKit for Web in jQuery 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: 'Document.pdf',
})
  .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>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- 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"
    />
    <title>My App</title>
  </head>
  <body>
    <!-- Element where PSPDFKit will be mounted. -->
    <div id="pspdfkit" style="width: 100%; height: 100vh"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <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. Open http://localhost:8080 in your browser to view the website.

Next Steps

Integrate into a jQuery 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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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-2022.5.1.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.

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this demo document as an example.

  2. In the index.html file in the root folder of your application, 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. Add the jQuery CDN to your HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  1. Include pspdfkit.js in your HTML page:

<script src="assets/pspdfkit.js"></script>
  1. Initialize PSPDFKit for Web in jQuery 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 lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- 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"
    />
    <title>PDF Viewer in jQuery</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <!-- Element where PSPDFKit will be mounted. -->
    <div id="pspdfkit" style="width: 100%; height: 100vh"></div>

    <!-- Google jQuery CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <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. Open http://localhost:8080 in your browser to view the website.

Next Steps

Integrate into a jQuery 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

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

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-2022.5.1.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.

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this demo document as an example.

  2. In the index.html file in the root folder of your application, 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. Add the jQuery CDN to your HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  1. Import pspdfkit into your application, and initialize PSPDFKit for Web in jQuery 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: 'Document.pdf',
})
  .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>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- 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"
    />
    <title>My App</title>
  </head>
  <body>
    <!-- Element where PSPDFKit will be mounted. -->
    <div id="pspdfkit" style="width: 100%; height: 100vh"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <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. Open http://localhost:8080 in your browser to view the website.

Next Steps

Integrate into a PHP 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

  • PHP

We recommend installing PHP via Homebrew, as explained here.

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-2022.5.1.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.

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this 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 PHP page:

<script src="assets/pspdfkit.js"></script>
  1. Initialize PSPDFKit for Web in PHP 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.php file (which is just a plain HTML file):

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</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

  1. Go to your terminal and run a server with this command:

php -S 127.0.0.1:8000
  1. Navigate to http://127.0.0.1:8000 to view the website.

Next Steps

Integrate into a PHP 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 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-2022.5.1.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.

  4. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Integrating into Your Project

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to your project’s root directory. You can use this 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 PHP page:

<script src="assets/pspdfkit.js"></script>
  1. Initialize PSPDFKit for Web in PHP 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.php file (which is just a plain HTML file):

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</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

  1. Go to your terminal and run a server with this command:

php -S 127.0.0.1:8000
  1. Navigate to http://127.0.0.1:8000 to view the website.

Next Steps

Integrate into a Laravel 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

To get started, you’ll need:

You can install PHP via XAMPP, MAMP, or Homebrew.

Don’t forget to add composer to your path directory:

export PATH="$HOME/.composer/vendor/bin:$PATH"

Creating the Project

  1. Create a new Laravel project:

laravel new pspdfkit-app
  1. Change to the created project directory:

cd pspdfkit-app

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 pspdfkit
  1. Copy the PSPDFKit for Web distribution to the /public/assets/ directory in your project’s folder:

mkdir public/assets && cp -R ./node_modules/pspdfkit/dist/ ./public/assets/
  1. Make sure your /public/assets/ directory contains the pspdfkit.js file and a pspdfkit-lib directory with the library assets.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. Navigate to the resources/views/welcome.blade.php file.

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

<div id="pspdfkit" style="height: 100vh"></div>
  1. Include pspdfkit.js on the welcome.blade.php page:

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

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

Here’s the full welcome.blade.php file (which is just a plain HTML file) :

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
 		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="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>
  1. You can see the file structure of changed files:

pspdfkit-app
├── public
│   ├── assets
│   │   ├── modern
│   │   ├── pspdfkit-lib
│   │   ├── pspdfkit.js
│   └── document.pdf
├── resources
│   ├── views
│   |   └── welcome.blade.php

Viewing Your Website

  1. Go to your terminal and run a server with this command:

php artisan serve
  1. Navigate to http://127.0.0.1:8000 to view the website.

Next Steps

Integrate into a Laravel 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 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 pspdfkit
  1. Copy the PSPDFKit for Web distribution to the /public/assets/ directory in your project’s folder:

mkdir public/assets && cp -R ./node_modules/pspdfkit/dist/ ./public/assets/
  1. Make sure your /public/assets/ directory contains the pspdfkit.js file and a pspdfkit-lib directory with the library assets.

  2. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. Navigate to the resources/views/welcome.blade.php file.

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

<div id="pspdfkit" style="height: 100vh"></div>
  1. Include pspdfkit.js on the welcome.blade.php page:

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

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

Here’s the full welcome.blade.php file (which is just a plain HTML file) :

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
 		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="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>

Viewing Your Website

  1. Go to your terminal and run a server with this command:

php artisan serve
  1. Navigate to http://127.0.0.1:8000 to view the website.

Next Steps

Integrate into a Laravel 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

To get started, you’ll need:

You can install PHP via XAMPP, MAMP, or Homebrew.

Don’t forget to add composer to your path directory:

export PATH="$HOME/.composer/vendor/bin:$PATH"

Creating the Project

  1. Create a new Laravel project:

laravel new pspdfkit-app
  1. Change to the created project directory:

cd pspdfkit-app

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-2022.5.1.tar.gz to your computer.

  2. Once the download is complete, extract the archive to your computer.

  3. Create a new directory under public called assets and copy the entire contents of its dist folder to your project’s public/assets folder.

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

  5. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. Navigate to the resources/views/welcome.blade.php file.

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

<div id="pspdfkit" style="height: 100vh"></div>
  1. Include pspdfkit.js on the welcome.blade.php page:

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

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

Here’s the full welcome.blade.php file (which is just a plain HTML file) :

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
 		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="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>
  1. You can see the file structure of changed files:

pspdfkit-app
├── public
│   ├── assets
│   │   ├── modern
│   │   ├── pspdfkit-lib
│   │   ├── pspdfkit.js
│   └── document.pdf
├── resources
│   ├── views
│   |   └── welcome.blade.php

Viewing Your Website

  1. Go to your terminal and run a server with this command:

php artisan serve
  1. Navigate to http://127.0.0.1:8000 to view the website.

Next Steps

Integrate into a Laravel 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 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-2022.5.1.tar.gz to your computer.

  2. Once the download is complete, extract the archive to your computer.

  3. Create a new directory under public called assets and copy the entire contents of its dist folder to your project’s public/assets folder.

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

  5. Make sure your server has the Content-Type: application/wasm MIME typeset. Read more about this in the Troubleshooting section.

Displaying a PDF

  1. Rename the PDF document you want to display in your application to document.pdf, and then add the PDF document to the public directory. You can use this demo document as an example.

  2. Navigate to the resources/views/welcome.blade.php file.

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

<div id="pspdfkit" style="height: 100vh"></div>
  1. Include pspdfkit.js on the welcome.blade.php page:

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

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

Here’s the full welcome.blade.php file (which is just a plain HTML file) :

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
 		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="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>

Viewing Your Website

  1. Go to your terminal and run a server with this command:

php artisan serve
  1. Navigate to http://127.0.0.1:8000 to view the website.

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 SharePoint Online as a Web Part

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into SharePoint Online pages using a web part. By the end of this guide, you’ll be able to use a web browser to directly open PDF documents stored in SharePoint, as well as display, edit, and save them back to SharePoint.

PSPDFKit for SharePoint is a wrapper on top of PSPDFKit for Web Standalone, which is a client-side JavaScript library for viewing and editing PDF documents directly in a web browser.

PSPDFKit for SharePoint shares the same APIs as PSPDFKit for Web Standalone, so please use the Web documentation when customizing your SharePoint application.

integration diagram

Requirements

Setup

  1. Clone the pspdfkit-sp-online-webpart repository from GitHub.

Navigate to the directory where you want to place the SharePoint integration, and type the following command in your command line/terminal:

git clone https://github.com/PSPDFKit/pspdfkit-sp-online-webpart.git

Alternatively, you can download the project as a .zip file without cloning the project.

  1. Navigate to admin.microsoft.com and sign in to your tenant account.

To make the SharePoint catalog available, click Show All… in the side navigation, and find Admin centers > SharePoint. This will direct you to SharePoint Admin portal.

Follow along with this tutorial from Microsoft to configure your SharePoint tenant and create your new team site.

  1. To configure your URL, go to the config/serve.json file in your pspdfkit-sp-online-webpart project and change enter-your-SharePoint-site to the URL of your SharePoint site:

"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx",
  1. Now, set up your development environment to build a client-side web part.

Don’t forget to execute gulp trust-dev-cert from the root of your project to trust the self-signed developer certificate.

  1. Change your directory into the pspdfkit-sp-online-webpart directory:

cd pspdfkit-sp-online-webpart
  1. Open the project in your preferred code editor and check which version of Node.js you’re using:

node --version
Information

Make sure you have Node.js version 14.17.6 installed. If you’re using a different version of Node, switch to Node.js version 14.17.6 via nvm (node version manager) or asdf.

💡 Tip: If you’re using asdf, you can switch the Node version locally for this project. First, install Node.js 14.17.6 using the following command:

asdf install nodejs 14.17.6

Now, run asdf local nodejs 14.17.6 to switch to the Node.js version you just installed. This will create a .tool-versions file in the root of your project with Node version 14.17.6. If you encounter any issues, check out the asdf documentation.

💡 Tip: If you’re using nvm, you can switch to Node.js 14.17.6 by typing the following command:

nvm use 14.17.6
  1. Install the dependencies:

npm install
  1. To serve the project, type:

npm run serve

The browser will open a new tab with your SharePoint account.

Integrating PSPDFKit into SharePoint

PSPDFKit can be added to your project as a widget. You can add it to your project using the UI elements.

Refer to the following video for information on how to integrate the PSPDFKit widget into your project, or continue with the instructions.

  1. On your Home page, in the upper right-hand corner, find the Edit button.

  2. Click the Edit button. This will open the Editing interface.

  3. To add the PSPDFKit widget, hover over where you want to place it. This will display a plus icon. When you click the plus icon, it’ll open a dialog box with the possible web parts you can incorporate into your project.

  4. Search for the PSPDFKit widget and click on it.

adding pspdfkit widget

  1. Find the edit button with the pencil icon, and click Select Document from the open panel.

pspdfkit widget properties

  1. Choose your document and click Open. Now you’ll be able to see the PSPDFKit widget in your project like in the video above.

pspdfkit preview

Using for Production

For production, you need to follow these steps to deploy into your SharePoint environment.

  1. Run npm run bundle and then npm run package.

  2. Then, follow the steps outlined in this SharePoint guide for packaging and deploying your web part. If a previous installation already exists, it’s recommended to remove it before proceeding.

Information

Please make sure to select Make this solution available to all sites in the organization. This appears in the confirmation dialog you’ll see after dragging the package.

pspdfkit widget properties

  1. To make the web part available in Microsoft Teams, synchronize your solution with Teams.

  1. Navigate to the workbench of one of your SharePoint sites and add the PSPDFKit web part there.

  2. There’s an issue getting SharePoint to bundle the static assets of PSPDFKit for Web under the correct subdirectory when using the SharePoint file system itself as your CDN instead of a custom one (you can specify a custom URL for the static assets under write-manifests.json), so you might see a network error when requesting one of the chunks for the PSPDFKit library.

pspdfkit widget properties

If this happens, it’s because the pspdfkit-lib subdirectory hasn’t been created by SharePoint. To fix this, navigate to the erroring URL but trim its path before the pspdfkit-lib segment (i.e. https://<your-sharepoint-site>/sites/appcatalog/ClientSideAssets/<some-hash>) and create a pspdfkit-lib folder.

pspdfkit widget properties

Then, you can copy the contents from ./sharepoint/solution/debug/ClientSideAssets/pspdfkit-lib to the newly created folder.

Information

Make sure you have the latest version of PSPDFKit inside the pspdfkit-lib folder.

ℹ️ Note: As an alternative to this step, consider hosting the assets in a CDN and set it in the write-manifests.json file.

  1. Your PSPDFKit instance should now work. Try opening your workbench and check if the PSPDFKit web part appears as part of the list of available web parts to add.

You can now begin customizing the user interface, implementing custom functionality, or adding a custom file handler for PDF files.

Next Steps

References

Integrate into SharePoint Online as a File Handler

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into SharePoint Online as a file handler.

File handlers instruct SharePoint to redirect to your URL of choice whenever a file with a particular extension is clicked. By using a file handler, you’ll override SharePoint’s default behavior so that PDF documents are opened directly inside your application. Any edits to the opened files using your application can then be directly saved back to SharePoint.

PSPDFKit for SharePoint is a wrapper on top of PSPDFKit for Web Standalone, which is a client-side JavaScript library for viewing and editing PDF documents directly in a web browser.

PSPDFKit for SharePoint shares the same APIs as PSPDFKit for Web Standalone, so please use the Web documentation when customizing your SharePoint application.

integration diagram

Requirements

Information

File handlers are registered centrally for the entire SharePoint tenant and cannot be selectively enabled or disabled. Uninstalling a file handler from the environment can be problematic due to aggressive caching and may take 24–48 hours to take effect.

Setup

  1. Clone the pspdfkit-sp-online-filehandler repository from GitHub.

Navigate to the directory where you want to place the SharePoint integration, and type the following command in your command line/terminal:

git clone https://github.com/PSPDFKit/pspdfkit-sp-online-filehandler.git

Alternatively, you can download the project as a .zip file without cloning the project.

This project uses Next.js as a server-side framework; however, you can use any other server-side framework you like. The application serves as a native file handler of PDF documents for SharePoint sites.

Concretely, this server handles requests to open PDF documents from a SharePoint site and then proceeds to render an HTML page containing the PSPDFKit for Web Standalone viewer.

This project is based on the Markdown FileHandler example project.

Installation and Development Deployment

After cloning the repository, and before starting the development setup process, it’s worth understanding how the file handler architecture works.

setup steps

Information

Setup Application is a special helper application that needs to be registered in the Azure App Directory. However, it doesn’t represent the file handler app, rather it’s a helper to automate the process of creating the file handler. This helper app can later safely be removed from the environment.

Customizing the Manifest Specification

The file handler server is a regular server-side web application that handles requests initiated by SharePoint when users click files from the SharePoint Document Library.

The main important part around the file handler is the manifest file, which defines the URL that will handle the requests, how authentication will be handled, and what elements will be rendered in the SharePoint UI (e.g. the context menu item).

In this project, the final manifest is generated by a set of TypeScript scripts under the ./tools/local-setup directory. The entry point is ./tools/local-setup/bin/localsetup.ts. The result of this series of scripts is the automatic generation of the final file handler application registration in your Azure Active Directory.

There are certain key aspects that you can customize as part of the manifest (outlined below).

Display name of the menu — To change the string used when a file is selected, go to ./tools/local-setup/tasks/ensure-app.ts and change the value for the appDisplayName variable.

setup steps

Login URL — To change the URL SharePoint uses to handle logging in, go to ./tools/local-setup/tasks/ensure-app.ts and change the value for redirectUris.

Logout URL — To change the URL SharePoint uses to handle logging out, go to ./tools/local-setup/tasks/ensure-app.ts and change the value for logoutUrls.

URL to edit a selected file — To change the URL SharePoint uses to handle redirection after a file is opened, go to tools/local-setup/tasks/inject-manifest.ts and change the value for the "url" field as part of the actions array (line 9). Notice how the file extension your file handler will operate on — in addition to other metadata — is also defined here.

Once these aspects are defined, you can proceed with the development environment preparation for the file handler.

Notice that, by default, you’re defining localhost:3000. This means SharePoint will, for the time being, always use that URL when selecting a file, which means you need to have your local development server running.

Later, there are instructions on how to change that server once a production deployment exists.

Development Setup

  1. Change your directory into the pspdfkit-sp-online-filehandler directory:

cd pspdfkit-sp-online-filehandler
  1. Open the project in your preferred code editor and check which version of Node.js you’re using:

node --version
Information

Make sure you have Node.js version 14.17.6 installed. If you’re using a different version of Node, switch to Node.js version 14.17.6 via nvm (node version manager) or asdf.

💡 Tip: If you’re using asdf, you can switch the Node version locally for this project. First, install Node.js 14.17.6 using the following command:

asdf install nodejs 14.17.6

Now, run asdf local nodejs 14.17.6 to switch to the Node.js version you just installed. This will create a .tool-versions file in the root of your project with Node version 14.17.6. If you encounter any issues, check out the asdf documentation.

💡 Tip: If you’re using nvm, you can switch to Node.js 14.17.6 by typing the following command:

nvm use 14.17.6
  1. Install the dependencies:

npm install
  1. You need to set up a file handler app registration and load it with a manifest. To do this, you need to be an admin of a SharePoint tenant.

Information

The app you're manually creating is used as a way of automating the registration of the actual file handler, but it isn’t the file handler itself. At a later point, you’ll no longer need this temporal app, and you can remove it from your Azure Active Directory.

  1. Sign in to the Azure portal.

  2. Switch to the tenant in which you want to register the application (if you have more than one).

  3. Select Azure Active Directory.

Azure Active Directory

  1. Under Manage, select App registrations > New registration.

app registrations link

  1. Give it an easy-to-find name (e.g. “filehandler localdev setup”).

  2. Add API permissions:

  • Microsoft Graph > Delegated permissions: openid, Directory.AccessAsUser.All.

  • Grant admin consent to the permissions.

  1. Under the Authentication section:

  • Add a platform:

    • Add mobile and desktop applications.

    • Under Redirect URIs, select the MSAL only option.

  • Set Allow public client flows to Yes. This will treat the app as a public client. Please make sure this step isn’t skipped, as otherwise, the whole process will later fail when running your dev-setup script.

  1. Copy the Application (client) ID and the Directory (tenant) ID, which you’ll need in the next step.

  1. Make sure OpenSSL is installed on your system. Then, run npm run dev-setup, and supply the client and tenant IDs from the previous step when prompted. Follow the onscreen prompts to complete the device code authorization flow.

Information

It’ll take 24–48 hours for the manifest change to take effect. You can follow these steps for clearing the cache to speed this up.

  1. Once setup is complete, you can optionally delete the registration helper application or leave it in place for future use.

  2. Running the dev-setup command in step 4 generates an .env.local file in the root of this project. Review the values and ensure it was created correctly. It’ll appear similar to what’s shown below:

IRON_SESSION_PASSWORD='{anything you want}'
NODE_ENV='production'
AAD_MSAL_AUTH_TENANT_ID="{app tenant id from step 3.9}"
AAD_MSAL_AUTH_ID="{app client id from step 3.9}"
AAD_MSAL_AUTH_SECRET="{app secret from step 3.9}"
NEXT_PUBLIC_FILEHANDLER_SITE_HOST_URL="https://localhost:3000"
  1. Run npm run dev and launch the file handler from within OneDrive or the SharePoint document library on a .pdf file.

Document Library

Production Deployment

Follow these steps when you want to upload the file handler into a production server after development.

  1. Run npm run build from your terminal.

  2. Deploy the Next.js application somewhere. For this, you can use Vercel, Heroku, AWS Amplify, Digital Ocean, or another self-hosting option.

  3. Sign in to the Azure portal.

  4. Go to the Azure Active Directory. Then, follow the App registrations link in the sidebar.

  5. Select your existing application (created from step 3 of the development setup).

  6. Select Manifest from the sidebar, as shown in the screenshot below.

Link to manifest

  1. Once in the manifest editor, search for the logoutUrl property and replace its value with the same path, but pointing to your production domain instead (the one your application was deployed to in step 2).

Search for the replyUrlsWithType array, and for objects with the url key, replace it to also point to your domain (but maintaining the path).

  1. Click Save. Now the file handler is ready to be used in production.

Go to the SharePoint document library and try to open a PDF file. The file will be opened using the PSPDFKit viewer.

Information

It’ll take 24–48 hours for the manifest change to take effect. You can follow these steps for clearing the cache to speed this up.

You can now begin customizing the user interface or implementing custom functionality.

Next Steps

Integrate into SharePoint On-Premises as a File Handler

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into SharePoint on-premises environments as a file handler.

File handlers are simple XML files that instruct SharePoint to redirect to your URL of choice whenever a file with a particular extension is clicked. By using a file handler, you’ll override SharePoint’s default behavior so that PDF documents stored in SharePoint are opened directly inside your application. Any edits to the opened files using your application can then be directly saved back to SharePoint.

PSPDFKit for SharePoint is a wrapper on top of PSPDFKit for Web Standalone, which is a client-side JavaScript library for viewing and editing PDF documents directly in a web browser.

PSPDFKit for SharePoint shares the same APIs as PSPDFKit for Web Standalone, so please use the Web documentation when customizing your SharePoint application.

integration diagram

Requirements

Hardware and operating system requirements are determined by the requirements of the SharePoint version you’re targeting, as well as the requirements of the Visual Studio version used for development. Both SharePoint Server and Visual Studio have to be installed on the developer machine.

The required Visual Studio versions for targeting different SharePoint versions are summarized in the following table. Up to Visual Studio 2017, the matching Microsoft Office Developer Tools needs to be manually downloaded and installed. For Visual Studio 2019 and 2022, the relevant components can be selected during installation of Visual Studio.

matrix table

SharePoint Permissions Considerations

To develop SharePoint solutions, you must have sufficient permissions to run and debug them. Before you can test a SharePoint solution, take the following steps to ensure you have the necessary permissions:

  1. Add your user account as an Administrator on the system.

  2. Add your user account as a Farm Administrator for the SharePoint server.

  • In SharePoint Central Administration, click the Manage the farm administrators group link.

  • On the Farm Administrators page, click the New button.

  1. Add your user account to the WSS_ADMIN_WPG group.

You can find more information by clicking the link that corresponds to your version of Visual Studio:

Creating a New Project

A new project has to be created in Visual Studio. The project can then be deployed to and debugged in your selected SharePoint environment. The project can also be published to create an installable SharePoint solution package (.wsp).

The example here uses Visual Studio 2019, but SharePoint project templates are also available in earlier versions (minimum Visual Studio 2013).

  1. Create a new empty SharePoint project matching the desired SharePoint version (SharePoint 2013, SharePoint 2016, or SharePoint 2019).

Creating an empty project on SharePoint 2013

  1. Give your project the name OpenPDFSharePoint, set its location on your disk, select the desired .NET Framework version, and click Create.

Configure project

  1. Select your development SharePoint site for debugging, and pick Deploy as farm solution. Click Finish. This will create the skeleton of your project.

Debugging options

Creating the Folder Structure

Some folders in your project have to be created or mapped to SharePoint folders in advance.

  1. In the Solution Explorer window, right-click the OpenPDFSharePoint project and select Add > SharePoint “Layouts” Mapped Folder. This will create the Layouts folder and a folder for your code (OpenPDFSharePoint) inside. It also automatically updates the package details.

Add the Layouts mapped folder

  1. Right-click the OpenPDFSharePoint project in the Solution Explorer window again and select Add > SharePoint Mapped Folder. Select {SharePointRoot} > TEMPLATE > XML from the tree structure in the popup dialogue and click OK.

Add the XML mapped folder

  1. Using the context menu again (right-click on the newly created OpenPDFSharePoint folder inside the Layouts folder), select Add > New Folder. Create the following nested subfolders inside the OpenPDFSharePoint folder: assets > modern > pspdfkit-lib.

Folders inside the OpenPDFSharePoint folder

Adding the PSPDFKit Libraries to the Project

The content (the .wasm file and the JavaScript, CSS, and font files) mentioned in this next part is the PSPDFKit Web Standalone product. It enables the browser to render and edit PDF files.

  1. Download the latest PSPDFKit Web Standalone libraries from https://customers.pspdfkit.com/download/web/latest.

  2. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2022.2.2.tar.gz to your computer.

  3. Once the download is complete, extract the archive.

  4. Right-click on the Layouts > OpenPDFSharePoint > assets > modern folder in the Solution Explorer window and select Add > Existing Item…

  5. Navigate to the extracted package > dist > modern > pspdfkit.js file, select it, and click Add.

  6. Now, right-click on the Layouts > OpenPDFSharePoint > assets > modern > pspdfkit-lib folder in the Solution Explorer window and select Add > Existing Item… again.

  7. Navigate to the extracted package > dist > modern > pspdfkit-lib folder, select all the files in the folder, and click Add. The result will look like this:

PSPDFKit library files

Adding a PDF Viewer Page

This SharePoint application page will encapsulate the PSPDFKit Web Standalone component and configure it to display the selected PDF file. It’ll also save the changes back into the SharePoint library.

Right-click the OpenPDFSharePoint folder inside the Layouts folder in the Solution Explorer window and select Add > New Item.

Add new item

Select Application Page (Farm Solution only) and name it ViewPDF.aspx. Click Add.

Add Application Page for Farm Solution

In the ViewPDF.aspx file, identify the the main content placeholder:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
</asp:Content>

You have to add three things inside the main content placeholder.

  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: calc(100vh - 210px);"></div>
  1. Add a reference to the PSPDFKit JavaScript file:

<script type="text/javascript" src="assets/modern/pspdfkit.js"></script>
  1. Add the following script:

<script type="text/javascript">
	 // !!! Enter your license key here !!!
	 let licenseKey = "paste your license here";

	 // Load PDF Editor
	 PSPDFKit.load({
		  container: "#pspdfkit",
		  document: "<%= fileURL %>",
		  licenseKey: licenseKey
	 })
		  .then(function (instance) {
				console.log("PSPDFKit loaded", instance);
		  })
		  .catch(function (error) {
				console.error(error.message);
		  });
</script>

If you have a PSPDFKit license, then paste it into the script (at the beginning) between the quotation marks. Otherwise, let the licenseKey variable be an empty string.

Warning

You must explicitly set the type attribute of the script elements to `"text/javascript"`. Otherwise, they’ll be ignored.

Modify the ViewPDF.aspx.cs code behind the file to include the fileURL public property and some new code in the Page_load event:

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System;

namespace OpenPDFSharePoint.Layouts.OpenPDFSharePoint
{
	 public partial class ViewPDF : LayoutsPageBase
	 {
		  /// <summary>
		  /// Gets the file URL extracted from the URL key.
		  /// </summary>
		  public string fileURL { get; private set; }

		  /// <summary>
		  /// Page load event.
		  /// </summary>
		  protected void Page_Load(object sender, EventArgs e)
		  {
				// Extract the file URL for the SharePoint file.
				fileURL = Request.QueryString["fileURL"];
		  }
	 }
}

Adding a File Handler

A SharePoint file handler can be used to link PDF files to the PSPDFKit PDF editor. The file handlers are simple XML files at a specific location. They instruct SharePoint to redirect to your URL of choice whenever a file with a particular extension is clicked.

Add an .xml file named serverfilesPSPDFKit.xml to the XML folder in the solution with the following content:

<?xml version="1.0" encoding="utf-8" ?>
<ServerFiles>
  <!-- Redirect any links to a PDF file to the PDF Editor application page -->
  <Mapping FileExtension="pdf" RedirectUrlTemplate="/_layouts/15/OpenPDFSharePoint/ViewPDF.aspx?fileURL=|0" NoGetRedirect="TRUE"/>
</ServerFiles>

Enabling the WASM MIME Type

Before the above example can be used, verify that .wasm files are served by your SharePoint web server.

Start the Internet Information Services (IIS) Manager. Navigate to the website that belongs to your SharePoint instance. Double-click MIME Types in the Features View.

Enabling the WASM MIME Type

If .wasm isn’t in the list of extensions, click the Add button in the Actions pane. In the Add MIME Type popup window, enter ".wasm" (under File name extension:) and "application/wasm" (under MIME type:).

Add Mime type

Publishing the Solution

Visual Studio allows you to deploy your solution to the SharePoint instance you selected at the beginning for debugging purposes. Select Build > Deploy Solution.

The Build menu

It’s also possible to publish a deployable package (.wsp) by selecting Build > Publish… Pick Publish to File System, specifying your desired location, and clicking Publish.

Publish your solution

Installing the Solution

Open the SharePoint Management Shell with Run as administrator. Assuming you have the .wsp file in the c:\deploy folder, copy and execute the following command:

Add-SPSolution "c:\deploy\OpenPDFSharePoint.wsp"

Next, copy and execute the following command:

Install-SPSolution -Identity OpenPDFSharePoint.wsp -GACDeployment
Warning

SharePoint Administration and SharePoint Timer Service must be running.

Using the Solution

Navigate to a SharePoint document library and click on a PDF file. It’ll open in the PSPDFKit PDF editor.

You can now begin customizing the user interface or implementing custom functionality.

Next Steps

Integrate into SharePoint On-Premises as a File Handler

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into SharePoint on-premises environments as a file handler.

File handlers are simple XML files that instruct SharePoint to redirect to your URL of choice whenever a file with a particular extension is clicked. By using a file handler, you’ll override SharePoint’s default behavior so that PDF documents stored in SharePoint are opened directly inside your application. Any edits to the opened files using your application can then be directly saved back to SharePoint.

PSPDFKit for SharePoint is a wrapper on top of PSPDFKit for Web Standalone, which is a client-side JavaScript library for viewing and editing PDF documents directly in a web browser.

PSPDFKit for SharePoint shares the same APIs as PSPDFKit for Web Standalone, so please use the Web documentation when customizing your SharePoint application.

integration diagram

Requirements

Hardware and operating system requirements are determined by the requirements of the SharePoint version you’re targeting, as well as the requirements of the Visual Studio version used for development. Both SharePoint Server and Visual Studio have to be installed on the developer machine.

The required Visual Studio versions for targeting different SharePoint versions are summarized in the following table. Up to Visual Studio 2017, the matching Microsoft Office Developer Tools needs to be manually downloaded and installed. For Visual Studio 2019 and 2022, the relevant components can be selected during installation of Visual Studio.

matrix table

SharePoint Permissions Considerations

To develop SharePoint solutions, you must have sufficient permissions to run and debug them. Before you can test a SharePoint solution, take the following steps to ensure you have the necessary permissions:

  1. Add your user account as an Administrator on the system.

  2. Add your user account as a Farm Administrator for the SharePoint server.

  • In SharePoint Central Administration, click the Manage the farm administrators group link.

  • On the Farm Administrators page, click the New button.

  1. Add your user account to the WSS_ADMIN_WPG group.

You can find more information by clicking the link that corresponds to your version of Visual Studio:

Adding the PSPDFKit Libraries to the Project

The content (the .wasm file and the JavaScript, CSS, and font files) mentioned in this next part is the PSPDFKit Web Standalone product. It enables the browser to render and edit PDF files.

  1. Download the latest PSPDFKit Web Standalone libraries from https://customers.pspdfkit.com/download/web/latest.

  2. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2022.2.2.tar.gz to your computer.

  3. Once the download is complete, extract the archive.

  4. Right-click on the Layouts > OpenPDFSharePoint > assets > modern folder in the Solution Explorer window and select Add > Existing Item…

  5. Navigate to the extracted package > dist > modern > pspdfkit.js file, select it, and click Add.

  6. Now, right-click on the Layouts > OpenPDFSharePoint > assets > modern > pspdfkit-lib folder in the Solution Explorer window and select Add > Existing Item… again.

  7. Navigate to the extracted package > dist > modern > pspdfkit-lib folder, select all the files in the folder, and click Add. The result will look like this:

PSPDFKit library files

Adding a PDF Viewer Page

This SharePoint application page will encapsulate the PSPDFKit Web Standalone component and configure it to display the selected PDF file. It’ll also save the changes back into the SharePoint library.

Right-click the OpenPDFSharePoint folder inside the Layouts folder in the Solution Explorer window and select Add > New Item.

Add new item

Select Application Page (Farm Solution only) and name it ViewPDF.aspx. Click Add.

Add Application Page for Farm Solution

In the ViewPDF.aspx file, identify the the main content placeholder:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
</asp:Content>

You have to add three things inside the main content placeholder.

  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: calc(100vh - 210px);"></div>
  1. Add a reference to the PSPDFKit JavaScript file:

<script type="text/javascript" src="assets/modern/pspdfkit.js"></script>
  1. Add the following script:

<script type="text/javascript">
	 // !!! Enter your license key here !!!
	 let licenseKey = "paste your license here";

	 // Load PDF Editor
	 PSPDFKit.load({
		  container: "#pspdfkit",
		  document: "<%= fileURL %>",
		  licenseKey: licenseKey
	 })
		  .then(function (instance) {
				console.log("PSPDFKit loaded", instance);
		  })
		  .catch(function (error) {
				console.error(error.message);
		  });
</script>

If you have a PSPDFKit license, then paste it into the script (at the beginning) between the quotation marks. Otherwise, let the licenseKey variable be an empty string.

Warning

You must explicitly set the type attribute of the script elements to `"text/javascript"`. Otherwise, they’ll be ignored.

Modify the ViewPDF.aspx.cs code behind the file to include the fileURL public property and some new code in the Page_load event:

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System;

namespace OpenPDFSharePoint.Layouts.OpenPDFSharePoint
{
	 public partial class ViewPDF : LayoutsPageBase
	 {
		  /// <summary>
		  /// Gets the file URL extracted from the URL key.
		  /// </summary>
		  public string fileURL { get; private set; }

		  /// <summary>
		  /// Page load event.
		  /// </summary>
		  protected void Page_Load(object sender, EventArgs e)
		  {
				// Extract the file URL for the SharePoint file.
				fileURL = Request.QueryString["fileURL"];
		  }
	 }
}

Adding a File Handler

A SharePoint file handler can be used to link PDF files to the PSPDFKit PDF editor. The file handlers are simple XML files at a specific location. They instruct SharePoint to redirect to your URL of choice whenever a file with a particular extension is clicked.

Add an .xml file named serverfilesPSPDFKit.xml to the XML folder in the solution with the following content:

<?xml version="1.0" encoding="utf-8" ?>
<ServerFiles>
  <!-- Redirect any links to a PDF file to the PDF Editor application page -->
  <Mapping FileExtension="pdf" RedirectUrlTemplate="/_layouts/15/OpenPDFSharePoint/ViewPDF.aspx?fileURL=|0" NoGetRedirect="TRUE"/>
</ServerFiles>

Enabling the WASM MIME Type

Before the above example can be used, verify that .wasm files are served by your SharePoint web server.

Start the Internet Information Services (IIS) Manager. Navigate to the website that belongs to your SharePoint instance. Double-click MIME Types in the Features View.

Enabling the WASM MIME Type

If .wasm isn’t in the list of extensions, click the Add button in the Actions pane. In the Add MIME Type popup window, enter ".wasm" (under File name extension:) and "application/wasm" (under MIME type:).

Add Mime type

Publishing the Solution

Visual Studio allows you to deploy your solution to the SharePoint instance you selected at the beginning for debugging purposes. Select Build > Deploy Solution.

The Build menu

It’s also possible to publish a deployable package (.wsp) by selecting Build > Publish… Pick Publish to File System, specifying your desired location, and clicking Publish.

Publish your solution

Installing the Solution

Open the SharePoint Management Shell with Run as administrator. Assuming you have the .wsp file in the c:\deploy folder, copy and execute the following command:

Add-SPSolution "c:\deploy\OpenPDFSharePoint.wsp"

Next, copy and execute the following command:

Install-SPSolution -Identity OpenPDFSharePoint.wsp -GACDeployment
Warning

SharePoint Administration and SharePoint Timer Service must be running.

Using the Solution

Navigate to a SharePoint document library and click on a PDF file. It’ll open in the PSPDFKit PDF editor.

You can now begin customizing the user interface or implementing custom functionality.

Next Steps

Integrate into Microsoft Teams

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into Microsoft Teams as a tab app. By the end of this guide, you’ll be able to use a web browser to directly open PDF documents in a Teams tab, as well as display, edit, and save them back to Teams.

PSPDFKit for Teams is a wrapper on top of PSPDFKit for Web Standalone, which is a client-side JavaScript library for viewing and editing PDF documents directly in a web browser.

PSPDFKit for Teams shares the same APIs as PSPDFKit for Web Standalone, so please use the Web documentation when customizing your Teams application.

integration diagram

Starting with SharePoint v1.8, Microsoft made it possible to build tab apps using a SharePoint Online web part.

To get started with PSPDFKit for Teams, please first follow the instructions for integrating PSPDFKit for SharePoint as a web part.

Once you’ve completed the steps in the guide and the SharePoint web part has been created, add TeamsTab to the supportedHosts property of the web part manifest to use it as a tab in a channel. You’ll find the manifest file under the ./src/webparts/**/**.manifest.json file:

// src/webparts/PSPDFKit/PSPDFKitWebPart.manifest.json
"supportedHosts": ["SharePointWebPart", "TeamsTab"],

The PSPDFKit web part will now appear as a tab app that you can add to a Microsoft Teams channel.

add tabs

Once the PSPDFKit tab app has been added to a channel, click the PSPDFKit tab and select the Settings option. Then click Select Document to choose a PDF file to open.

You can now begin customizing the user interface or implementing custom functionality.

Next Steps

References

Integrate into Microsoft OneDrive

This guide will walk you through the steps necessary to integrate PSPDFKit for Web into Microsoft OneDrive as a file handler. File handlers instruct OneDrive to redirect to your URL of choice whenever a file with a particular extension is clicked. By using a file handler, you’ll override OneDrive’s default behavior so that PDF documents are opened directly inside your application. Any edits to the opened files using your application can then be directly saved back to OneDrive.

PSPDFKit for OneDrive is a wrapper on top of PSPDFKit for Web Standalone, which is a client-side JavaScript library for viewing and editing PDF documents directly in a web browser.

PSPDFKit for OneDrive shares the same APIs as PSPDFKit for Web Standalone, so please use the Web documentation when customizing your OneDrive application.

integration diagram

SharePoint Online and OneDrive share the same file handler manifest, which means that implementing the file handler for OneDrive will automatically also implement it for SharePoint. It isn’t possible to selectively implement it for only one of these services. Therefore, to implement the OneDrive file handler, please follow the instructions for implementing the SharePoint Online file handler.

After the SharePoint Online file handler has been deployed, PDF documents in the OneDrive document library will open by default in your PDF editor, where they can be edited and saved.

You can now begin customizing the user interface or implementing custom functionality.

Next Steps

Integrate into a Vanilla JavaScript Project

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

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Integrating into Your Project

  1. Add an empty <div> element to a file named index.html with a defined width and height to where PSPDFKit will be mounted:

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

<script type="text/javascript" src="https://cdn.cloud.pspdfkit.com/pspdfkit-web@2022.5.1/pspdfkit.js"></script>
  1. Initialize PSPDFKit for Web in JavaScript by calling PSPDFKit.load(). Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

<script>
	PSPDFKit.load({
    container: "#pspdfkit",
    authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" },
    instant: true
	})
	.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"
    />

    <script type="text/javascript" src="https://cdn.cloud.pspdfkit.com/pspdfkit-web@2022.5.1/pspdfkit.js"></script>
  </head>
  <body>
    <!-- Element where PSPDFKit will be mounted. -->
    <div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

    <script>
      PSPDFKit.load({
        container: "#pspdfkit",
        authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" }
      })
        .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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web UI.

Requirements

You need Node.js to complete this guide, but in general, Node.js isn’t a requirement for using PSPDFKit for Web.

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Integrating into Your Project

  1. Add an empty <div> element to a file named index.html 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 a file named index.js by calling PSPDFKit.load(). Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

import "https://cdn.cloud.pspdfkit.com/pspdfkit-web@2022.5.1/pspdfkit.js";

PSPDFKit.load({
  container: "#pspdfkit",
  authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" },
  instant: true
})
.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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web 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

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

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

import { useEffect, useRef, useState } from "react";
import PSPDFKit from "pspdfkit";

export default function PdfViewerComponent(props) {
  // Reference to the DOM element that serves as a container for PSPDFKit.
  const containerRef = useRef(null);

  // We'll use state to store the loaded PSPDFKit instance.
  const [instance, setInstance] = useState(null)

  useEffect(() => {
    const container = containerRef.current;

    (async function() {
        const instance = await PSPDFKit.load({
          // Container where PSPDFKit should be mounted.
          container,
          // The access token to use.
          authPayload: { accessToken: props.accessToken },
          // Enable Instant collaboration.
          instant: true,
        });

        setInstance(instance);
    })();

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

  useEffect(() => {
    if (instance) {
      // Perform side effects on the loaded PSPDFKit instance.
      console.log(instance);
    }
  }, [instance]);

  return (
    <div ref={containerRef} style={{ width: "100%", height: "100vh"}}/>
  );
}
  1. Include the newly created component in App.js. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

import PdfViewerComponent from './components/PdfViewerComponent';

function App() {
  return (
    <div className="App">
      <div className="PDF-viewer">
        <PdfViewerComponent
          accessToken={"psd_live_<rest_of_your_access_token>"}
        />
      </div>
    </div>
  );
}

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

pspdfkit-react-example
├── 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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web UI.

Adding PSPDFKit to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

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

import { useEffect, useRef, useState } from "react";
import PSPDFKit from "pspdfkit";

export default function PdfViewerComponent(props) {
  // Reference to the DOM element that serves as a container for PSPDFKit.
  const containerRef = useRef(null);

  // We'll use state to store the loaded PSPDFKit instance.
  const [instance, setInstance] = useState(null)

  useEffect(() => {
    const container = containerRef.current;

    (async function() {
        const instance = await PSPDFKit.load({
          // Container where PSPDFKit should be mounted.
          container,
          // The access token to use.
          authPayload: { accessToken: props.accessToken },
          // Enable Instant collaboration.
          instant: true,
        });

        setInstance(instance);
    })();

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

  useEffect(() => {
    if (instance) {
      // Perform side effects on the loaded PSPDFKit instance.
      console.log(instance);
    }
  }, [instance]);

  return (
    <div ref={containerRef} style={{ width: "100%", height: "100vh"}}/>
  );
}
  1. Include the newly created component in your app. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

import PdfViewerComponent from './components/PdfViewerComponent';

// Add the PSPDFKit wrapper component to your `render` function.
function DocumentViewerComponent() {
  return (
    <div className="PDF-viewer">
      <PdfViewerComponent
        accessToken={"psd_live_<rest_of_your_access_token>"}
      />
    </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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web 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 to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

  1. 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 Cloud Angular Example";

	ngAfterViewInit() {
		PSPDFKit.load({
      container: "#pspdfkit-container",
      authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" },
      instant: true
		} as any).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;
		});
	}
}

Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token.

  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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web UI.

Adding PSPDFKit to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

  1. 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. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

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({
      container: "#pspdfkit-container",
      authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" },
      instant: true
    } as any).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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web 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 3) ([Vue 3] 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 to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

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

<template>
  <div class="pdf-container"></div>
</template>

<script>
import PSPDFKit from "pspdfkit";

/**
 * PSPDFKit for Web example component.
 */
export default {
  name: 'PSPDFKit',
  /**
	 * The component receives `pdfFile` as a prop, which is type of `String` and is required.
	 */
  props: {
    accessToken: {
      type: String,
      required: true,
    },
  },
  /**
	* We wait until the template has been rendered to load the document into the library.
	*/
  mounted() {
    this.loadPSPDFKit().then((instance) => {
      this.$emit("loaded", instance);
    });
  },
  /**
	 * We watch for `pdfFile` prop changes and trigger unloading and loading when there's a new document to load.
	 */
  watch: {
    accessToken(val) {
      if (val) {
        this.loadPSPDFKit();
      }
    },
  },
  /**
	 * Our component has the `loadPSPDFKit` method. This unloads and cleans up the component and triggers document loading.
	 */
  methods: {
    async loadPSPDFKit() {
      PSPDFKit.unload(".pdf-container");
      return PSPDFKit.load({
        // Container where PSPDFKit should be mounted.
        container: ".pdf-container",
        // The access token to use.
        authPayload: { accessToken: this.accessToken },
        // Enable Instant collaboration.
        instant: true,
      });
    },
  },

  /**
	 * Clean up when the component is unmounted so it's ready to load another document (not needed in this example).
	 */
  beforeUnmount() {
    PSPDFKit.unload(".pdf-container");
  },
};
</script>


<style scoped>
.pdf-container {
  height: 100vh;
}
</style>
  1. Include the newly created component in src/App.vue. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

<template>
  <div id="app">
    <PSPDFKitContainer accessToken="psd_live_<rest_of_your_access_token>" @loaded="handleLoaded" />
  </div>
</template>

<script>
import PSPDFKitContainer from "@/components/PSPDFKitContainer";

export default {
  /**
   * Render the `PSPDFKitContainer` component.
   */
  components: {
    PSPDFKitContainer,
  },
  /**
   * Our component has a method to get notified about the document being loaded.
   */
  methods: {
    handleLoaded(instance) {
      console.log("PSPDFKit has loaded: ", instance);
      // Do something.
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

body {
  margin: 0;
}

input[type="file"] {
    display: none;
}

.custom-file-upload {
    border: 1px solid #ccc;
    border-radius: 4px;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    background:#4A8FED;
    padding:10px;
    color:#fff;
    font:inherit;
    font-size: 16px;
    font-weight: bold;
}

</style>
  1. Start the app:

yarn serve
npm run 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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web UI.

Adding PSPDFKit to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

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

<template>
  <div class="pdf-container"></div>
</template>

<script>
import PSPDFKit from "pspdfkit";

/**
 * PSPDFKit for Web example component.
 */
export default {
  name: 'PSPDFKit',
  /**
	 * The component receives `pdfFile` as a prop, which is type of `String` and is required.
	 */
  props: {
    accessToken: {
      type: String,
      required: true,
    },
  },
  /**
	* We wait until the template has been rendered to load the document into the library.
	*/
  mounted() {
    this.loadPSPDFKit().then((instance) => {
      this.$emit("loaded", instance);
    });
  },
  /**
	 * We watch for `pdfFile` prop changes and trigger unloading and loading when there's a new document to load.
	 */
  watch: {
    accessToken(val) {
      if (val) {
        this.loadPSPDFKit();
      }
    },
  },
  /**
	 * Our component has the `loadPSPDFKit` method. This unloads and cleans up the component and triggers document loading.
	 */
  methods: {
    async loadPSPDFKit() {
      PSPDFKit.unload(".pdf-container");
      return PSPDFKit.load({
        // Container where PSPDFKit should be mounted.
        container: ".pdf-container",
        // The access token to use.
        authPayload: { accessToken: this.accessToken },
        // Enable Instant collaboration.
        instant: true,
      });
    },
  },

  /**
	 * Clean up when the component is unmounted so it's ready to load another document (not needed in this example).
	 */
  beforeUnmount() {
    PSPDFKit.unload(".pdf-container");
  },
};
</script>


<style scoped>
.pdf-container {
  height: 100vh;
}
</style>
  1. Include the newly created component in src/App.vue. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

<template>
  <div id="app">
    <PSPDFKitContainer accessToken="psd_live_<rest_of_your_access_token>" @loaded="handleLoaded" />
  </div>
</template>

<script>
import PSPDFKitContainer from "@/components/PSPDFKitContainer";

export default {
  /**
   * Render the `PSPDFKitContainer` component.
   */
  components: {
    PSPDFKitContainer,
  },
  /**
   * Our component has a method to get notified about the document being loaded.
   */
  methods: {
    handleLoaded(instance) {
      console.log("PSPDFKit has loaded: ", instance);
      // Do something.
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

body {
  margin: 0;
}

input[type="file"] {
    display: none;
}

.custom-file-upload {
    border: 1px solid #ccc;
    border-radius: 4px;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    background:#4A8FED;
    padding:10px;
    color:#fff;
    font:inherit;
    font-size: 16px;
    font-weight: bold;
}

</style>
  1. Start the app:

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

Next Steps

Integrate into a Next.js Project

This guide will walk you through the steps necessary to integrate PSPDFKit Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web 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

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

  1. Add the following code to your pages/index.js file. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

import React, { useEffect, useRef } from "react";

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

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

    (async function () {
      PSPDFKit = await import("pspdfkit");
      
      if (PSPDFKit) {
        PSPDFKit.unload(container);
      }
      
      await PSPDFKit.load({
        // Container where PSPDFKit should be mounted.
        container,
        // The access token to use.
        authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" },
        // Enable Instant collaboration.
        instant: true,
      });
    })();

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

  return (
      <div ref={containerRef} style={{ height: "100vh" }} />
  );
}
  1. Start the app:

yarn dev
npm run 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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web UI.

Adding PSPDFKit to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

  1. Add the following code to your pages/index.js file. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

import React, { useEffect, useRef } from "react";

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

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

    (async function () {
      PSPDFKit = await import("pspdfkit");
      
      if (PSPDFKit) {
        PSPDFKit.unload(container);
      }
      
      await PSPDFKit.load({
        // Container where PSPDFKit should be mounted.
        container,
        // The access token to use.
        authPayload: { accessToken: "psd_live_<rest_of_your_access_token>" },
        // Enable Instant collaboration.
        instant: true,
      });
    })();

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

  return (
      <div ref={containerRef} style={{ height: "100vh" }} />
  );
}
  1. Start the app:

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

Next Steps

Integrate into a Svelte Project

This guide will walk you through the steps necessary to integrate PSPDFKit Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web 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

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

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

// src/PdfViewerComponent.svelte

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

  let currentAccessToken;
  let container;
  let instance;

  export let accessToken;

  async function load() {
    currentAccessToken = accessToken;
    instance = await PSPDFKit.load({
      // Container where PSPDFKit should be mounted.
      container,
      // The access token to use.
      authPayload: { accessToken },
      // Enable Instant collaboration.
      instant: true,
    });
  }

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

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

  afterUpdate(() => {
    if (accessToken !== currentAccessToken) {
      unload();
      load();
    }
  });

  onDestroy(() => {
    unload();
  });
</script>

<body>
  <div bind:this={container} style="height: 100vh; width: 100vw;" />
</body>
  1. Replace the contents of the App.svelte file with the newly created component:

// src/App.svelte
  <script>
    import Pspdfkit from './PdfViewerComponent.svelte';
  </script>

  <main>
    <Pspdfkit accessToken='psd_live_<rest_of_your_access_token>'/>
  </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 Cloud into your project. By the end, you’ll be able to present a PDF document in the PSPDFKit for Web UI.

Adding PSPDFKit to Your Project

Add the PSPDFKit dependency:

yarn add pspdfkit
npm install pspdfkit

Uploading a Document to PSPDFKit Cloud

  1. Log in to the PSPDFKit Cloud dashboard.

  2. Pick a document to upload by clicking the Browse Files button.

Upload document step

  1. Wait for the upload to complete.

  2. Note the Copy Token button; you can use it to copy the document’s access token to the clipboard so you can paste it into the code below.

Copy token step

The access token should start with psd_live_, followed by random characters.

Displaying a PDF

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

// src/PdfViewerComponent.svelte

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

  let currentAccessToken;
  let container;
  let instance;

  export let accessToken;

  async function load() {
    currentAccessToken = accessToken;
    instance = await PSPDFKit.load({
      // Container where PSPDFKit should be mounted.
      container,
      // The access token to use.
      authPayload: { accessToken },
      // Enable Instant collaboration.
      instant: true,
    });
  }

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

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

  afterUpdate(() => {
    if (accessToken !== currentAccessToken) {
      unload();
      load();
    }
  });

  onDestroy(() => {
    unload();
  });
</script>

<body>
  <div bind:this={container} style="height: 100vh; width: 100vw;" />
</body>
  1. Include the PdfViewerComponent component in your app. Don’t forget to replace psd_live_<rest_of_your_access_token> with your document’s access token:

// src/App.svelte
  <script>
    import Pspdfkit from './PdfViewerComponent.svelte';
  </script>

  <main>
    <Pspdfkit accessToken='psd_live_<rest_of_your_access_token>'/>
  </main>
  1. Start the app:

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

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

Adding the PSPDFKit Carthage Dependency

Information

For new PSPDFKit integrations, we recommend using Swift Package Manager instead of Carthage.

  1. In the terminal, change the directory to the location of the PSPDFKit-Demo.xcodeproj file and create a Cartfile next to it:

cd path/to/xcode_project_directory
cat > Cartfile
  1. Open your project’s Cartfile in a text editor and add the PSPDFKit dependency:

binary "https://customers.pspdfkit.com/pspdfkit-ios.json"
  1. Run carthage update and wait for Carthage to download PSPDFKit.

  2. Open your application’s project or workspace in Xcode.

  3. Drag the binaries from Carthage/Build/iOS into the Frameworks, Libraries, and Embedded Content section of your target.

drag-and-drop-frameworks

  1. To work around the compatibility issue between fat frameworks and Xcode 12, make sure EXCLUDED_ARCHS for iOS Simulator SDK is set to arm architectures (arm64) in your project configuration. This ensures you’ll avoid running into an issue while building for iOS Simulator:

"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;

drag-and-drop-frameworks

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

Adding the PSPDFKit Swift Package

  1. Open your application in Xcode and select your project’s Package Dependencies tab:

Selecting the Xcode project Package Dependencies

  1. Copy the PSPDFKit Swift package repository URL into the search field:

https://github.com/PSPDFKit/PSPDFKit-SP

Adding the package URL

  1. Under Dependency Rule, select Branch: master, and then click Add Package:

Choosing Branch: master

💡 Tip: Using Branch: master will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select Version: Up to Next Minor to update at your own pace.

After the package download completes, select Add Package:

Adding the package

PSPDFKit should now be listed under Swift Package Dependencies in the Xcode Project navigator.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

  3. Close the Xcode project for now.

Adding the PSPDFKit CocoaPods Dependency

  1. Open the terminal and go to the directory containing your Xcode project: cd path/to/PSPDFKit-Demo.

  2. Run pod init. This will create a new Podfile next to your .xcodeproj file:

podfile-created

  1. Open the newly created Podfile in a text editor and add the PSPDFKit pod URL:

pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'

Your Podfile should look like this:

target 'PSPDFKit-Demo' do
  use_frameworks!
  pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end
  1. Run pod install and wait for CocoaPods to download PSPDFKit.

  2. Open your application’s newly created workspace (PSPDFKit-Demo.xcworkspace) in Xcode.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

Adding the PSPDFKit XCFrameworks Manually

  1. Download the latest DMG and mount it on your Mac.

  2. Find PSPDFKit.xcframework and PSPDFKitUI.xcframework in the mounted DMG and copy them to your project directory next to the PSPDFKit-Demo.xcodeproj file.

  3. Drag the newly copied PSPDFKit.xcframework and PSPDFKitUI.xcframework files into the Frameworks, Libraries, and Embedded Content section of your target:

manual-embedded-binaries

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit Carthage Dependency

Information

For new PSPDFKit integrations, we recommend using Swift Package Manager instead of Carthage.

  1. Open your project’s Cartfile in a text editor and add the PSPDFKit dependency:

binary "https://customers.pspdfkit.com/pspdfkit-ios.json"

💡 Tip: The Carthage JSON URL from above will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select a specific version to update at your own pace. Take a look at our Advanced Carthage Integration guide for more details.

  1. In the terminal, change the directory to the location of your Cartfile: cd path/to/Cartfile.

  2. Run carthage update and wait for Carthage to download PSPDFKit.

  3. Open your application’s project or workspace in Xcode.

  4. Drag the binaries from Carthage/Build/iOS into the Frameworks, Libraries, and Embedded Content section of your target.

drag-and-drop-frameworks

  1. To work around the compatibility issue between fat frameworks and Xcode 12, make sure EXCLUDED_ARCHS for iOS Simulator SDK is set to arm architectures (arm64) in your project configuration. This ensures you’ll avoid running into an issue while building for iOS Simulator:

"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;

drag-and-drop-frameworks

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller. This can be done in a button action handler, table view cell selection delegate, or similar:

// Update to use your document name.
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
let document = Document(url: fileURL)

// The configuration closure is optional and allows additional customization.
let pdfController = PDFViewController(document: document) {
	$0.isPageLabelEnabled = false
}

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
present(UINavigationController(rootViewController: pdfController), animated: true)
// Update to use your document name.
NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

// The configuration object is optional and allows additional customization.
PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
	builder.pageLabelEnabled = NO;
}]];

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
[self presentViewController:navController animated:YES completion:NULL];
  1. Build and run your application.

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit CocoaPods Dependency

  1. Open your project’s Podfile and add the PSPDFKit pod URL:

pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'

Your Podfile should look like this:

target 'YourTargetName' do
  use_frameworks!
  pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end

💡 Tip: latest.podspec will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select a specific version by replacing latest.podspec with a version number podspec (e.g. 10.2.0.podspec) to update at your own pace. Take a look at our Advanced CocoaPods Integration guide for more details.

  1. In the terminal, go to the directory containing your Podfile: cd path/to/Your-Project.

  2. Run pod install and wait for CocoaPods to download PSPDFKit.

  3. Open your application’s workspace in Xcode.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller. This can be done in a button action handler, table view cell selection delegate, or similar:

// Update to use your document name.
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
let document = Document(url: fileURL)

// The configuration closure is optional and allows additional customization.
let pdfController = PDFViewController(document: document) {
	$0.isPageLabelEnabled = false
}

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
present(UINavigationController(rootViewController: pdfController), animated: true)
// Update to use your document name.
NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

// The configuration object is optional and allows additional customization.
PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
	builder.pageLabelEnabled = NO;
}]];

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
[self presentViewController:navController animated:YES completion:NULL];
  1. Build and run your application.

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit Swift Package

  1. Open your application in Xcode and select your project’s Package Dependencies tab:

Selecting the Xcode project Package Dependencies

  1. Copy the PSPDFKit Swift package repository URL into the search field:

https://github.com/PSPDFKit/PSPDFKit-SP

Adding the package URL

  1. Under Dependency Rule, select Branch: master, and then click Add Package:

Choosing Branch: master

💡 Tip: Using Branch: master will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select Version: Up to Next Minor to update at your own pace.

After the package download completes, select Add Package:

Adding the package

PSPDFKit should now be listed under Swift Package Dependencies in the Xcode Project navigator.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller. This can be done in a button action handler, table view cell selection delegate, or similar:

// Update to use your document name.
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
let document = Document(url: fileURL)

// The configuration closure is optional and allows additional customization.
let pdfController = PDFViewController(document: document) {
	$0.isPageLabelEnabled = false
}

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
present(UINavigationController(rootViewController: pdfController), animated: true)
// Update to use your document name.
NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

// The configuration object is optional and allows additional customization.
PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
	builder.pageLabelEnabled = NO;
}]];

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
[self presentViewController:navController animated:YES completion:NULL];
  1. Build and run your application.

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your iOS application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit XCFrameworks Manually

  1. Download the latest DMG and mount it on your Mac.

  2. Find PSPDFKit.xcframework and PSPDFKitUI.xcframework in the mounted DMG and copy them to your project directory next to your .xcodeproj file.

  3. Drag the newly copied PSPDFKit.xcframework and PSPDFKitUI.xcframework files into the Frameworks, Libraries, and Embedded Content section of your target:

manual-embedded-binaries

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller. This can be done in a button action handler, table view cell selection delegate, or similar:

// Update to use your document name.
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
let document = Document(url: fileURL)

// The configuration closure is optional and allows additional customization.
let pdfController = PDFViewController(document: document) {
	$0.isPageLabelEnabled = false
}

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
present(UINavigationController(rootViewController: pdfController), animated: true)
// Update to use your document name.
NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

// The configuration object is optional and allows additional customization.
PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
	builder.pageLabelEnabled = NO;
}]];

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
[self presentViewController:navController animated:YES completion:NULL];
  1. Build and run your application.

Next Steps

This guide will take you through the steps necessary to clone the PSPDFKit Catalog app and run it on your Mac.

Requirements

Cloning PSPDFKit Catalog

  1. Open the terminal and change the current working directory. In this case, we’ll use the ~/Downloads directory:

cd ~/Downloads
  1. Clone the PSPDFKit Catalog repository:

git clone https://github.com/PSPDFKit/pspdfkit-ios-catalog.git
  1. Open the Catalog Xcode project (Catalog.xcodeproj):

open pspdfkit-ios-catalog/Catalog.xcodeproj/
  1. Wait a few moments for the PSPDFKit Swift packages to download.

  2. Build and run the Catalog on an iOS simulator.

💡 Tip: If you see any errors related to Swift Packages, use the File > Packages > Reset Package Caches menu option in Xcode.

catalog-simulator

Next Steps

Creating a New Project

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

create-new-project

  1. Choose the correct template for your project. In this example, we’ll use Empty Activity:

app-template

  1. When prompted, choose your app name (PSPDFKit Demo) and set the Save location, Language, and Minimum SDK (21), of your choice:

app-options

  1. Click the Finish button to save the project to your default project location.

Adding PSPDFKit to Your Project

  1. In the settings.gradle file at the root of your project, add the PSPDFKit Maven repository:

dependencyResolutionManagement {
	repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
	repositories {
		google()
		mavenCentral()
		maven {
			url 'https://customers.pspdfkit.com/maven/'
		}
	}
}
dependencyResolutionManagement {
	repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
	repositories {
		google()
		mavenCentral()
		maven {
			url = uri("https://customers.pspdfkit.com/maven")
		}
	}
}
  1. In your app/build.gradle file, add the PSPDFKit dependency:

dependencies {
	implementation 'com.pspdfkit:pspdfkit:8.4.1'
}
dependencies {
	implementation("com.pspdfkit:pspdfkit:8.4.1")
}

Configuring Your Build

PSPDFKit is supported on Android devices running API level 21 and newer and targeting the latest stable Android version 12 (API 31). Furthermore, PSPDFKit requires apps to enable Java 8 language features to build.

Inside your app/build.gradle file, make sure to have the following configuration:

android {
    compileSdk 31
    buildToolsVersion '30.0.3'

    defaultConfig {
        applicationId 'com.example.app'
        minSdk 21
        targetSdk 31
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
android {
    compileSdk = 31
    buildToolsVersion = "30.0.3"

    defaultConfig {
        applicationId = "com.example.app"
        minSdk = 21
        targetSdk = 31
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}
Information

With minSdk set to 21, your app is available on more than 94.1 percent of devices on the Google Play Store (last update: September 2021).

Displaying a PDF

To verify that PSPDFKit was successfully integrated into your app, try opening a PDF file with the ready-to-use PdfActivity:

  1. Copy a PDF document into the assets directory of your Android project — for example, to src/main/assets/my-document.pdf.

  2. Add PdfActivity to your app’s AndroidManifest.xml:

<application>
	<activity
		android:name="com.pspdfkit.ui.PdfActivity"
		android:windowSoftInputMode="adjustNothing" />
</application>
  1. You can now start PdfActivity with the document from your assets directory:

val uri = Uri.parse("file:///android_asset/my-document.pdf")
val config = PdfActivityConfiguration.Builder(context).build()
PdfActivity.showDocument(this, uri, config)
final Uri uri = Uri.parse("file:///android_asset/my-document.pdf");
final PdfActivityConfiguration config = new PdfActivityConfiguration.Builder(context).build();
PdfActivity.showDocument(this, uri, config);
  1. PdfActivity will now present the document from your assets directory.

Information

Note that the android_assets folder is read-only and is used as a simple example. For actual usage, you might want to copy the file to a local folder first for full read and write privileges. You can read more about this in our guide on opening PDFs from URLs and in Google’s Data and file storage overview.

Next Steps

Adding PSPDFKit to Your Project

  1. In the settings.gradle file at the root of your project, add the PSPDFKit Maven repository:

dependencyResolutionManagement {
	repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
	repositories {
		google()
		mavenCentral()
		maven {
			url 'https://customers.pspdfkit.com/maven/'
		}
	}
}
dependencyResolutionManagement {
	repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
	repositories {
		google()
		mavenCentral()
		maven {
			url = uri("https://customers.pspdfkit.com/maven")
		}
	}
}
  1. In your app/build.gradle file, add the PSPDFKit dependency:

dependencies {
	implementation 'com.pspdfkit:pspdfkit:8.4.1'
}
dependencies {
	implementation("com.pspdfkit:pspdfkit:8.4.1")
}

Configuring Your Build

PSPDFKit is supported on Android devices running API level 21 and newer and targeting the latest stable Android version 12 (API 31). Furthermore, PSPDFKit requires apps to enable Java 8 language features to build.

Inside your app/build.gradle file, make sure to have the following configuration:

android {
    compileSdk 31
    buildToolsVersion '30.0.3'

    defaultConfig {
        applicationId 'com.example.app'
        minSdk 21
        targetSdk 31
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
android {
    compileSdk = 31
    buildToolsVersion = "30.0.3"

    defaultConfig {
        applicationId = "com.example.app"
        minSdk = 21
        targetSdk = 31
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}
Information

With minSdk set to 21, your app is available on more than 94.1 percent of devices on the Google Play Store (last update: September 2021).

Displaying a PDF

To verify that PSPDFKit was successfully integrated into your app, try opening a PDF file with the ready-to-use PdfActivity:

  1. Copy a PDF document into the assets directory of your Android project — for example, to src/main/assets/my-document.pdf.

  2. Add PdfActivity to your app’s AndroidManifest.xml:

<application>
	<activity
		android:name="com.pspdfkit.ui.PdfActivity"
		android:windowSoftInputMode="adjustNothing" />
</application>
  1. You can now start PdfActivity with the document from your assets directory:

val uri = Uri.parse("file:///android_asset/my-document.pdf")
val config = PdfActivityConfiguration.Builder(context).build()
PdfActivity.showDocument(this, uri, config)
final Uri uri = Uri.parse("file:///android_asset/my-document.pdf");
final PdfActivityConfiguration config = new PdfActivityConfiguration.Builder(context).build();
PdfActivity.showDocument(this, uri, config);
  1. PdfActivity will now present the document from your assets directory.

Information

Note that the android_assets folder is read-only and is used as a simple example. For actual usage, you might want to copy the file to a local folder first for full read and write privileges. You can read more about this in our guide on opening PDFs from URLs and in Google’s Data and file storage overview.

Next Steps

Adding PSPDFKit to Your Project

PSPDFKit for Android can be imported manually. Below are the steps to follow if you wish to do so.

  1. Download the PSPDFKit for Android library AAR bundle from our Maven repository.

  2. Copy the PSPDFKit AAR file into your project’s libs directory, and rename it to pspdfkit-8.4.1.aar.

  3. Include PSPDFKit as a file-based dependency in your project, and provide all the transitive dependencies required by PSPDFKit (as shown below):

dependencies {
	implementation files('libs/pspdfkit-8.4.1.aar')

	// You must include all transitive dependencies of PSPDFKit.
	implementation 'androidx.legacy:legacy-support-v4:1.0.0'
	implementation 'androidx.appcompat:appcompat:1.4.1'
	implementation 'androidx.recyclerview:recyclerview:'
	implementation 'androidx.cardview:cardview:1.0.0'
	implementation 'androidx.palette:palette:1.0.0'
	implementation 'androidx.exifinterface:exifinterface:1.3.2'
	implementation 'androidx.gridlayout:gridlayout:1.0.0'
	implementation 'androidx.viewpager2:viewpager2:1.0.0'
	implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
	implementation 'io.reactivex.rxjava2:rxjava:2.2.7'
	implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
	implementation 'com.getkeepsafe.relinker:relinker:1.4.4'
	implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.10'
}

ℹ️ Note: Starting with the Android Gradle plugin 3.5.0, the use of flatDir repositories to include local AAR files is no longer supported. If you’ve been using this technique, you need to migrate to file-based dependencies when updating the Android Gradle plugin to 3.5.0.

The following library is included in the list of transitive dependencies:

  • ReLinker — to work around some versions of Android that have unreliable PackageManager implementations

This optional library can be omitted from the list of transitive dependencies if you don’t want to bundle it with your app. In such a case, PSPDFKit will detect the absence of this dependency and fall back to different implementations.

ProGuard

There’s no need to specify additional ProGuard rules since PSPDFKit uses consumersProguardFiles to keep ProGuard from obfuscating the required symbols. If you want to check out the rules, you should take a look at proguard.txt, which is located inside the PSPDFKit .aar:

cd [YOUR_AAR_LOCATION]
	unzip [YOUR_AAR_NAME].aar -d aar-contents
	cat aar-contents/proguard.txt

Displaying a PDF

To verify that PSPDFKit was successfully integrated into your app, try opening a PDF file with the ready-to-use PdfActivity:

  1. Copy a PDF document into the assets directory of your Android project — for example, to src/main/assets/my-document.pdf.

  2. Add PdfActivity to your app’s AndroidManifest.xml:

<application>
	<activity
		android:name="com.pspdfkit.ui.PdfActivity"
		android:windowSoftInputMode="adjustNothing" />
</application>
  1. You can now start PdfActivity with the document from your assets directory:

val uri = Uri.parse("file:///android_asset/my-document.pdf")
val config = PdfActivityConfiguration.Builder(context).build()
PdfActivity.showDocument(this, uri, config)
final Uri uri = Uri.parse("file:///android_asset/my-document.pdf");
final PdfActivityConfiguration config = new PdfActivityConfiguration.Builder(context).build();
PdfActivity.showDocument(this, uri, config);
  1. PdfActivity will now present the document from your assets directory.

Information

Note that the android_assets folder is read-only and is used as a simple example. For actual usage, you might want to copy the file to a local folder first for full read and write privileges. You can read more about this in our guide on opening PDFs from URLs and in Google’s Data and file storage overview.

Next Steps

Cloning PSPDFKit Catalog

  1. Open the terminal app and change the current working directory. In this case, we’ll use the ~/Downloads directory:

cd ~/Downloads
  1. Clone the PSPDFKit for Android Catalog repository:

git clone https://github.com/PSPDFKit/pspdfkit-android-catalog.git
  1. Start Android Studio and open the cloned project folder from the File > Open… menu.

  2. Wait a few moments for Gradle to sync the project.

  3. Make sure you either set up an emulator with the AVD or connect an Android device.

  4. Build and run the app configuration using the Run ‘app’ button in Android Studio.

build-run-catalog-app

  1. You should see the PSPDFKit Catalog app on your device:

catalog-view

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created Mac Catalyst application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project. Mac Catalyst is a technology that enables creating Mac versions of iPad apps, so make sure to select the iOS platform at the top:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

  3. Enable Mac support for your target:

enable-mac-support

Adding the PSPDFKit Swift Package

  1. Open your application in Xcode and select your project’s Package Dependencies tab:

Selecting the Xcode project Package Dependencies

  1. Copy the PSPDFKit Swift package repository URL into the search field:

https://github.com/PSPDFKit/PSPDFKit-SP

Adding the package URL

  1. Under Dependency Rule, select Branch: master, and then click Add Package:

Choosing Branch: master

💡 Tip: Using Branch: master will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select Version: Up to Next Minor to update at your own pace.

After the package download completes, select Add Package:

Adding the package

PSPDFKit should now be listed under Swift Package Dependencies in the Xcode Project navigator.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created Mac Catalyst application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project. Mac Catalyst is a technology that enables creating Mac versions of iPad apps, so make sure to select the iOS platform at the top:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

  3. Enable Mac support for your target:

enable-mac-support

  1. Close the Xcode project for now.

Adding the PSPDFKit CocoaPods Dependency

  1. Open the terminal and go to the directory containing your Xcode project: cd path/to/PSPDFKit-Demo.

  2. Run pod init. This will create a new Podfile next to your .xcodeproj file:

podfile-created

  1. Open the newly created Podfile in a text editor and add the PSPDFKit pod URL:

pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'

Your Podfile should look like this:

target 'PSPDFKit-Demo' do
  use_frameworks!
  pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end
  1. Run pod install and wait for CocoaPods to download PSPDFKit.

  2. Open your application’s newly created workspace (PSPDFKit-Demo.xcworkspace) in Xcode.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into a newly created Mac Catalyst application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Creating a New Xcode Project

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

create-new-project

  1. Choose the App template for your project. Mac Catalyst is a technology that enables creating Mac versions of iPad apps, so make sure to select the iOS platform at the top:

app-template

  1. When prompted, enter your app name (PSPDFKit-Demo) and your organization identifier (com.example) and choose Storyboard for the interface:

app-options

  1. Click the Next button and select the location to save the project.

  2. Click the Create button to finish.

  3. Enable Mac support for your target:

enable-mac-support

Adding the PSPDFKit XCFrameworks Manually

  1. Download the latest DMG and mount it on your Mac.

  2. Find PSPDFKit.xcframework and PSPDFKitUI.xcframework in the mounted DMG and copy them to your project directory next to the PSPDFKit-Demo.xcodeproj file.

  3. Drag the newly copied PSPDFKit.xcframework and PSPDFKitUI.xcframework files into the Frameworks, Libraries, and Embedded Content section of your target:

manual-embedded-binaries

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your Mac Catalyst application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit Swift Package

  1. Open your application in Xcode and select your project’s Package Dependencies tab:

Selecting the Xcode project Package Dependencies

  1. Copy the PSPDFKit Swift package repository URL into the search field:

https://github.com/PSPDFKit/PSPDFKit-SP

Adding the package URL

  1. Under Dependency Rule, select Branch: master, and then click Add Package:

Choosing Branch: master

💡 Tip: Using Branch: master will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select Version: Up to Next Minor to update at your own pace.

After the package download completes, select Add Package:

Adding the package

PSPDFKit should now be listed under Swift Package Dependencies in the Xcode Project navigator.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller. This can be done in a button action handler, table view cell selection delegate, or similar:

// Update to use your document name.
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
let document = Document(url: fileURL)

// The configuration closure is optional and allows additional customization.
let pdfController = PDFViewController(document: document) {
	$0.isPageLabelEnabled = false
}

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
present(UINavigationController(rootViewController: pdfController), animated: true)
// Update to use your document name.
NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

// The configuration object is optional and allows additional customization.
PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
	builder.pageLabelEnabled = NO;
}]];

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
[self presentViewController:navController animated:YES completion:NULL];
  1. Build and run your application.

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your Mac Catalyst application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit CocoaPods Dependency

  1. Open your project’s Podfile and add the PSPDFKit pod URL:

pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'

Your Podfile should look like this:

target 'YourTargetName' do
  use_frameworks!
  pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end

💡 Tip: latest.podspec will ensure you always use the latest available version of PSPDFKit. Alternatively, you can select a specific version by replacing latest.podspec with a version number podspec (e.g. 10.2.0.podspec) to update at your own pace. Take a look at our Advanced CocoaPods Integration guide for more details.

  1. In the terminal, go to the directory containing your Podfile: cd path/to/Your-Project.

  2. Run pod install and wait for CocoaPods to download PSPDFKit.

  3. Open your application’s workspace in Xcode.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller by implementing viewDidAppear(_:) in the ViewController.swift file like so:

override func viewDidAppear(_ animated: Bool) {
	super.viewDidAppear(animated)

	// Update to use your document name.
	let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
	let document = Document(url: fileURL)

	// The configuration closure is optional and allows additional customization.
	let pdfController = PDFViewController(document: document) {
			$0.isPageLabelEnabled = false
	}

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	present(UINavigationController(rootViewController: pdfController), animated: true)
}
- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	// Update to use your document name.
	NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
	PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

	// The configuration object is optional and allows additional customization.
	PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
			builder.pageLabelEnabled = NO;
	}]];

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
	[self presentViewController:navController animated:YES completion:NULL];
}

Next Steps

This guide will take you through the steps necessary to integrate PSPDFKit into your Mac Catalyst application. By the end, you’ll be able to present a PDF document in the default PSPDFKit UI.

Requirements

Adding the PSPDFKit XCFrameworks Manually

  1. Download the latest DMG and mount it on your Mac.

  2. Find PSPDFKit.xcframework and PSPDFKitUI.xcframework in the mounted DMG and copy them to your project directory next to your .xcodeproj file.

  3. Drag the newly copied PSPDFKit.xcframework and PSPDFKitUI.xcframework files into the Frameworks, Libraries, and Embedded Content section of your target:

manual-embedded-binaries

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import PSPDFKit and PSPDFKitUI at the top of your UIViewController subclass implementation:

import PSPDFKit
import PSPDFKitUI
@import PSPDFKit;
@import PSPDFKitUI;
  1. Load your PDF document and display the view controller. This can be done in a button action handler, table view cell selection delegate, or similar:

// Update to use your document name.
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!
let document = Document(url: fileURL)

// The configuration closure is optional and allows additional customization.
let pdfController = PDFViewController(document: document) {
	$0.isPageLabelEnabled = false
}

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
present(UINavigationController(rootViewController: pdfController), animated: true)
// Update to use your document name.
NSURL *documentURL = [NSBundle.mainBundle URLForResource:@"Document" withExtension:@"pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

// The configuration object is optional and allows additional customization.
PSPDFViewController *pdfController = [[PSPDFViewController alloc] initWithDocument:document configuration:[PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) {
	builder.pageLabelEnabled = NO;
}]];

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:pdfController];
[self presentViewController:navController animated:YES completion:NULL];
  1. Build and run your application.

Next Steps

Requirements

Install the following required packages:

Creating a New Flutter Project

  1. Create a Flutter project called pspdfkit_demo with the flutter CLI:

flutter create --org com.example.pspdfkit_demo pspdfkit_demo

Installing the PSPDFKit Flutter Dependency

  1. In the terminal app, change the location of the current working directory to your project:

cd <project-root>
  1. Open the project’s Gradle build file, android/build.gradle:

open android/build.gradle
  1. Modify the Kotlin version inside the buildscript section:

buildscript {
-   ext.kotlin_version = '1.3.50'
+   ext.kotlin_version = '1.5.31'
        repositories {
            google()
            mavenCentral()
    }
...
  1. Open the app’s Gradle build file, android/app/build.gradle:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

android {
-   compileSdkVersion flutter.compileSdkVersion
+   compileSdkVersion 31
...
    defaultConfig {
-        minSdkVersion flutter.minSdkVersion
+        minSdkVersion 21
...
    }
  1. Open Runner.xcworkspace from the ios folder in Xcode:

open ios/Runner.xcworkspace
  1. Make sure the iOS deployment target is set to 14.0 or higher.

iOS Deployment Target

  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit dependency in pubspec.yaml:

dependencies:
  flutter:
     sdk: flutter
+ pspdfkit_flutter:
  1. From the terminal app, run the following command to get all the packages:

flutter packages get
  1. Then run the command below to upgrade the dependencies:

flutter packages get upgrade
  1. Open your project’s Podfile in a text editor:

open ios/Podfile
  1. Update the platform to iOS 14 and add the PSPDFKit Podspec:

-# platform :ios, '9.0'
+platform :ios, '14.0'
...
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
+  pod 'PSPDFKit', podspec:'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end

Displaying a PDF

  1. Open the lib/main.dart file:

open lib/main.dart
  1. Replace the contents of lib/main.dart with the following code snippet that loads a document from the assets path:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:pspdfkit_flutter/pspdfkit.dart';

const String DOCUMENT_PATH = 'PDFs/Document.pdf';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
void showDocument(BuildContext context) async {
	final bytes = await DefaultAssetBundle.of(context).load(DOCUMENT_PATH);
	final list = bytes.buffer.asUint8List();

	final tempDir = await Pspdfkit.getTemporaryDirectory();
	final tempDocumentPath = '${tempDir.path}/$DOCUMENT_PATH';

	final file = await File(tempDocumentPath).create(recursive: true);
	file.writeAsBytesSync(list);

	await Pspdfkit.present(tempDocumentPath);
}

@override
Widget build(BuildContext context) {
	final themeData = Theme.of(context);
	return MaterialApp(
		home: Scaffold(
		body: Builder(
			builder: (BuildContext context) {
				return Center(
				child: Column(
					mainAxisAlignment: MainAxisAlignment.spaceEvenly,
					children: [
						ElevatedButton(
						child: Text('Tap to Open Document',
							style: themeData.textTheme.headline4?.copyWith(fontSize: 21.0)),
							onPressed: () => showDocument(context))
					]));
			},
		)),
	);
}
}
  1. Add the PDF document you want to display in your project’s assets directory. You can use this QuickStart Guide PDF as an example.

  2. Create a PDFs directory:

mkdir PDFs
  1. Copy the sample document into the newly created PDFs directory:

cp ~/Downloads/Document.pdf PDFs/Document.pdf
  1. Specify the assets directory in pubspec.yaml:

# The following section is specific to Flutter.
flutter:
+  assets:
+    - PDFs/
...
  1. Start your Android emulator or iOS simulator, or connect a device.

  2. Run the app with:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Installing the PSPDFKit Flutter Dependency

  1. In the terminal app, change the location of the current working directory to your project:

cd <project-root>
  1. Open the project’s Gradle build file, android/build.gradle:

open android/build.gradle
  1. Modify the Kotlin version inside the buildscript section:

buildscript {
-   ext.kotlin_version = '1.3.50'
+   ext.kotlin_version = '1.5.31'
        repositories {
            google()
            mavenCentral()
    }
...
  1. Open the app’s Gradle build file, android/app/build.gradle:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

android {
-   compileSdkVersion flutter.compileSdkVersion
+   compileSdkVersion 31
...
    defaultConfig {
-        minSdkVersion flutter.minSdkVersion
+        minSdkVersion 21
...
    }
  1. Open Runner.xcworkspace from the ios folder in Xcode:

open ios/Runner.xcworkspace
  1. Make sure the iOS deployment target is set to 14.0 or higher.

iOS Deployment Target

  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit dependency in pubspec.yaml:

dependencies:
  flutter:
     sdk: flutter
+ pspdfkit_flutter:
  1. From the terminal app, run the following command to get all the packages:

flutter packages get
  1. Then run the command below to upgrade the dependencies:

flutter packages get upgrade
  1. Open your project’s Podfile in a text editor:

open ios/Podfile
  1. Update the platform to iOS 14 and add the PSPDFKit Podspec:

-# platform :ios, '9.0'
+platform :ios, '14.0'
...
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
+  pod 'PSPDFKit', podspec:'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end

Displaying a PDF

Integrating into an existing project consists of initializing the PSPDFKit SDK and presenting it with a document.

  1. Import the PSPDFKit package:

import 'package:pspdfkit_flutter/pspdfkit.dart';
  1. Showing a PDF document inside your Flutter app is as simple as this:

Pspdfkit.present('file:///path/to/Document.pdf');

If you’re having trouble with integration, go through the New Project guide to see if there’s anything missing in your setup.

  1. Add the PDF document you want to display in your project’s assets directory. You can use this QuickStart Guide PDF as an example.

  2. Create a PDFs directory:

mkdir PDFs
  1. Copy the sample document into the newly created PDFs directory:

cp ~/Downloads/Document.pdf PDFs/Document.pdf
  1. Specify the assets directory in pubspec.yaml:

# The following section is specific to Flutter.
flutter:
+  assets:
+    - PDFs/
...
  1. Start your Android emulator or iOS simulator, or connect a device.

  2. Run the app with:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Cloning the Flutter Sample Project

  1. Open the terminal app and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-flutter.git
  1. Enter the example project directory:

cd pspdfkit-flutter/example
  1. Start your Android emulator or iOS simulator, or connect a device.

  2. Launch the Catalog application:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Creating a New Flutter Project

  1. Create a Flutter project called pspdfkit_demo with the flutter CLI:

flutter create --org com.example.pspdfkit_demo pspdfkit_demo

Installing the PSPDFKit Flutter Dependency

  1. In the terminal app, change the location of the current working directory to your project:

cd <project-root>
  1. Open the project’s Gradle build file, android/build.gradle:

open android/build.gradle
  1. Modify the Kotlin version inside the buildscript section:

buildscript {
-   ext.kotlin_version = '1.3.50'
+   ext.kotlin_version = '1.5.31'
        repositories {
            google()
            mavenCentral()
    }
...
  1. Open the app’s Gradle build file, android/app/build.gradle:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

android {
-   compileSdkVersion flutter.compileSdkVersion
+   compileSdkVersion 31
...
    defaultConfig {
-        minSdkVersion flutter.minSdkVersion
+        minSdkVersion 21
...
    }
  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit dependency in pubspec.yaml:

dependencies:
  flutter:
     sdk: flutter
+ pspdfkit_flutter:
  1. From the terminal app, run the following command to get all the packages:

flutter packages get
  1. Then run the command below to upgrade the dependencies:

flutter packages get upgrade

Displaying a PDF

  1. Open the lib/main.dart file:

open lib/main.dart
  1. Replace the contents of lib/main.dart with the following code snippet that loads a document from the assets path:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:pspdfkit_flutter/pspdfkit.dart';

const String DOCUMENT_PATH = 'PDFs/Document.pdf';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
void showDocument(BuildContext context) async {
	final bytes = await DefaultAssetBundle.of(context).load(DOCUMENT_PATH);
	final list = bytes.buffer.asUint8List();

	final tempDir = await Pspdfkit.getTemporaryDirectory();
	final tempDocumentPath = '${tempDir.path}/$DOCUMENT_PATH';

	final file = await File(tempDocumentPath).create(recursive: true);
	file.writeAsBytesSync(list);

	await Pspdfkit.present(tempDocumentPath);
}

@override
Widget build(BuildContext context) {
	final themeData = Theme.of(context);
	return MaterialApp(
		home: Scaffold(
		body: Builder(
			builder: (BuildContext context) {
				return Center(
				child: Column(
					mainAxisAlignment: MainAxisAlignment.spaceEvenly,
					children: [
						ElevatedButton(
						child: Text('Tap to Open Document',
							style: themeData.textTheme.headline4?.copyWith(fontSize: 21.0)),
							onPressed: () => showDocument(context))
					]));
			},
		)),
	);
}
}
  1. Add the PDF document you want to display in your project’s assets directory. You can use this QuickStart Guide PDF as an example.

  2. Create a PDFs directory:

mkdir PDFs
  1. Copy the sample document into the newly created PDFs directory:

cp ~/Downloads/Document.pdf PDFs/Document.pdf
  1. Specify the assets directory in pubspec.yaml:

# The following section is specific to Flutter.
flutter:
+  assets:
+    - PDFs/
...
  1. Start your Android emulator or connect a device.

  2. Run the app with:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Installing the PSPDFKit Flutter Dependency

  1. In the terminal app, change the location of the current working directory to your project:

cd <project-root>
  1. Open the project’s Gradle build file, android/build.gradle:

open android/build.gradle
  1. Modify the Kotlin version inside the buildscript section:

buildscript {
-   ext.kotlin_version = '1.3.50'
+   ext.kotlin_version = '1.5.31'
        repositories {
            google()
            mavenCentral()
    }
...
  1. Open the app’s Gradle build file, android/app/build.gradle:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

android {
-   compileSdkVersion flutter.compileSdkVersion
+   compileSdkVersion 31
...
    defaultConfig {
-        minSdkVersion flutter.minSdkVersion
+        minSdkVersion 21
...
    }
  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit dependency in pubspec.yaml:

dependencies:
  flutter:
     sdk: flutter
+ pspdfkit_flutter:
  1. From the terminal app, run the following command to get all the packages:

flutter packages get
  1. Then run the command below to upgrade the dependencies:

flutter packages get upgrade

Displaying a PDF

Integrating into an existing project consists of initializing the PSPDFKit SDK and presenting it with a document.

  1. Import the PSPDFKit package:

import 'package:pspdfkit_flutter/pspdfkit.dart';
  1. Showing a PDF document inside your Flutter app is as simple as this:

Pspdfkit.present('file:///path/to/Document.pdf');

If you’re having trouble with integration, go through the New Project guide to see if there’s anything missing in your setup.

  1. Add the PDF document you want to display in your project’s assets directory. You can use this QuickStart Guide PDF as an example.

  2. Create a PDFs directory:

mkdir PDFs
  1. Copy the sample document into the newly created PDFs directory:

cp ~/Downloads/Document.pdf PDFs/Document.pdf
  1. Specify the assets directory in pubspec.yaml:

# The following section is specific to Flutter.
flutter:
+  assets:
+    - PDFs/
...
  1. Start your Android emulator or connect a device.

  2. Run the app with:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Cloning the Flutter Sample Project

  1. Open the terminal app and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-flutter.git
  1. Enter the example project directory:

cd pspdfkit-flutter/example
  1. Start your Android emulator or connect a device.

  2. Launch the Catalog application:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Creating a New Flutter Project

  1. Create a Flutter project called pspdfkit_demo with the flutter CLI:

flutter create --org com.example.pspdfkit_demo pspdfkit_demo

Installing the PSPDFKit Flutter Dependency

  1. In the terminal app, change the location of the current working directory to your project:

cd <project-root>
  1. Open Runner.xcworkspace from the ios folder in Xcode:

open ios/Runner.xcworkspace
  1. Make sure the iOS deployment target is set to 14.0 or higher.

iOS Deployment Target

  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit dependency in pubspec.yaml:

dependencies:
  flutter:
     sdk: flutter
+ pspdfkit_flutter:
  1. From the terminal app, run the following command to get all the packages:

flutter packages get
  1. Then run the command below to upgrade the dependencies:

flutter packages get upgrade
  1. Open your project’s Podfile in a text editor:

open ios/Podfile
  1. Update the platform to iOS 14 and add the PSPDFKit Podspec:

-# platform :ios, '9.0'
+platform :ios, '14.0'
...
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
+  pod 'PSPDFKit', podspec:'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end

Displaying a PDF

  1. Open the lib/main.dart file:

open lib/main.dart
  1. Replace the contents of lib/main.dart with the following code snippet that loads a document from the assets path:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:pspdfkit_flutter/pspdfkit.dart';

const String DOCUMENT_PATH = 'PDFs/Document.pdf';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
void showDocument(BuildContext context) async {
	final bytes = await DefaultAssetBundle.of(context).load(DOCUMENT_PATH);
	final list = bytes.buffer.asUint8List();

	final tempDir = await Pspdfkit.getTemporaryDirectory();
	final tempDocumentPath = '${tempDir.path}/$DOCUMENT_PATH';

	final file = await File(tempDocumentPath).create(recursive: true);
	file.writeAsBytesSync(list);

	await Pspdfkit.present(tempDocumentPath);
}

@override
Widget build(BuildContext context) {
	final themeData = Theme.of(context);
	return MaterialApp(
		home: Scaffold(
		body: Builder(
			builder: (BuildContext context) {
				return Center(
				child: Column(
					mainAxisAlignment: MainAxisAlignment.spaceEvenly,
					children: [
						ElevatedButton(
						child: Text('Tap to Open Document',
							style: themeData.textTheme.headline4?.copyWith(fontSize: 21.0)),
							onPressed: () => showDocument(context))
					]));
			},
		)),
	);
}
}
  1. Add the PDF document you want to display in your project’s assets directory. You can use this QuickStart Guide PDF as an example.

  2. Create a PDFs directory:

mkdir PDFs
  1. Copy the sample document into the newly created PDFs directory:

cp ~/Downloads/Document.pdf PDFs/Document.pdf
  1. Specify the assets directory in pubspec.yaml:

# The following section is specific to Flutter.
flutter:
+  assets:
+    - PDFs/
...
  1. Start your iOS simulator.

  2. Run the app with:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Installing the PSPDFKit Flutter Dependency

  1. In the terminal app, change the location of the current working directory to your project:

cd <project-root>
  1. Open Runner.xcworkspace from the ios folder in Xcode:

open ios/Runner.xcworkspace
  1. Make sure the iOS deployment target is set to 14.0 or higher.

iOS Deployment Target

  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit dependency in pubspec.yaml:

dependencies:
  flutter:
     sdk: flutter
+ pspdfkit_flutter:
  1. From the terminal app, run the following command to get all the packages:

flutter packages get
  1. Then run the command below to upgrade the dependencies:

flutter packages get upgrade
  1. Open your project’s Podfile in a text editor:

open ios/Podfile
  1. Update the platform to iOS 14 and add the PSPDFKit Podspec:

-# platform :ios, '9.0'
+platform :ios, '14.0'
...
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
+  pod 'PSPDFKit', podspec:'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
end

Displaying a PDF

Integrating into an existing project consists of initializing the PSPDFKit SDK and presenting it with a document.

  1. Import the PSPDFKit package:

import 'package:pspdfkit_flutter/pspdfkit.dart';
  1. Showing a PDF document inside your Flutter app is as simple as this:

Pspdfkit.present('file:///path/to/Document.pdf');

If you’re having trouble with integration, go through the New Project guide to see if there’s anything missing in your setup.

  1. Add the PDF document you want to display in your project’s assets directory. You can use this QuickStart Guide PDF as an example.

  2. Create a PDFs directory:

mkdir PDFs
  1. Copy the sample document into the newly created PDFs directory:

cp ~/Downloads/Document.pdf PDFs/Document.pdf
  1. Specify the assets directory in pubspec.yaml:

# The following section is specific to Flutter.
flutter:
+  assets:
+    - PDFs/
...
  1. Start your iOS simulator.

  2. Run the app with:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

Install the following required packages:

Cloning the Flutter Sample Project

  1. Open the terminal app and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-flutter.git
  1. Enter the example project directory:

cd pspdfkit-flutter/example
  1. Start your iOS simulator.

  2. Launch the Catalog application:

flutter run

Next Steps

To learn more about Flutter, make sure to check out the following blog posts:

You can find our Flutter library on pub.dev and GitHub.

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Creating a New React Native Project

  1. In the terminal app, change the current working directory to the location you wish to save your project. In this example, we’ll use the ~/Documents/ directory:

cd ~/Documents
  1. Create the React Native project by running the following command:

react-native init PSPDFKitDemo

Installing the PSPDFKit React Native Dependency

  1. In the terminal app, change the location of the current working directory inside the newly created project:

cd PSPDFKitDemo
  1. Add the PSPDFKit plugin:

yarn add github:PSPDFKit/react-native
  1. Install all the dependencies for the project:

yarn install
  1. Open your project’s build.gradle file:

open android/build.gradle
  1. Add the PSPDFKit repository to download the PSPDFKit library:

...
 allprojects {
     repositories {
         mavenLocal()
+        maven {
+            url 'https://customers.pspdfkit.com/maven/'
+        }
...
  1. Open the app’s build.gradle file:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

...
android {
-  compileSdkVersion rootProject.ext.compileSdkVersion
+  compileSdkVersion 31
...
  defaultConfig {
      applicationId "com.pspdfkitdemo"
-     minSdkVersion rootProject.ext.minSdkVersion
+     minSdkVersion 21
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
  }
}
...
  1. Open your project’s Podfile in a text editor to update the platform to iOS 14, and add the PSPDFKit Podspec:

open ios/Podfile

Your Podfile should look like this:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
 
- platform :ios, '11.0'
+ platform :ios, '14.0'

target 'PSPDFKitDemo' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  target 'PSPDFKitDemoTests' do
    inherit! :complete
    # Pods for testing
  end
+ pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
  end
end
  1. Change the location of the current working directory to the ios folder:

cd ios
  1. Install the CocoaPods dependencies:

pod install
  1. Open your project’s Workspace in Xcode:

open PSPDFKitDemo.xcworkspace
  1. Make sure the deployment target is set to 14.0 or higher:

Deployment Target

  1. Change View controller-based status bar appearance to YES in your project’s Info.plist:

View Controller Based Status Bar Appearance

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Change the location of the current working directory back to the root project folder:

cd ..
  1. Create the assets directory:

mkdir android/app/src/main/assets
  1. Copy a PDF document into your assets directory:

cp ~/Downloads/Document.pdf android/app/src/main/assets/Document.pdf
  1. Open your App.js file:

open App.js
  1. Replace the entire contents of App.js with the following code snippet:

import React, {Component} from 'react';
import {Platform} from 'react-native';
import PSPDFKitView from 'react-native-pspdfkit';

const DOCUMENT =
  Platform.OS === 'ios' ? 'Document.pdf' : 'file:///android_asset/Document.pdf';
export default class PSPDFKitDemo extends Component<{}> {
  render() {
    return (
      <PSPDFKitView
        document={DOCUMENT}
        configuration={{
          showThumbnailBar: 'scrollable',
          pageTransition: 'scrollContinuous',
          scrollDirection: 'vertical',
        }}
        ref="pdfView"
        fragmentTag="PDF1"
        style={{flex: 1}}
      />
    );
  }
}
  1. The app is now ready to launch! Go back to the terminal app and run:

npx react-native run-android
npx react-native run-ios

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Installing the PSPDFKit React Native Dependency

  1. Open the terminal app and change the location of the current working directory inside your project:

cd path/to/YourProject
  1. Add the PSPDFKit plugin:

yarn add github:PSPDFKit/react-native
  1. Install all the dependencies for the project:

yarn install
  1. Open your project’s build.gradle file:

open android/build.gradle
  1. Add the PSPDFKit repository to download the PSPDFKit library:

...
 allprojects {
     repositories {
         mavenLocal()
+        maven {
+            url 'https://customers.pspdfkit.com/maven/'
+        }
...
  1. Open the app’s build.gradle file:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

...
android {
-  compileSdkVersion rootProject.ext.compileSdkVersion
+  compileSdkVersion 31
...
  defaultConfig {
      applicationId "com.pspdfkitdemo"
-     minSdkVersion rootProject.ext.minSdkVersion
+     minSdkVersion 21
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
  }
}
...
  1. Open your project’s Podfile in a text editor to update the platform to iOS 14, and add the PSPDFKit Podspec:

open ios/Podfile

Your Podfile should look like this:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
 
- platform :ios, '11.0'
+ platform :ios, '14.0'

target 'PSPDFKitDemo' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  target 'PSPDFKitDemoTests' do
    inherit! :complete
    # Pods for testing
  end
+ pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
  end
end
  1. Change the location of the current working directory to the ios folder:

cd ios
  1. Install the CocoaPods dependencies:

pod install
  1. Open your project’s Workspace in Xcode:

open YourProject.xcworkspace
  1. Make sure the deployment target is set to 14.0 or higher:

Deployment Target

  1. Change View controller-based status bar appearance to YES in your project’s Info.plist:

View Controller Based Status Bar Appearance

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Change the location of the current working directory back to the root project folder:

cd ..
  1. Create the assets directory if you don’t have one already:

mkdir android/app/src/main/assets
  1. Copy a PDF document into your assets directory:

cp ~/Downloads/Document.pdf android/app/src/main/assets/Document.pdf
  1. Use the PSPDFKitView React component in your project:

import {Platform} from 'react-native';
import PSPDFKitView from 'react-native-pspdfkit';

...

const DOCUMENT =
  Platform.OS === 'ios' ? 'Document.pdf' : 'file:///android_asset/Document.pdf';

...

<PSPDFKitView
  document={DOCUMENT}
  configuration={{
    showThumbnailBar: 'scrollable',
    pageTransition: 'scrollContinuous',
    scrollDirection: 'vertical',
  }}
  ref="pdfView"
  fragmentTag="PDF1"
  style={{flex: 1}}
/>
  1. The app is now ready to launch! Go back to the terminal app and run:

npx react-native run-android
npx react-native run-ios

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Cloning the Catalog Sample Project

  1. Open the terminal app and clone the GitHub repository:

git clone https://github.com/PSPDFKit/react-native.git
  1. Change the current working directory to the Catalog directory:

cd react-native/samples/Catalog
  1. Install the dependencies:

yarn install
  1. From the iOS folder, run pod install to install all the iOS dependencies. Go back to the root directory once the command finishes successfully.

cd iOS
pod install
cd ..
  1. The Catalog app is now ready to launch:

npx react-native run-android
npx react-native run-ios

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Creating a New React Native Project

  1. In the terminal app, change the current working directory to the location you wish to save your project. In this example, we’ll use the ~/Documents/ directory:

cd ~/Documents
  1. Create the React Native project by running the following command:

react-native init PSPDFKitDemo

Installing the PSPDFKit React Native Dependency

  1. In the terminal app, change the location of the current working directory inside the newly created project:

cd PSPDFKitDemo
  1. Add the PSPDFKit plugin:

yarn add github:PSPDFKit/react-native
  1. Install all the dependencies for the project:

yarn install
  1. Open your project’s build.gradle file:

open android/build.gradle
  1. Add the PSPDFKit repository to download the PSPDFKit library:

...
 allprojects {
     repositories {
         mavenLocal()
+        maven {
+            url 'https://customers.pspdfkit.com/maven/'
+        }
...
  1. Open the app’s build.gradle file:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

...
android {
-  compileSdkVersion rootProject.ext.compileSdkVersion
+  compileSdkVersion 31
...
  defaultConfig {
      applicationId "com.pspdfkitdemo"
-     minSdkVersion rootProject.ext.minSdkVersion
+     minSdkVersion 21
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
  }
}
...

Displaying a PDF

  1. Add the PDF document you want to display to your application. You can download this QuickStart Guide PDF as an example.

  2. Create the assets directory:

mkdir android/app/src/main/assets
  1. Copy a PDF document into your assets directory:

cp ~/Downloads/Document.pdf android/app/src/main/assets/Document.pdf
  1. Open your App.js file:

open App.js
  1. Replace the entire contents of App.js with the following code snippet:

import React, {Component} from 'react';
import {Platform} from 'react-native';
import PSPDFKitView from 'react-native-pspdfkit';

const DOCUMENT =
  Platform.OS === 'ios' ? 'Document.pdf' : 'file:///android_asset/Document.pdf';
export default class PSPDFKitDemo extends Component<{}> {
  render() {
    return (
      <PSPDFKitView
        document={DOCUMENT}
        configuration={{
          showThumbnailBar: 'scrollable',
          pageTransition: 'scrollContinuous',
          scrollDirection: 'vertical',
        }}
        ref="pdfView"
        fragmentTag="PDF1"
        style={{flex: 1}}
      />
    );
  }
}
  1. The app is now ready to launch! Go back to the terminal app and run:

npx react-native run-android

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Installing the PSPDFKit React Native Dependency

  1. Open the terminal app and change the location of the current working directory inside your project:

cd path/to/YourProject
  1. Add the PSPDFKit plugin:

yarn add github:PSPDFKit/react-native
  1. Install all the dependencies for the project:

yarn install
  1. Open your project’s build.gradle file:

open android/build.gradle
  1. Add the PSPDFKit repository to download the PSPDFKit library:

...
 allprojects {
     repositories {
         mavenLocal()
+        maven {
+            url 'https://customers.pspdfkit.com/maven/'
+        }
...
  1. Open the app’s build.gradle file:

open android/app/build.gradle
  1. Modify the compile SDK version and the minimum SDK version:

...
android {
-  compileSdkVersion rootProject.ext.compileSdkVersion
+  compileSdkVersion 31
...
  defaultConfig {
      applicationId "com.pspdfkitdemo"
-     minSdkVersion rootProject.ext.minSdkVersion
+     minSdkVersion 21
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
  }
}
...

Displaying a PDF

  1. Add the PDF document you want to display to your application. You can download this QuickStart Guide PDF as an example.

  2. Create the assets directory if you don’t have one already:

mkdir android/app/src/main/assets
  1. Copy a PDF document into your assets directory:

cp ~/Downloads/Document.pdf android/app/src/main/assets/Document.pdf
  1. Use the PSPDFKitView React component in your project:

import {Platform} from 'react-native';
import PSPDFKitView from 'react-native-pspdfkit';

...

const DOCUMENT =
  Platform.OS === 'ios' ? 'Document.pdf' : 'file:///android_asset/Document.pdf';

...

<PSPDFKitView
  document={DOCUMENT}
  configuration={{
    showThumbnailBar: 'scrollable',
    pageTransition: 'scrollContinuous',
    scrollDirection: 'vertical',
  }}
  ref="pdfView"
  fragmentTag="PDF1"
  style={{flex: 1}}
/>
  1. The app is now ready to launch! Go back to the terminal app and run:

npx react-native run-android

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Cloning the Catalog Sample Project

  1. Open the terminal app and clone the GitHub repository:

git clone https://github.com/PSPDFKit/react-native.git
  1. Change the current working directory to the Catalog directory:

cd react-native/samples/Catalog
  1. Install the dependencies:

yarn install
  1. The Catalog app is now ready to launch:

npx react-native run-android

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

ℹ️ Note: The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory or npm install github:PSPDFKit/react-native if you’re using npm.

Creating a New React Native Project

  1. In the terminal app, change the current working directory to the location you wish to save your project. In this example, we’ll use the ~/Documents/ directory:

cd ~/Documents
  1. Create the React Native project by running the following command:

react-native init PSPDFKitDemo

Installing the PSPDFKit React Native Dependency

  1. In the terminal app, change the location of the current working directory inside the newly created project:

cd PSPDFKitDemo
  1. Add the PSPDFKit plugin:

yarn add github:PSPDFKit/react-native
  1. Install all the dependencies for the project:

yarn install
  1. Open your project’s Podfile in a text editor to update the platform to iOS 14, and add the PSPDFKit Podspec:

open ios/Podfile

Your Podfile should look like this:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
 
- platform :ios, '11.0'
+ platform :ios, '14.0'

target 'PSPDFKitDemo' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  target 'PSPDFKitDemoTests' do
    inherit! :complete
    # Pods for testing
  end
+ pod 'PSPDFKit', podspec: 'https://customers.pspdfkit.com/pspdfkit-ios/latest.podspec'
  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    rea