Get Started with Our Free Trial

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.

Requirements

Adding to Your Project

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

  1. Add the PSPDFKit dependency:

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

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

Integrating into Your Project

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

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

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

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

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

Here’s the full index.html file:

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

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

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

Serving Your Website

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

  1. Install the serve package:

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

serve -l 8080 .
  1. Navigate to http://localhost:8080 to view the website.

Next Steps

Integrate into a Vanilla JavaScript Project

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

Requirements

Adding to Your Project

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

  1. Add the PSPDFKit dependency:

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

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

Integrating into Your Project

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

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

<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>
  1. Import pspdfkit into your application and initialize PSPDFKit for Web in JavaScript by calling PSPDFKit.load():

import "./assets/pspdfkit.js";

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

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

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

Here’s the full index.html file:

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

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

Serving Your Website

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

  1. Install the serve package:

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

serve -l 8080 .
  1. Navigate to http://localhost:8080 to view the website.

Next Steps

Integrate into a Vanilla JavaScript Project

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

Requirements

Adding to Your Project

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

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.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.

Integrating into Your Project

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

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

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

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

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

Here’s the full index.html file:

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

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

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

Serving Your Website

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

  1. Install the serve package:

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

serve -l 8080 .
  1. Navigate to http://localhost:8080 to view the website.

Next Steps

Integrate into a Vanilla JavaScript Project

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

Requirements

Adding to Your Project

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

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.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.

Integrating into Your Project

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

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

<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>
  1. Import pspdfkit into your application and initialize PSPDFKit for Web in JavaScript by calling PSPDFKit.load():

import "./assets/pspdfkit.js";

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

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

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

Here’s the full index.html file:

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

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

Serving Your Website

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

  1. Install the serve package:

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

serve -l 8080 .
  1. Navigate to http://localhost:8080 to view the website.

Next Steps

Integrate into a React Project

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

Requirements

Creating a New Project

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

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

cd pspdfkit-react-example

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		instance = await PSPDFKit.load({
		// Container where PSPDFKit should be mounted.
		container,
		// The document to open.
		document: props.document,
		// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.
		baseUrl: `${window.location.protocol}//${window.location.host}/${process.env.PUBLIC_URL}`
		});
	})();

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

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

import PSPDFKit from './components/PdfViewerComponent';

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

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

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

yarn start
npm start

Next Steps

Integrate into a React Project

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

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		instance = await PSPDFKit.load({
		// Container where PSPDFKit should be mounted.
		container,
		// The document to open.
		document: props.document,
		// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.
		baseUrl: `${window.location.protocol}//${window.location.host}/${process.env.PUBLIC_URL}`
		});
	})();

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

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

import PSPDFKit from './components/pspdfkit';

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

yarn start
npm start

Next Steps

Integrate into an Angular Project

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

Requirements

Creating a New Project

  1. Install the Angular CLI:

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

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

  2. Change to the created project directory:

cd my-app

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

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

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

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

Displaying a PDF

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

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

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

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

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

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

yarn start --open
npm start --open

Next Steps

Integrate into an Angular Project

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

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

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

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

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

Displaying a PDF

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

  2. Generate a new PDF viewer component:

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

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

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

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

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

yarn start --open
npm start --open

Next Steps

Integrate into a Vue.js Project

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

Requirements

Installing the Vue.js CLI

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

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

Creating the Project

  1. Create a new Vue.js app:

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

Activity controller

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

  2. Change to the created project directory:

cd my-app

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

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

import PSPDFKit from 'pspdfkit';

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

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

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

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

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

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

Next Steps

Integrate into a Vue.js Project

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

Adding PSPDFKit

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

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

import PSPDFKit from 'pspdfkit';

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

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

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

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

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

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

Next Steps

Integrate into a Svelte Project

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

Requirements

Creating a New Project

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

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

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

yarn install
npm install

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

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

      let currentDocument
      let container
      let instance

      export let document

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

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

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

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

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

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

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

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

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

Next Steps

Integrate into a Svelte Project

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

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

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

      let currentDocument
      let container
      let instance

      export let document

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

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

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

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

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

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

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

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

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

Next Steps

Integrate into a PWA Project

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

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

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

Prerequisites

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

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

A Note about Progressive Enhancement

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

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

Opening a PDF File

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

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

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

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

  element.addEventListener("change", handler);

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

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

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

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

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

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

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

Adding Caching and Offline Capabilities with Service Workers

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

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

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

Now, create the ./serviceWorker.js file:

/* ./serviceWorker.js */

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

Then, register it in your application shell:

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

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

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

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

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

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

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

A Note about the Service Worker API

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

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

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

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

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

Final Touches

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

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

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

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

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

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

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

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

Manifest file in the dev tools.

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

Limitations

Disk Quota

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

Precached PSPDFKit Assets

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

Conclusion

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

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

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

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

Integrate into an Electron Project

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

Requirements

Creating a New Project

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

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

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

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

Adding PSPDFKit

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

yarn add pspdfkit
npm install --save pspdfkit

Displaying a PDF

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

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

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	</head>
	<body>
		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

		<script>
			// Invoke the JavaScript for the renderer process.
			require("./renderer.js");
		</script>
	</body>
</html>
  1. Load PSPDFKit in the JavaScript file of your renderer process:

const PSPDFKit = require("pspdfkit");

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

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

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

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

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

	mainWindow.loadFile("index.html");

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

app.whenReady().then(createWindow)

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

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

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

yarn start
npm start

Next Steps

Integrate into an Electron Project

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

Adding PSPDFKit

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

yarn add pspdfkit
npm install --save pspdfkit

Displaying a PDF

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

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

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	</head>
	<body>
		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

		<script>
			// Invoke the JavaScript for the renderer process.
			require("./renderer.js");
		</script>
	</body>
</html>
  1. Load PSPDFKit in the JavaScript file of your renderer process:

const PSPDFKit = require("pspdfkit");

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

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

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

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

yarn start
npm start

Next Steps

Integrate into a Next.js Project

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

Requirements

Creating a New Project

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

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

cd pspdfkit-next-js-example

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		instance = await PSPDFKit.load({
		// Container where PSPDFKit should be mounted.
		container,
		// The document to open.
		document: props.document,
		// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.
		baseUrl: `${window.location.protocol}//${window.location.host}/}`
		});
	})();

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

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

import PdfViewerComponent from '../components/PdfViewerComponent'

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

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

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

Next Steps

Integrate into a Next.js Project

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

Adding PSPDFKit to Your Project

  1. Add the PSPDFKit dependency:

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

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

Displaying a PDF

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

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

import { useEffect, useRef } from "react";

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

useEffect(() => {
	const container = containerRef.current;
	let instance, PSPDFKit;
	(async function() {
		PSPDFKit = await import("pspdfkit");
		instance = await PSPDFKit.load({
		// Container where PSPDFKit should be mounted.
		container,
		// The document to open.
		document: props.document,
		// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.
		baseUrl: `${window.location.protocol}//${window.location.host}/}`
		});
	})();

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

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

import PdfViewerComponent from '../components/PdfViewerComponent'

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

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

Next Steps

Integrate into an ASP.NET Project

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

Requirements

  • Visual Studio 2019 or above

Creating a New Project

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

visual-studio-new-solution

  1. Choose the ASP.NET MVC Project template:

visual-studio-template

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

visual-studio-project-name

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

Adding PSPDFKit

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

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.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 Content/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

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

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

<script src="/Content/pspdfkit/pspdfkit.js>"></script>
  1. Add an empty <div> element with a defined width and height to where PSPDFKit will be mounted:

<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>
  1. Initialize PSPDFKit for Web by calling PSPDFKit.load():

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

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

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

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

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

Displaying the PDF

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

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

Next Steps

Integrate into an ASP.NET Project

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

Requirements

Creating a New Project

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

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

cd pspdfkit-example

Adding PSPDFKit

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

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.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/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

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

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

<script src="/lib/pspdfkit/pspdfkit.js>"></script>
  1. Add an empty <div> element with a defined width and height to where PSPDFKit will be mounted:

<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>
  1. Initialize PSPDFKit for Web by calling PSPDFKit.load():

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

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

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

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

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

Displaying the PDF

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

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

dotnet watch run

Next Steps

Integrate into an ASP.NET Project

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

Requirements

  • Visual Studio 2019 or above

Adding PSPDFKit

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

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.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 Content/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

Integrate PSPDFKit in your view:

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

<script src="/Content/pspdfkit/pspdfkit.js>"></script>
  1. Add an empty <div> element with a defined width and height to where PSPDFKit will be mounted:

<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>
  1. Initialize PSPDFKit for Web by calling PSPDFKit.load():

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

Displaying the PDF

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

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

Next Steps

Integrate into an ASP.NET Project

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

Requirements

Adding PSPDFKit

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

  1. Download the framework here. The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2021.4.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/pspdfkit/ directory in your project.

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

Integrating PSPDFKit

Integrate PSPDFKit in your view:

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

<script src="/lib/pspdfkit/pspdfkit.js>"></script>
  1. Add an empty <div> element with a defined width and height to where PSPDFKit will be mounted:

<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>
  1. Initialize PSPDFKit for Web by calling PSPDFKit.load():

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

Displaying the PDF

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

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

dotnet watch run

Next Steps

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, choose your app name (PSPDFKit-Demo) and use the default options:

app-options

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

  2. Click on the Create button to finish.

Adding the PSPDFKit Carthage Dependency

  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 Validate Workspace in your target’s build settings is enabled:

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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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, choose your app name (PSPDFKit-Demo) and use the default options:

app-options

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

  2. Click on the Create button to finish.

Adding the PSPDFKit Swift Package

  1. Open your application in Xcode and select your project’s Swift Packages tab:

xcode-project-swift-packages

  1. Copy the PSPDFKit Swift package repository URL into the search field and click Next:

https://github.com/PSPDFKit/PSPDFKit-SP

add-package-url

  1. Under Choose Package Options, select Branch: master, and click Next:

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 Finish. 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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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, choose your app name (PSPDFKit-Demo) and use the default options:

app-options

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

  2. Click on the Create button to finish.

  3. Close the Xcode project for now.

Adding the PSPDFKit CocoaPods Dependency

  1. Open the terminal and change the directory to the location of 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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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, choose your app name (PSPDFKit-Demo) and use the default options:

app-options

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

  2. Click on 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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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

  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 Validate Workspace in your target’s build settings is enabled:

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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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, change the directory to the location of your Podfile: cd path/to/Podfile.

  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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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 Swift Packages tab:

xcode-project-swift-packages

  1. Copy the PSPDFKit Swift package repository URL into the search field and click Next:

https://github.com/PSPDFKit/PSPDFKit-SP

add-package-url

  1. Under Choose Package Options, select Branch: master, and click Next:

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 Finish. 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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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.

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 (19), 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 your top-level build.gradle file, add the PSPDFKit Maven repository:

allprojects {
	repositories {
		maven {
				url 'https://customers.pspdfkit.com/maven/'
		}
	}
}
allprojects {
	repositories {
		maven {
				url = uri("https://customers.pspdfkit.com/maven")
		}
	}
}
  1. In your app/build.gradle file, add the PSPDFKit dependency:

dependencies {
	implementation 'com.pspdfkit:pspdfkit:6.6.2'
}
dependencies {
	implementation("com.pspdfkit:pspdfkit:6.6.2")
}

Configuring Your Build

PSPDFKit is supported on Android devices running API level 19 and newer and targeting the latest stable Android version 10 (API 29). 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 {
    compileSdkVersion 29
    buildToolsVersion '29.0.1'

    defaultConfig {
        applicationId 'com.example.app'
        minSdkVersion 19
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
android {
    compileSdkVersion(29)
    buildToolsVersion = "29.0.1"

    defaultConfig {
        applicationId = "com.example.app"
        minSdkVersion(19)
        targetSdkVersion(29)
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}
Information

With minSdkVersion set to 21, your app is available on more than 94.1 percent of devices on the Google Play Store (last update: March 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.

Next Steps

Adding PSPDFKit to Your Project

  1. In your top-level build.gradle file, add the PSPDFKit Maven repository:

allprojects {
	repositories {
		maven {
				url 'https://customers.pspdfkit.com/maven/'
		}
	}
}
allprojects {
	repositories {
		maven {
				url = uri("https://customers.pspdfkit.com/maven")
		}
	}
}
  1. In your app/build.gradle file, add the PSPDFKit dependency:

dependencies {
	implementation 'com.pspdfkit:pspdfkit:6.6.2'
}
dependencies {
	implementation("com.pspdfkit:pspdfkit:6.6.2")
}

Configuring Your Build

PSPDFKit is supported on Android devices running API level 19 and newer and targeting the latest stable Android version 10 (API 29). 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 {
    compileSdkVersion 29
    buildToolsVersion '29.0.1'

    defaultConfig {
        applicationId 'com.example.app'
        minSdkVersion 19
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
android {
    compileSdkVersion(29)
    buildToolsVersion = "29.0.1"

    defaultConfig {
        applicationId = "com.example.app"
        minSdkVersion(19)
        targetSdkVersion(29)
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}
Information

With minSdkVersion set to 21, your app is available on more than 94.1 percent of devices on the Google Play Store (last update: March 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.

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.

  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-6.6.2.aar')

	// You must include all transitive dependencies of PSPDFKit.
	implementation 'androidx.legacy:legacy-support-v4:1.0.0'
	implementation 'androidx.appcompat:appcompat:1.1.0'
	implementation 'androidx.recyclerview:recyclerview:1.0.0'
	implementation 'androidx.cardview:cardview:1.0.0'
	implementation 'androidx.palette:palette:1.0.0'
	implementation 'androidx.exifinterface:exifinterface:1.0.0'
	implementation 'androidx.gridlayout:gridlayout:1.0.0'
	implementation 'com.google.android.material:material:1.2.0-alpha01'
	implementation 'io.reactivex.rxjava2:rxjava:2.2.7'
	implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
	implementation 'com.getkeepsafe.relinker:relinker:1.4.1'
	implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.71'
}

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

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:

app-template

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

app-options

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

  2. Click on 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 Swift Packages tab:

xcode-project-swift-packages

  1. Copy the PSPDFKit Swift package repository URL into the search field and click Next:

https://github.com/PSPDFKit/PSPDFKit-SP

add-package-url

  1. Under Choose Package Options, select Branch: master, and click Next:

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 Finish. 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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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:

app-template

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

app-options

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

  2. Click on 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 change the directory to the location of 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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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:

app-template

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

app-options

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

  2. Click on 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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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 Swift Packages tab:

xcode-project-swift-packages

  1. Copy the PSPDFKit Swift package repository URL into the search field and click Next:

https://github.com/PSPDFKit/PSPDFKit-SP

add-package-url

  1. Under Choose Package Options, select Branch: master, and click Next:

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 Finish. 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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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, change the directory to the location of your Podfile: cd path/to/Podfile.

  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.
	guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
	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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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. Mac Catalyst apps need to be code signed, even during development. So please change the Catalog’s Bundle Identifier and setup code signing using your Team identifier:

code-signing-catalog-catalyst

  1. Build and run the Catalog on your Mac.

catalog-catalyst

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 app’s Gradle build file, android/app/build.gradle:

open android/app/build.gradle
  1. Modify the minimum SDK version, enable multidex, and set the Java compatibility to Java 8 to enable desugaring. All this is done inside the android section:

android {
    defaultConfig {
-        minSdkVersion 16
+        minSdkVersion 21
...
+        multiDexEnabled true
...
+    compileOptions {
+        sourceCompatibility 1.8
+        targetCompatibility 1.8
+    }
...
}
  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit and path_provider dependencies in pubspec.yaml:

dependencies:
flutter:
   sdk: flutter
+  pspdfkit_flutter:
+  path_provider: ^0.4.1
  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:path_provider/path_provider.dart';
import 'package:pspdfkit_flutter/src/main.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 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 plugin 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 app’s Gradle build file, android/app/build.gradle:

open android/app/build.gradle
  1. Modify the minimum SDK version, enable multidex, and set the Java compatibility to Java 8 to enable desugaring. All this is done inside the android section:

android {
    defaultConfig {
-        minSdkVersion 16
+        minSdkVersion 21
...
+        multiDexEnabled true
...
+    compileOptions {
+        sourceCompatibility 1.8
+        targetCompatibility 1.8
+    }
...
}
  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit and path_provider dependencies in pubspec.yaml:

dependencies:
flutter:
   sdk: flutter
+  pspdfkit_flutter:
+  path_provider: ^0.4.1
  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 plugin package:

import 'package:pspdfkit_flutter/src/main.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 plugin 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 plugin 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 12.0 or higher.

iOS Deployment Target

  1. Change View controller-based status bar appearance to YES in Info.plist.

iOS View controller-based status bar appearance

  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit and path_provider dependencies in pubspec.yaml:

dependencies:
flutter:
   sdk: flutter
+  pspdfkit_flutter:
+  path_provider: ^0.4.1
  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 12 and add the PSPDFKit Podspec:

-# platform :ios, '9.0'
+platform :ios, '12.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:path_provider/path_provider.dart';
import 'package:pspdfkit_flutter/src/main.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 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 plugin 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 12.0 or higher.

iOS Deployment Target

  1. Change View controller-based status bar appearance to YES in Info.plist.

iOS View controller-based status bar appearance

  1. Open pubspec.yaml:

open pubspec.yaml
  1. Add the PSPDFKit and path_provider dependencies in pubspec.yaml:

dependencies:
flutter:
   sdk: flutter
+  pspdfkit_flutter:
+  path_provider: ^0.4.1
  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 12 and add the PSPDFKit Podspec:

-# platform :ios, '9.0'
+platform :ios, '12.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 plugin package:

import 'package:pspdfkit_flutter/src/main.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 plugin 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 plugin on pub.dev and GitHub.

Requirements

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. Enable multidex support:

...
  defaultConfig {
      applicationId "com.pspdfkitdemo"
      minSdkVersion rootProject.ext.minSdkVersion
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
+     multiDexEnabled true
  }
...

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={{
          thumbnailBarMode: '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:

react-native run-android

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

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. Enable multidex support:

...
  defaultConfig {
      applicationId "com.pspdfkitdemo"
      minSdkVersion rootProject.ext.minSdkVersion
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
+     multiDexEnabled true
  }
...

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:

const DOCUMENT =
  Platform.OS === 'ios' ? 'Document.pdf' : 'file:///android_asset/Document.pdf';

...

<PSPDFKitView
  document={DOCUMENT}
  configuration={{
    thumbnailBarMode: '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:

react-native run-android

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

Cloning the Catalog Sample Project

  1. Open the terminal app and clone the GitHub repository:

git clone https://github.com/PSPDFKit/react-native.git
cd react-native/samples/Catalog
  1. Install the dependencies:

yarn install
  1. Start your emulator.

  2. Start the Metro bundler by running yarn start within your project folder:

yarn start
  1. The Catalog app is now ready to launch:

react-native run-android

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

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 12, 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, '10.0'
+ platform :ios, '12.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 'react-native-pspdfkit', :path => '../node_modules/react-native-pspdfkit'
+ 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 12.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. 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={{
          thumbnailBarMode: '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:

react-native run-ios

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

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 Podfile in a text editor to update the platform to iOS 12, 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, '10.0'
+ platform :ios, '12.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 'react-native-pspdfkit', :path => '../node_modules/react-native-pspdfkit'
+ 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 12.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. Use the PSPDFKitView React component in your project:

const DOCUMENT =
  Platform.OS === 'ios' ? 'Document.pdf' : 'file:///android_asset/Document.pdf';

...

<PSPDFKitView
  document={DOCUMENT}
  configuration={{
    thumbnailBarMode: '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:

react-native run-ios

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

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 newly cloned folder:

cd react-native
  1. Create a new PSPDFKit directory:

mkdir PSPDFKit
  1. Download the latest version of PSPDFKit for iOS and mount the DMG file.

  2. Copy PSPDFKit.xcframework and PSPDFKitUI.xcframework into the newly created PSPDFKit directory:

cp -r /Volumes/PSPDFKit/*/PSPDFKit.xcframework/ PSPDFKit/PSPDFKit.xcframework
cp -r /Volumes/PSPDFKit/*/PSPDFKitUI.xcframework/ PSPDFKit/PSPDFKitUI.xcframework
  1. Change the current working directory to the Catalog directory:

cd samples/Catalog
  1. Install the dependencies:

yarn install
  1. Start the Metro bundler by running yarn start within your project folder:

yarn start
  1. The Catalog app is now ready to launch:

react-native run-ios --simulator="iPhone 8"

Next Steps

To learn more about React Native, make sure to check out the following blog posts:

Requirements

Creating a new Xamarin Solution

  1. Open Visual Studio and create a new solution by selecting File > New Solution... in the menu:

create-new-solution

  1. Choose the Blank App template for your solution:

app-template

  1. When prompted, choose your app name (“PSPDFKit-Demo”) and use the default options:

configure-ios-app

  1. Click on the Next button and select the location to save the solution:

create-app

  1. Click on the Create button to finish.

Install the PSPDFKit SDK via NuGet

  1. Make sure the PSPDFKit-Demo.sln is loaded in Visual Studio.

  2. Right-click on your solution in Visual Studio and select the “Manage NuGet Packages…” menu:

manage-nuget-packages

  1. In the Browse section of nuget.org, search for PSPDFKit.

  2. Select the PSPDFKit.Android package.

add-pspdfkit-nuget-packages

  1. Android also requires the following package. Search for it and tick the box to install:

  1. Tap on the Add Packages button to add the NuGet packages to your solution.

Displaying a PDF

  1. Open the AndroidManifest.xml file in your text editor.

open <project-path>/Properties/AndroidManifest.xml
  1. Edit the file to add the PdfActivity Activity to the <application> tag:

	<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
+		<activity android:name="com.pspdfkit.ui.PdfActivity"/>
		...
	</application>
  1. Add the PDF document you want to display to your application by dragging it into your solution’s assets. You can download this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import the following namespaces at the top of your MainActivity.cs:

using PSPDFKit.UI;  // To display the PDF.
using PSPDFKit.Configuration.Activity;  // For `PdfActivityConfiguration`.
using PSPDFKit.Configuration.Page;  // For activity configuration properties.
using Android.Content.Res;  // For Assets access.
using System.IO;  // Path creation.
using Java.IO;  // File creation.
  1. Load your PDF document and display it. This can be done in a button action handler or the MainActivity::OnCreate or similar. We also need some code to load the file from Assets into our device memory. Add the following functions that can be accessed from the MainActivity class:

// Read the contents of our asset
Java.IO.File GetFileFromAssets(string assetName)
{
	AssetManager assets = this.Assets;
	var bytes = default(byte[]);
	using (StreamReader reader = new StreamReader(assets.Open(assetName)))
	{
		using (var memstream = new MemoryStream())
		{
				reader.BaseStream.CopyTo(memstream);
				bytes = memstream.ToArray();
		}
	}

	var tempDir = System.IO.Path.GetTempPath();
	var filename = System.IO.Path.Combine(tempDir, assetName);
	Directory.CreateDirectory(tempDir);

	using (var fileOutputStream = new FileOutputStream(filename))
	{
		fileOutputStream.Write(bytes);
	}

	return new Java.IO.File(filename);
}

// Display the PDF we added to our assets.
void ShowPdfDocument()
{
	var jfile = GetFileFromAssets("Document.pdf");
	var docUri = Android.Net.Uri.FromFile(jfile);

	// The configuration object is optional and allows additional customization.
	var configuration = new PdfActivityConfiguration.Builder(this)
		.LayoutMode(PageLayoutMode.Single)
		.ScrollMode(PageScrollMode.Continuous)
		.ScrollDirection(PageScrollDirection.Vertical);

	// Show the PDF document.
	PdfActivity.ShowDocument(this, docUri, configuration.Build());
}
  1. ShowPdfDocument() can be called at the end of the OnCreate method in the generated MainActivity.cs code:

protected override void OnCreate(Bundle savedInstanceState)
{
	base.OnCreate(savedInstanceState);
	Xamarin.Essentials.Platform.Init(this, savedInstanceState);
	// Set our view from the "main" layout resource
	SetContentView(Resource.Layout.activity_main);
+	ShowPdfDocument();
}
  1. Build and run your application.

Next Steps

You can find more about Xamarin integration in our GitHub project, and our guides pages.

Requirements

Install the PSPDFKit SDK via NuGet

  1. Open your solution in Visual Studio:

open path/to/YourSolution.sln
  1. Right-click on your solution in Visual Studio and select the “Manage NuGet Packages…” menu:

manage-nuget-packages

  1. In the Browse section of nuget.org, search for PSPDFKit.

  2. Select the PSPDFKit.Android package.

add-pspdfkit-nuget-packages

  1. Android also requires the following package. Search for it and tick the box to install:

  1. Tap on the Add Packages button to add the NuGet packages to your solution.

Displaying a PDF

  1. Open the AndroidManifest.xml file in your text editor.

open <project-path>/Properties/AndroidManifest.xml
  1. Edit the file to add the PdfActivity Activity to the <application> tag:

	<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
+		<activity android:name="com.pspdfkit.ui.PdfActivity"/>
		...
	</application>
  1. Add the PDF document you want to display to your application by dragging it into your solution’s assets. You can download this QuickStart Guide PDF as an example.

drag-and-drop-document

  1. Import the following namespaces at the top of your MainActivity.cs:

using PSPDFKit.UI;  // To display the PDF.
using PSPDFKit.Configuration.Activity;  // For `PdfActivityConfiguration`.
using PSPDFKit.Configuration.Page;  // For activity configuration properties.
using Android.Content.Res;  // For Assets access.
using System.IO;  // Path creation.
using Java.IO;  // File creation.
  1. Load your PDF document and display it. This can be done in a button action handler or the MainActivity::OnCreate or similar. We also need some code to load the file from Assets into our device memory. Add the following functions that can be accessed from the MainActivity class:

// Read the contents of our asset
Java.IO.File GetFileFromAssets(string assetName)
{
	AssetManager assets = this.Assets;
	var bytes = default(byte[]);
	using (StreamReader reader = new StreamReader(assets.Open(assetName)))
	{
		using (var memstream = new MemoryStream())
		{
				reader.BaseStream.CopyTo(memstream);
				bytes = memstream.ToArray();
		}
	}

	var tempDir = System.IO.Path.GetTempPath();
	var filename = System.IO.Path.Combine(tempDir, assetName);
	Directory.CreateDirectory(tempDir);

	using (var fileOutputStream = new FileOutputStream(filename))
	{
		fileOutputStream.Write(bytes);
	}

	return new Java.IO.File(filename);
}

// Display the PDF we added to our assets.
void ShowPdfDocument()
{
	var jfile = GetFileFromAssets("Document.pdf");
	var docUri = Android.Net.Uri.FromFile(jfile);

	// The configuration object is optional and allows additional customization.
	var configuration = new PdfActivityConfiguration.Builder(this)
		.LayoutMode(PageLayoutMode.Single)
		.ScrollMode(PageScrollMode.Continuous)
		.ScrollDirection(PageScrollDirection.Vertical);

	// Show the PDF document.
	PdfActivity.ShowDocument(this, docUri, configuration.Build());
}
  1. Build and run your application.

Next Steps

You can find more about Xamarin integration in our GitHub project, and our guides pages.

Requirements

Cloning the Catalog Sample Project

  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 Xamarin Android repository:

git clone https://github.com/PSPDFKit/Xamarin-Android.git
  1. Change the current working directory to the root directory:

cd Xamarin-Android
  1. Download the PSPDFKit Android .aar file.

  2. Copy or move the file you’ve just downloaded to the Jars directory and rename it to pspdfkit-6.6.0.aar:

mv ~/Downloads/PSPDFKit-for-Android-AAR-6.6.0.aar PSPDFKit.Android/Jars/pspdfkit-6.6.0.aar
  1. Run the following command to download the remaining PSPDFKit dependencies:

./build.sh
  1. Open the PSPDFKit solution (PSPDFKit.Android.sln) in Visual Studio:

open PSPDFKit.Android.sln
  1. Build and run the PSPDFCatalog on an Android emulator.

catalog-emulator

Next Steps

You can find more about Xamarin integration in our GitHub project, and our guides pages.

Requirements

Creating a new Xamarin Solution

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

create-new-solution

  1. Choose the Single View App template for your solution:

app-template

  1. When prompted, choose your app name (“PSPDFKit-Demo”) and use the default options:

configure-ios-app

  1. Click on the Next button and select the location to save the solution:

create-app

  1. Click on the Create button to finish.

Install the PSPDFKit SDK via NuGet

  1. Make sure the PSPDFKit-Demo.sln is loaded in Visual Studio.

  2. Right-click on your solution in Visual Studio and select the “Manage NuGet Packages…” menu:

manage-nuget-packages

  1. In the Browse section of nuget.org, search for PSPDFKit.

  2. Select the following two iOS packages: PSPDFKit.iOS.Model and PSPDFKit.iOS.UI:

add-pspdfkit-nuget-packages

  1. Tap on the Add Packages button to add the NuGet packages to your solution.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your solution’s resources. 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 ViewController.cs:

using PSPDFKit.Model;
using PSPDFKit.UI;
  1. Load your PDF document and display the view controller, by implementing ViewDidAppear(Boolean) in the ViewController.cs file like so:

public override void ViewDidAppear(bool animated)
{
	base.ViewDidAppear(animated);

	// Update to use your document name.
	var document = new PSPDFDocument(NSUrl.FromFilename("Document.pdf"));

	// The configuration object is optional and allows additional customization.
	var configuration = PSPDFConfiguration.FromConfigurationBuilder((builder) => {
		builder.PageMode = PSPDFPageMode.Single;
		builder.PageTransition = PSPDFPageTransition.ScrollContinuous;
		builder.ScrollDirection = PSPDFScrollDirection.Vertical;
	});
	var pdfViewController = new PSPDFViewController(document, configuration);

	// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
	var navController = new UINavigationController(rootViewController: pdfViewController);
	_ = this.PresentViewControllerAsync(navController, animated: true);
}

Next Steps

You can find more about Xamarin integration in our GitHub project, and our guides pages.

Requirements

Install the PSPDFKit SDK via NuGet

  1. Open your solution in Visual Studio:

open path/to/YourSolution.sln
  1. Right-click on your solution in Visual Studio and select the “Manage NuGet Packages…” menu:

manage-nuget-packages

  1. In the Browse section of nuget.org, search for PSPDFKit.

  2. Select the following two iOS packages: PSPDFKit.iOS.Model and PSPDFKit.iOS.UI:

add-pspdfkit-nuget-packages

  1. Tap on the Add Packages button to add the NuGet packages to your solution.

Displaying a PDF

  1. Add the PDF document you want to display to your application by dragging it into your solution’s resources. 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 ViewController.cs:

using PSPDFKit.Model;
using PSPDFKit.UI;
  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.
var document = new PSPDFDocument(NSUrl.FromFilename("Document.pdf"));

// The configuration object is optional and allows additional customization.
var configuration = PSPDFConfiguration.FromConfigurationBuilder((builder) => {
	builder.PageMode = PSPDFPageMode.Single;
	builder.PageTransition = PSPDFPageTransition.ScrollContinuous;
	builder.ScrollDirection = PSPDFScrollDirection.Vertical;
});
var pdfViewController = new PSPDFViewController(document, configuration);

// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.
var navController = new UINavigationController(rootViewController: pdfViewController);
_ = this.PresentViewControllerAsync(navController, animated: true);
  1. Build and run your application.

Next Steps

You can find more about Xamarin integration in our GitHub project, and our guides pages.

Requirements

Cloning the Catalog Sample Project

  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 Xamarin iOS repository:

git clone https://github.com/PSPDFKit/Xamarin-iOS.git
  1. Change the current working directory to the root directory:

cd Xamarin-iOS
  1. Run the following command to download the PSPDFKit dependencies:

./build.sh --target DownloadDeps
  1. Wait a few moments for the dependencies to download.

  2. Open the PSPDFKit solution (PSPDFKit.sln) in Visual Studio:

open PSPDFKit.sln
  1. Build and run the PSPDFCatalog on an iOS Simulator.

catalog-simulator

Next Steps

You can find more about Xamarin integration in our GitHub project, and our guides pages.

Coming Soon

For now, please use our example Xamarin Forms projects for each platform:

Requirements

Creating a New Cordova Project

  1. In the terminal, 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 new Cordova project by running the following command:

cordova create PSPDFKit-Demo com.pspdfkit.demo PSPDFKit-Demo

Installing the PSPDFKit Cordova Dependency

  1. In the terminal, change the location of the current working directory inside the newly created project:

cd PSPDFKit-Demo
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
+   <preference name="AndroidXEnabled" value="true" />
    <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Add the PSPDFKit plugin:

cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Add the Android platform:

cordova platform add android

Displaying a PDF

  1. Add the PDF document you want to display in your project’s www directory. You can use this QuickStart Guide PDF as an example.

cp ~/Downloads/Document.pdf platforms/android/app/src/main/assets/Document.pdf
  1. Open the www/js/index.js file:

open www/js/index.js
  1. Modify the onDeviceReady function like so:

...
  onDeviceReady: function() {
    this.receivedEvent('deviceready');
+   const DOCUMENT = (window.cordova.platformId === "ios") ? "Document.pdf" : "file:///android_asset/Document.pdf";
+   PSPDFKit.present(DOCUMENT);
  },
...
  1. Start your emulator.

  2. The app is now ready to launch! Go back to the terminal and run:

cordova emulate android

Next Steps

To learn more about Cordova, make sure to check out the following:

Requirements

Installing the PSPDFKit Cordova Dependency

  1. Open the terminal and change the location of the current working directory inside your project:

cd path/to/YourProject
  1. Remove all the platforms from your project to properly propagate the changes in the config.xml file below throughout the project:

cordova platform remove android
cordova platform remove ios
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
+   <preference name="AndroidXEnabled" value="true" />
    <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Add the PSPDFKit plugin:

cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Add back all the platforms:

cordova platform add android
cordova platform add ios

Displaying a PDF

  1. Add the PDF document you want to display in your project’s www directory. You can use this QuickStart Guide PDF as an example.

cp ~/Downloads/Document.pdf platforms/android/app/src/main/assets/Document.pdf
  1. Present PSPDFKit from your codebase. You can do it from a button action, event handler, or similar:

const DOCUMENT = (window.cordova.platformId === "ios") ? "Document.pdf" : "file:///android_asset/Document.pdf";
PSPDFKit.present(DOCUMENT);
  1. Start your emulator.

  2. The app is now ready to launch! Go back to the terminal and run:

cordova emulate android

Next Steps

To learn more about Cordova, make sure to check out the following:

Requirements

Cloning the PSPDFKit-Demo Cordova Example Project

  1. Open the terminal and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-cordova.git
  1. Change the current working directory to the example project’s folder:

cd pspdfkit-cordova/examples/cordova/PSPDFKit-Demo
  1. Install the dependencies:

npm install
  1. Add the Android platform:

cordova platform add android
  1. Copy the PDF document from the www directory into your project’s assets directory:

cp www/Document.pdf platforms/android/app/src/main/assets/Document.pdf 
  1. Start your emulator.

  2. The app is now ready to launch:

cordova emulate android

Next Steps

To learn more about Cordova, make sure to check out the following:

Requirements

Creating a New Cordova Project

  1. In the terminal, 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 new Cordova project by running the following command:

cordova create PSPDFKit-Demo com.pspdfkit.demo PSPDFKit-Demo

Installing the PSPDFKit Cordova Dependency

  1. In the terminal, change the location of the current working directory inside the newly created project:

cd PSPDFKit-Demo
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
+   <preference name="AndroidXEnabled" value="true" />
    <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Add the PSPDFKit plugin:

cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Add the iOS platform:

cordova platform add ios

Displaying a PDF

  1. Add the PDF document you want to display in your project’s www directory. You can use this QuickStart Guide PDF as an example.

cp ~/Downloads/Document.pdf www/Document.pdf
  1. Open the www/js/index.js file:

open www/js/index.js
  1. Modify the onDeviceReady function like so:

...
  onDeviceReady: function() {
    this.receivedEvent('deviceready');
+   const DOCUMENT = (window.cordova.platformId === "ios") ? "Document.pdf" : "file:///android_asset/Document.pdf";
+   PSPDFKit.present(DOCUMENT);
  },
...
  1. The app is now ready to launch! Go back to the terminal and run:

cordova emulate ios

Next Steps

To learn more about Cordova, make sure to check out the following:

Requirements

Installing the PSPDFKit Cordova Dependency

  1. Open the terminal and change the location of the current working directory inside your project:

cd path/to/YourProject
  1. Remove all the platforms from your project to properly propagate the changes in the config.xml file below throughout the project:

cordova platform remove android
cordova platform remove ios
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
+   <preference name="AndroidXEnabled" value="true" />
    <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Add the PSPDFKit plugin:

cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Add back all the platforms:

cordova platform add android
cordova platform add ios

Displaying a PDF

  1. Add the PDF document you want to display in your project’s www directory. You can use this QuickStart Guide PDF as an example.

cp ~/Downloads/Document.pdf www/Document.pdf
  1. Present PSPDFKit from your codebase. You can do it from a button action, event handler, or similar:

const DOCUMENT = (window.cordova.platformId === "ios") ? "Document.pdf" : "file:///android_asset/Document.pdf";
PSPDFKit.present(DOCUMENT);
  1. The app is now ready to launch! Go back to the terminal and run:

cordova emulate ios

Next Steps

To learn more about Cordova, make sure to check out the following:

Requirements

Cloning the PSPDFKit-Demo Cordova Example Project

  1. Open the terminal and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-cordova.git
  1. Change the current working directory to the example project’s folder:

cd pspdfkit-cordova/examples/cordova/PSPDFKit-Demo
  1. Install the dependencies:

npm install
  1. Add the iOS platform:

cordova platform add ios
  1. The app is now ready to launch:

cordova emulate ios

Next Steps

To learn more about Cordova, make sure to check out the following:

Requirements

Creating a New Ionic Project

  1. In the terminal, 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 new Ionic project by running the following command:

ionic start PSPDFKit-Demo blank tabs --cordova --type=angular

Installing the PSPDFKit Ionic Dependency

  1. In the terminal, change the location of the current working directory inside the newly created project:

cd PSPDFKit-Demo
  1. Add the PSPDFKit plugin:

ionic cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
-    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
-       <application android:networkSecurityConfig="@xml/network_security_config" />
-    </edit-config>
+   <preference name="AndroidXEnabled" value="true" />
    ...
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <allow-navigation href="*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Declare PSPDFKit in the src/declarations.d.ts file:

echo "declare var PSPDFKit: any;" >> src/declarations.d.ts

Your src/declarations.d.ts file should look like this:

...
declare var PSPDFKit: any;
  1. Add the Android platform:

ionic cordova platform add android

Displaying a PDF

  1. Add the PDF document you want to display in your project’s www directory. You can use this QuickStart Guide PDF as an example:

cp ~/Downloads/Document.pdf platforms/android/app/src/main/assets/Document.pdf
  1. Open the src/app/app.component.ts file:

open src/app/app.component.ts
  1. Replace the entire contents of the app.component.ts file with the following code snippet:

import { Component } from "@angular/core";
import { Platform } from "@ionic/angular";

@Component({
  selector: "app-root",
  templateUrl: "app.component.html",
  styleUrls: ["app.component.scss"],
})
export class AppComponent {
  constructor(private platform: Platform) {
    this.platform.ready().then(() => {
      const DOCUMENT = this.platform.is("ios")
        ? "Document.pdf"
        : "file:///android_asset/Document.pdf";
      PSPDFKit.present(DOCUMENT);
    });
  }
}
  1. Start your emulator.

  2. The app is now ready to launch! Go back to the terminal and run:

ionic cordova emulate android

Next Steps

To learn more about Ionic, make sure to check out the following:

Requirements

Installing the PSPDFKit Ionic Dependency

  1. Open the terminal and change the location of the current working directory inside your project:

cd path/to/YourProject
  1. Remove all the platforms from your project to properly propagate the changes in the config.xml file below throughout the project:

ionic cordova platform remove android
ionic cordova platform remove ios
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
-    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
-       <application android:networkSecurityConfig="@xml/network_security_config" />
-    </edit-config>
+   <preference name="AndroidXEnabled" value="true" />
    ...
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <allow-navigation href="*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Add back all the platforms:

ionic cordova platform add android
ionic cordova platform add ios
  1. Add the PSPDFKit plugin:

ionic cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Declare PSPDFKit in the src/declarations.d.ts file:

echo "declare var PSPDFKit: any;" >> src/declarations.d.ts

Your src/declarations.d.ts file should look like this:

...
declare var PSPDFKit: any;

Displaying a PDF

  1. Add the PDF document you want to display in your project’s www directory. You can use this QuickStart Guide PDF as an example:

cp ~/Downloads/Document.pdf platforms/android/app/src/main/assets/Document.pdf
  1. Present PSPDFKit from your codebase. You can do this from a button action, event handler, or similar:

const DOCUMENT = this.platform.is("ios")
  ? "Document.pdf"
  : "file:///android_asset/Document.pdf";
PSPDFKit.present(DOCUMENT);
  1. Start your emulator.

  2. The app is now ready to launch! Go back to the terminal and run:

ionic cordova emulate android

Next Steps

To learn more about Ionic, make sure to check out the following:

Requirements

Cloning the PSPDFKit-Demo Ionic Example Project

  1. Open the terminal and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-cordova.git
  1. Change the current working directory to the example project’s folder:

cd pspdfkit-cordova/examples/ionic/PSPDFKit-Demo
  1. Install the dependencies:

npm install
  1. Add the Android platform:

ionic cordova platform add android
  1. Copy the PDF document from the resources directory into your project’s assets directory:

cp resources/Document.pdf platforms/android/app/src/main/assets/Document.pdf
  1. Start your emulator.

  2. The app is now ready to launch:

ionic cordova emulate android

Next Steps

To learn more about Ionic, make sure to check out the following:

Requirements

Creating a New Ionic Project

  1. In the terminal, 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 new Ionic project by running the following command:

ionic start PSPDFKit-Demo blank tabs --cordova --type=angular

Installing the PSPDFKit Ionic Dependency

  1. In the terminal, change the location of the current working directory inside the newly created project:

cd PSPDFKit-Demo
  1. Add the PSPDFKit plugin:

ionic cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
-    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
-       <application android:networkSecurityConfig="@xml/network_security_config" />
-    </edit-config>
+   <preference name="AndroidXEnabled" value="true" />
    ...
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <allow-navigation href="*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Declare PSPDFKit in the src/declarations.d.ts file:

echo "declare var PSPDFKit: any;" >> src/declarations.d.ts

Your src/declarations.d.ts file should look like this:

...
declare var PSPDFKit: any;
  1. Add the iOS platform:

ionic cordova platform add ios

Displaying a PDF

  1. Add the PDF document you want to display in your project’s platforms/ios/www directory. You can use this QuickStart Guide PDF as an example:

cp ~/Downloads/Document.pdf platforms/ios/platform_www/Document.pdf
  1. Open the src/app/app.component.ts file:

open src/app/app.component.ts
  1. Replace the entire contents of the app.component.ts file with the following code snippet:

import { Component } from "@angular/core";
import { Platform } from "@ionic/angular";

@Component({
  selector: "app-root",
  templateUrl: "app.component.html",
  styleUrls: ["app.component.scss"],
})
export class AppComponent {
  constructor(private platform: Platform) {
    this.platform.ready().then(() => {
      const DOCUMENT = this.platform.is("ios")
        ? "Document.pdf"
        : "file:///android_asset/Document.pdf";
      PSPDFKit.present(DOCUMENT);
    });
  }
}
  1. The app is now ready to launch! Go back to the terminal and run:

ionic cordova emulate ios

Next Steps

To learn more about Ionic, make sure to check out the following:

Requirements

Installing the PSPDFKit Ionic Dependency

  1. Open the terminal and change the location of the current working directory inside your project:

cd path/to/YourProject
  1. Remove all the platforms from your project to properly propagate the changes in the config.xml file below throughout the project:

ionic cordova platform remove android
ionic cordova platform remove ios
  1. Open config.xml in a text editor to enable AndroidX and to change the deployment target to iOS 12 or later:

open config.xml

Your config.xml file should look like this:

...
  <platform name="android">
-    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
-       <application android:networkSecurityConfig="@xml/network_security_config" />
-    </edit-config>
+   <preference name="AndroidXEnabled" value="true" />
    ...
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
+   <allow-navigation href="*" />
+   <preference name="deployment-target" value="12.0" />
    ...
  </platform>
...
  1. Add back all the platforms:

ionic cordova platform add android
ionic cordova platform add ios
  1. Add the PSPDFKit plugin:

ionic cordova plugin add https://github.com/PSPDFKit/PSPDFKit-Cordova.git
  1. Declare PSPDFKit in the src/declarations.d.ts file:

echo "declare var PSPDFKit: any;" >> src/declarations.d.ts

Your src/declarations.d.ts file should look like this:

...
declare var PSPDFKit: any;

Displaying a PDF

  1. Add the PDF document you want to display in your project’s platforms/ios/www directory. You can use this QuickStart Guide PDF as an example:

cp ~/Downloads/Document.pdf platforms/ios/platform_www/Document.pdf
  1. Present PSPDFKit from your codebase. You can do this from a button action, event handler, or similar:

const DOCUMENT = this.platform.is("ios")
  ? "Document.pdf"
  : "file:///android_asset/Document.pdf";
PSPDFKit.present(DOCUMENT);
  1. The app is now ready to launch! Go back to the terminal and run:

ionic cordova emulate ios

Next Steps

To learn more about Ionic, make sure to check out the following:

Requirements

Cloning the PSPDFKit-Demo Ionic Example Project

  1. Open the terminal and clone the GitHub repository:

git clone https://github.com/PSPDFKit/pspdfkit-cordova.git
  1. Change the current working directory to the example project’s folder:

cd pspdfkit-cordova/examples/ionic/PSPDFKit-Demo
  1. Install the dependencies:

npm install
  1. Add the iOS platform:

ionic cordova platform add ios
  1. Copy the PDF document from the resources directory into your project’s platform_www directory:

cp resources/Document.pdf platforms/ios/platform_www/
  1. The app is now ready to launch:

ionic cordova emulate ios

Next Steps

To learn more about Ionic, make sure to check out the following:

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.

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:

app-template

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

app-options

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

  2. Click on 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 Swift Packages tab:

xcode-project-swift-packages

  1. Copy the PSPDFKit Swift package repository URL into the search field and click Next:

https://github.com/PSPDFKit/PSPDFKit-SP

add-package-url

  1. Under Choose Package Options, select Branch: master, and click Next:

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 Finish. 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)
<span class="c1">// Update to use your document name.</span>
<span class="k">guard</span> <span class="k">let</span> <span class="nv">fileURL</span> <span class="o">=</span> <span class="kt">Bundle</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="nf">url</span><span class="p">(</span><span class="nv">forResource</span><span class="p">:</span> <span class="s">"Document"</span><span class="p">,</span> <span class="nv">withExtension</span><span class="p">:</span> <span class="s">"pdf"</span><span class="p">)</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
<span class="k">let</span> <span class="nv">document</span> <span class="o">=</span> <span class="kt">Document</span><span class="p">(</span><span class="nv">url</span><span class="p">:</span> <span class="n">fileURL</span><span class="p">)</span>

<span class="c1">// The configuration closure is optional and allows additional customization.</span>
<span class="k">let</span> <span class="nv">pdfController</span> <span class="o">=</span> <span class="kt">PDFViewController</span><span class="p">(</span><span class="nv">document</span><span class="p">:</span> <span class="n">document</span><span class="p">)</span> <span class="p">{</span>
		<span class="nv">$0</span><span class="o">.</span><span class="n">isPageLabelEnabled</span> <span class="o">=</span> <span class="kc">false</span>
<span class="p">}</span>

<span class="c1">// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.</span>
<span class="nf">present</span><span class="p">(</span><span class="kt">UINavigationController</span><span class="p">(</span><span class="nv">rootViewController</span><span class="p">:</span> <span class="n">pdfController</span><span class="p">),</span> <span class="nv">animated</span><span class="p">:</span> <span class="kc">true</span><span class="p">)</span>

}

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

<span class="c1">// Update to use your document name.</span>
<span class="n">NSURL</span> <span class="o">*</span><span class="n">documentURL</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSBundle</span><span class="p">.</span><span class="n">mainBundle</span> <span class="nf">URLForResource</span><span class="p">:</span><span class="s">@"Document"</span> <span class="nf">withExtension</span><span class="p">:</span><span class="s">@"pdf"</span><span class="p">];</span>
<span class="n">PSPDFDocument</span> <span class="o">*</span><span class="n">document</span> <span class="o">=</span> <span class="p">[[</span><span class="n">PSPDFDocument</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithURL</span><span class="p">:</span><span class="n">documentURL</span><span class="p">];</span>

<span class="c1">// The configuration object is optional and allows additional customization.</span>
<span class="n">PSPDFViewController</span> <span class="o">*</span><span class="n">pdfController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">PSPDFViewController</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithDocument</span><span class="p">:</span><span class="n">document</span> <span class="nf">configuration</span><span class="p">:[</span><span class="n">PSPDFConfiguration</span> <span class="nf">configurationWithBuilder</span><span class="p">:</span><span class="o">^</span><span class="p">(</span><span class="n">PSPDFConfigurationBuilder</span> <span class="o">*</span><span class="n">builder</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">builder</span><span class="p">.</span><span class="n">pageLabelEnabled</span> <span class="o">=</span> <span class="nb">NO</span><span class="p">;</span>
<span class="p">}]];</span>

<span class="c1">// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.</span>
<span class="n">UINavigationController</span> <span class="o">*</span><span class="n">navController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">UINavigationController</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithRootViewController</span><span class="p">:</span><span class="n">pdfController</span><span class="p">];</span>
<span class="p">[</span><span class="n">self</span> <span class="nf">presentViewController</span><span class="p">:</span><span class="n">navController</span> <span class="nf">animated</span><span class="p">:</span><span class="nb">YES</span> <span class="n">completion</span><span class="o">:</span><span class="nb">NULL</span><span class="p">];</span>

}

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.

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:

app-template

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

app-options

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

  2. Click on 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 change the directory to the location of 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)
<span class="c1">// Update to use your document name.</span>
<span class="k">guard</span> <span class="k">let</span> <span class="nv">fileURL</span> <span class="o">=</span> <span class="kt">Bundle</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="nf">url</span><span class="p">(</span><span class="nv">forResource</span><span class="p">:</span> <span class="s">"Document"</span><span class="p">,</span> <span class="nv">withExtension</span><span class="p">:</span> <span class="s">"pdf"</span><span class="p">)</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
<span class="k">let</span> <span class="nv">document</span> <span class="o">=</span> <span class="kt">Document</span><span class="p">(</span><span class="nv">url</span><span class="p">:</span> <span class="n">fileURL</span><span class="p">)</span>

<span class="c1">// The configuration closure is optional and allows additional customization.</span>
<span class="k">let</span> <span class="nv">pdfController</span> <span class="o">=</span> <span class="kt">PDFViewController</span><span class="p">(</span><span class="nv">document</span><span class="p">:</span> <span class="n">document</span><span class="p">)</span> <span class="p">{</span>
		<span class="nv">$0</span><span class="o">.</span><span class="n">isPageLabelEnabled</span> <span class="o">=</span> <span class="kc">false</span>
<span class="p">}</span>

<span class="c1">// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.</span>
<span class="nf">present</span><span class="p">(</span><span class="kt">UINavigationController</span><span class="p">(</span><span class="nv">rootViewController</span><span class="p">:</span> <span class="n">pdfController</span><span class="p">),</span> <span class="nv">animated</span><span class="p">:</span> <span class="kc">true</span><span class="p">)</span>

}

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

<span class="c1">// Update to use your document name.</span>
<span class="n">NSURL</span> <span class="o">*</span><span class="n">documentURL</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSBundle</span><span class="p">.</span><span class="n">mainBundle</span> <span class="nf">URLForResource</span><span class="p">:</span><span class="s">@"Document"</span> <span class="nf">withExtension</span><span class="p">:</span><span class="s">@"pdf"</span><span class="p">];</span>
<span class="n">PSPDFDocument</span> <span class="o">*</span><span class="n">document</span> <span class="o">=</span> <span class="p">[[</span><span class="n">PSPDFDocument</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithURL</span><span class="p">:</span><span class="n">documentURL</span><span class="p">];</span>

<span class="c1">// The configuration object is optional and allows additional customization.</span>
<span class="n">PSPDFViewController</span> <span class="o">*</span><span class="n">pdfController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">PSPDFViewController</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithDocument</span><span class="p">:</span><span class="n">document</span> <span class="nf">configuration</span><span class="p">:[</span><span class="n">PSPDFConfiguration</span> <span class="nf">configurationWithBuilder</span><span class="p">:</span><span class="o">^</span><span class="p">(</span><span class="n">PSPDFConfigurationBuilder</span> <span class="o">*</span><span class="n">builder</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">builder</span><span class="p">.</span><span class="n">pageLabelEnabled</span> <span class="o">=</span> <span class="nb">NO</span><span class="p">;</span>
<span class="p">}]];</span>

<span class="c1">// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.</span>
<span class="n">UINavigationController</span> <span class="o">*</span><span class="n">navController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">UINavigationController</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithRootViewController</span><span class="p">:</span><span class="n">pdfController</span><span class="p">];</span>
<span class="p">[</span><span class="n">self</span> <span class="nf">presentViewController</span><span class="p">:</span><span class="n">navController</span> <span class="nf">animated</span><span class="p">:</span><span class="nb">YES</span> <span class="n">completion</span><span class="o">:</span><span class="nb">NULL</span><span class="p">];</span>

}

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.

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:

app-template

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

app-options

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

  2. Click on 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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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)
<span class="c1">// Update to use your document name.</span>
<span class="k">guard</span> <span class="k">let</span> <span class="nv">fileURL</span> <span class="o">=</span> <span class="kt">Bundle</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="nf">url</span><span class="p">(</span><span class="nv">forResource</span><span class="p">:</span> <span class="s">"Document"</span><span class="p">,</span> <span class="nv">withExtension</span><span class="p">:</span> <span class="s">"pdf"</span><span class="p">)</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
<span class="k">let</span> <span class="nv">document</span> <span class="o">=</span> <span class="kt">Document</span><span class="p">(</span><span class="nv">url</span><span class="p">:</span> <span class="n">fileURL</span><span class="p">)</span>

<span class="c1">// The configuration closure is optional and allows additional customization.</span>
<span class="k">let</span> <span class="nv">pdfController</span> <span class="o">=</span> <span class="kt">PDFViewController</span><span class="p">(</span><span class="nv">document</span><span class="p">:</span> <span class="n">document</span><span class="p">)</span> <span class="p">{</span>
		<span class="nv">$0</span><span class="o">.</span><span class="n">isPageLabelEnabled</span> <span class="o">=</span> <span class="kc">false</span>
<span class="p">}</span>

<span class="c1">// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.</span>
<span class="nf">present</span><span class="p">(</span><span class="kt">UINavigationController</span><span class="p">(</span><span class="nv">rootViewController</span><span class="p">:</span> <span class="n">pdfController</span><span class="p">),</span> <span class="nv">animated</span><span class="p">:</span> <span class="kc">true</span><span class="p">)</span>

}

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

<span class="c1">// Update to use your document name.</span>
<span class="n">NSURL</span> <span class="o">*</span><span class="n">documentURL</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSBundle</span><span class="p">.</span><span class="n">mainBundle</span> <span class="nf">URLForResource</span><span class="p">:</span><span class="s">@"Document"</span> <span class="nf">withExtension</span><span class="p">:</span><span class="s">@"pdf"</span><span class="p">];</span>
<span class="n">PSPDFDocument</span> <span class="o">*</span><span class="n">document</span> <span class="o">=</span> <span class="p">[[</span><span class="n">PSPDFDocument</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithURL</span><span class="p">:</span><span class="n">documentURL</span><span class="p">];</span>

<span class="c1">// The configuration object is optional and allows additional customization.</span>
<span class="n">PSPDFViewController</span> <span class="o">*</span><span class="n">pdfController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">PSPDFViewController</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithDocument</span><span class="p">:</span><span class="n">document</span> <span class="nf">configuration</span><span class="p">:[</span><span class="n">PSPDFConfiguration</span> <span class="nf">configurationWithBuilder</span><span class="p">:</span><span class="o">^</span><span class="p">(</span><span class="n">PSPDFConfigurationBuilder</span> <span class="o">*</span><span class="n">builder</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">builder</span><span class="p">.</span><span class="n">pageLabelEnabled</span> <span class="o">=</span> <span class="nb">NO</span><span class="p">;</span>
<span class="p">}]];</span>

<span class="c1">// Present the PDF view controller within a `UINavigationController` to show built-in toolbar buttons.</span>
<span class="n">UINavigationController</span> <span class="o">*</span><span class="n">navController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">UINavigationController</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithRootViewController</span><span class="p">:</span><span class="n">pdfController</span><span class="p">];</span>
<span class="p">[</span><span class="n">self</span> <span class="nf">presentViewController</span><span class="p">:</span><span class="n">navController</span> <span class="nf">animated</span><span class="p">:</span><span class="nb">YES</span> <span class="n">completion</span><span class="o">:</span><span class="nb">NULL</span><span class="p">];</span>

}

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.

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 Swift Packages tab:

xcode-project-swift-packages

  1. Copy the PSPDFKit Swift package repository URL into the search field and click Next:

https://github.com/PSPDFKit/PSPDFKit-SP

add-package-url

  1. Under Choose Package Options, select Branch: master, and click Next:

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 Finish. 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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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.

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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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.

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

  1. If your application is targeting iOS versions prior to iOS 12.2 and your application does not already contain any Swift code, then you need to make sure Xcode bundles Swift standard libraries with your application distribution. To do so, open your target Build Settings and enable Always Embed Swift Standard Libraries:

always-embed-swift-standard-libraries

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.
guard let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf") else { return }
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. Mac Catalyst apps need to be code signed, even during development. So please change the Catalog’s Bundle Identifier and setup code signing using your Team identifier:

code-signing-catalog-catalyst

  1. Build and run the Catalog on your Mac.

catalog-catalyst

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

Creating a New Project

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

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

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

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

Adding PSPDFKit

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

yarn add pspdfkit
npm install --save pspdfkit

Displaying a PDF

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

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

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	</head>
	<body>
		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

		<script>
			// Invoke the JavaScript for the renderer process.
			require("./renderer.js");
		</script>
	</body>
</html>
  1. Load PSPDFKit in the JavaScript file of your renderer process:

const PSPDFKit = require("pspdfkit");

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

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

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

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

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

	mainWindow.loadFile("index.html");

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

app.whenReady().then(createWindow)

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

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

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

yarn start
npm start

Next Steps

Integrate into an Electron Project

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

Adding PSPDFKit

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

yarn add pspdfkit
npm install --save pspdfkit

Displaying a PDF

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

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

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	</head>
	<body>
		<!-- Element where PSPDFKit will be mounted. -->
		<div id="pspdfkit" style="width: 100%; height: 100vh;"></div>

		<script>
			// Invoke the JavaScript for the renderer process.
			require("./renderer.js");
		</script>
	</body>
</html>
  1. Load PSPDFKit in the JavaScript file of your renderer process:

const PSPDFKit = require("pspdfkit");

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

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

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

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

yarn start
npm start

Next Steps

Requirements

  • Windows 10

  • Visual Studio 2017 or above

Creating a New Project

  1. Open Visual Studio. Go to File > New > Project… and select Blank App (Universal Windows) from the template selection page.

  1. Configure your project by setting the name and location:

  1. Specify the minimum and target versions. We’re using the defaults:

Adding PSPDFKit to Your Project

Choose between integrating NuGet or a VSIX extension. We recommend using the NuGet package, as this doesn’t require a systemwide install of the extension, makes version tracking easier, and simplifies server-based build processes.

  1. Open your app’s solution, and in the Solution Explorer, right-click on References and click on the menu item Manage NuGet Packages…. This will open the NuGet Package Manager for your solution.

  1. Search for pspdfkituwp, and you’ll find the package on nuget.org.

  2. On the right side, in the panel describing the package, click on the Install button to install the package.

  1. Once that’s complete, you’ll see a reference to the package in the Solution Explorer under References.

Rather than targeting a package held at nuget.org, you may set up a configuration to point to a local package. This can be useful for situations in which, for example, your build machines don’t have access to the internet.

  1. Download the latest SDK ZIP file and unpack it wherever appropriate.

  2. Create or edit a nuget.config file in the same directory as your solution file (e.g. PSPDFKitDemo.sln).

The contents of the file should contain an XML element, packageSources — which describes where to find NuGet packages — as a child of a root node named configuration. If the file already exists, add the extra packageSources entry shown below. If the file is blank, copy and paste the entirety of the following contents:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<packageSources>
		<add key="PSPDFKitSource" value="path\to\directoryContainingNupkg" />
	</packageSources>
</configuration>

Edit the value of the contents to correctly refer to the location of the directory containing the PSPDFKitUWP.*.*.*.nupkg package — for example, C:\Users\me\nugetPackages\. Now save the file, and close and reopen your solution for Visual Studio to force a read of the NuGet configuration.

  1. Open your app’s solution, and in the Solution Explorer, right-click on References and click on the menu item Manage NuGet Packages…. This will open the NuGet Package Manager for your solution.

  1. On the right-hand side of the manager in the Package source dropdown window, choose the entry PSPDFKitSource (or whatever you decided to name it). You should then see the entry for PSPDFKitUWP by PSPDFKit GmbH.

  1. On the right side, in the panel describing the package, click on the Install button to install the package.

  1. Once that’s complete, you’ll see a reference to the package in the Solution Explorer under References.

We provide PSPDFKit for Windows as a VSIX in the SDK ZIP file. You can install this systemwide and then add a reference to your project.

Please be aware that with VSIX, you can only have one version of the SDK installed at a time.

  1. Make sure Visual Studio is closed.

  2. Double-click the installer, PSPDFKit for Windows.vsix. The installer will guide you through the installation process.

  3. Open Visual Studio. In the Solution Explorer, right-click References for your project and then select Add Reference.

  4. Navigate to Universal Windows > Extensions, and then select both PSPDFKit for UWP and Visual C++ 2015 Runtime for Universal Windows Platform Apps.

  5. Click on OK and you should see the following in your References:

Displaying a PDF

  1. Open MainPage.xaml and paste the following XML as a child of the <Grid> element:

<Grid.RowDefinitions>
	<RowDefinition Height="*"/>
	<RowDefinition Height="52"/>
</Grid.RowDefinitions>
<ui:PdfView Grid.Row="0" Name="PdfView" License="{StaticResource PSPDFKitLicense}" />
<Button IsEnabled="False" Content="Open PDF" HorizontalAlignment="Left" Margin="10" Grid.Row="1" Name="Button_OpenPDF" Click="Button_OpenPDF_Click"/>
  1. You’ll see a green line under ui:PdfView. If you hover over it, you’ll be given the option for potential fixes. Apply the suggested fix, which will add the following namespace to <Page>:

<Page
	xmlns:ui="using:PSPDFKit.UI"
/>
  1. Open the MainPage.xaml.cs file, add a delegate handler to PdfView.InitializationCompletedHandler in the constructor, and add the button’s click handler function:

using PSPDFKit.Document;
using PSPDFKit.Pdf;
using PSPDFKit.UI;

public MainPage()
{
	InitializeComponent();

	// This handler is invoked once the `PdfView` has been initialized, and then the `PdfView.Controller` can be used.
	PdfView.InitializationCompletedHandler += delegate(PdfView sender, Document args)
	{
		// Now that the `PdfView` is ready, enable the button for opening a file.
		Button_OpenPDF.IsEnabled = true;
	};
}

private async void Button_OpenPDF_Click(object sender, RoutedEventArgs e)
{
	var picker = new Windows.Storage.Pickers.FileOpenPicker();
	picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
	picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
	picker.FileTypeFilter.Add(".pdf");

	var file = await picker.PickSingleFileAsync();
	if (file != null)
	{
		var document = DocumentSource.CreateFromStorageFile(file);
		await PdfView.Controller.ShowDocumentAsync(document);
	}
}

Note that you must wait for initialization of the PdfView to be complete before using PdfView.Controller.

  1. In the Build toolbar, choose Debug and x86 or x64 — whichever you prefer.

  2. Then, in the menu, select Build > Build Solution.

  3. Start the application, and you should be able to open a PDF by clicking the Open button.

Next Steps

React Native for Windows UWP Support

PSPDFKit for Windows UWP comes with optional support for React Native. This makes it easy to add PDF support to your React Native Windows app. See our open source GitHub repository for details on how to integrate.

Support for .NET, WPF (Windows Presentation Foundation), and Xamarin

There’s ongoing work by Microsoft to allow integrating UWP controls in WPF apps. We also have a Xamarin wrapper for UWP, and you can check out our Xamarin guide for more information.

Support for Windows 7/Windows 8.1

For companies that still need to support legacy Windows, we offer CEF as a replacement. This has a slightly higher performance impact (around 20–30 percent slower), but otherwise, it’s functionally equivalent; it just needs more direct interaction with JavaScript.

Mainstream support for Windows 7 ended on 13 January 2015, and mainstream support for Windows 8.1 ended on 9 January 2018. However, Microsoft will still offer paid extended support until January 2020/2023, respectively.

Requirements

  • Windows 10

  • Visual Studio 2017 or above

  • A UWP-based application

Adding PSPDFKit to Your Project

Choose between integrating NuGet or a VSIX extension. We recommend using the NuGet package, as this doesn’t require a systemwide install of the extension, makes version tracking easier, and simplifies server-based build processes.

  1. Open your app’s solution, and in the Solution Explorer, right-click on References and click on the menu item Manage NuGet Packages…. This will open the NuGet Package Manager for your solution.

  1. Search for pspdfkituwp, and you’ll find the package on nuget.org.

  2. On the right side, in the panel describing the package, click on the Install button to install the package.

  1. Once that’s complete, you’ll see a reference to the package in the Solution Explorer under References.

Rather than targeting a package held at nuget.org, you may set up a configuration to point to a local package. This can be useful for situations in which, for example, your build machines don’t have access to the internet.

  1. Download the latest SDK ZIP file and unpack it wherever appropriate.

  2. Create or edit a nuget.config file in the same directory as your solution file (e.g. PSPDFKitDemo.sln).

The contents of the file should contain an XML element, packageSources — which describes where to find NuGet packages — as a child of a root node named configuration. If the file already exists, add the extra packageSources entry shown below. If the file is blank, copy and paste the entirety of the following contents:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<packageSources>
		<add key="PSPDFKitSource" value="path\to\directoryContainingNupkg" />
	</packageSources>
</configuration>

Edit the value of the contents to correctly refer to the location of the directory containing the PSPDFKitUWP.*.*.*.nupkg package — for example, C:\Users\me\nugetPackages\. Now save the file, and close and reopen your solution for Visual Studio to force a read of the NuGet configuration.

  1. Open your app’s solution, and in the Solution Explorer, right-click on References and click on the menu item Manage NuGet Packages…. This will open the NuGet Package Manager for your solution.

  1. On the right-hand side of the manager in the Package source dropdown window, choose the entry PSPDFKitSource (or whatever you decided to name it). You should then see the entry for PSPDFKitUWP by PSPDFKit GmbH.

  1. On the right side, in the panel describing the package, click on the Install button to install the package.

  1. Once that’s complete, you’ll see a reference to the package in the Solution Explorer under References.

We provide PSPDFKit for Windows as a VSIX in the SDK ZIP file. You can install this systemwide and then add a reference to your project.

Please be aware that with VSIX, you can only have one version of the SDK installed at a time.

  1. Make sure Visual Studio is closed.

  2. Double-click the installer, PSPDFKit for Windows.vsix. The installer will guide you through the installation process.

  3. Open Visual Studio. In the Solution Explorer, right-click References for your project and then select Add Reference.

  4. Navigate to Universal Windows > Extensions, and then select both PSPDFKit for UWP and Visual C++ 2015 Runtime for Universal Windows Platform Apps.

  5. Click on OK and you should see the following in your References:

Displaying a PDF

  1. Open MainPage.xaml and paste the following XML as a child of the <Grid> element:

<Grid.RowDefinitions>
	<RowDefinition Height="*"/>
	<RowDefinition Height="52"/>
</Grid.RowDefinitions>
<ui:PdfView Grid.Row="0" Name="PdfView" License="{StaticResource PSPDFKitLicense}" />
<Button IsEnabled="False" Content="Open PDF" HorizontalAlignment="Left" Margin="10" Grid.Row="1" Name="Button_OpenPDF" Click="Button_OpenPDF_Click"/>
  1. You’ll see a green line under ui:PdfView. If you hover over it, you’ll be given the option for potential fixes. Apply the suggested fix, which will add the following namespace to <Page>:

<Page
	xmlns:ui="using:PSPDFKit.UI"
/>
  1. Open the MainPage.xaml.cs file, add a delegate handler to PdfView.InitializationCompletedHandler in the constructor, and add the button’s click handler function:

using PSPDFKit.Document;
using PSPDFKit.Pdf;
using PSPDFKit.UI;

public MainPage()
{
	InitializeComponent();

	// This handler is invoked once the `PdfView` has been initialized, and then the `PdfView.Controller` can be used.
	PdfView.InitializationCompletedHandler += delegate(PdfView sender, Document args)
	{
		// Now that the `PdfView` is ready, enable the button for opening a file.
		Button_OpenPDF.IsEnabled = true;
	};
}

private async void Button_OpenPDF_Click(object sender, RoutedEventArgs e)
{
	var picker = new Windows.Storage.Pickers.FileOpenPicker();
	picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
	picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
	picker.FileTypeFilter.Add(".pdf");

	var file = await picker.PickSingleFileAsync();
	if (file != null)
	{
		var document = DocumentSource.CreateFromStorageFile(file);
		await PdfView.Controller.ShowDocumentAsync(document);
	}
}

Note that you must wait for initialization of the PdfView to be complete before using PdfView.Controller.

  1. In the Build toolbar, choose Debug and x86 or x64 — whichever you prefer.

  2. Then, in the menu, select Build > Build Solution.

  3. Start the application, and you should be able to open a PDF by clicking the Open button.

Next Steps

React Native for Windows UWP Support

PSPDFKit for Windows UWP comes with optional support for React Native. This makes it easy to add PDF support to your React Native Windows app. See our open source GitHub repository for details on how to integrate.

Support for .NET, WPF (Windows Presentation Foundation), and Xamarin

There’s ongoing work by Microsoft to allow integrating UWP controls in WPF apps. We also have a Xamarin wrapper for UWP, and you can check out our Xamarin guide for more information.

Support for Windows 7/Windows 8.1

For companies that still need to support legacy Windows, we offer CEF as a replacement. This has a slightly higher performance impact (around 20–30 percent slower), but otherwise, it’s functionally equivalent; it just needs more direct interaction with JavaScript.

Mainstream support for Windows 7 ended on 13 January 2015, and mainstream support for Windows 8.1 ended on 9 January 2018. However, Microsoft will still offer paid extended support until January 2020/2023, respectively.

Catalog App

The SDK comes with an example application called the Catalog app. It contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file or on the Microsoft Store. The latest SDK ZIP file can be downloaded here.

Building the Catalog App

To build the Catalog app, open the solution in Visual Studio, choose the solution platform x86 or x64, build, and run. Note that building and running for ARM requires an ARM-based device.

Next Steps

React Native for Windows UWP Support

PSPDFKit for Windows UWP comes with optional support for React Native. This makes it easy to add PDF support to your React Native Windows app. See our open source GitHub repository for details on how to integrate.

Support for .NET, WPF (Windows Presentation Foundation), and Xamarin

There’s ongoing work by Microsoft to allow integrating UWP controls in WPF apps. We also have a Xamarin wrapper for UWP, and you can check out our Xamarin guide for more information.

Support for Windows 7/Windows 8.1

For companies that still need to support legacy Windows, we offer CEF as a replacement. This has a slightly higher performance impact (around 20–30 percent slower), but otherwise, it’s functionally equivalent; it just needs more direct interaction with JavaScript.

Mainstream support for Windows 7 ended on 13 January 2015, and mainstream support for Windows 8.1 ended on 9 January 2018. However, Microsoft will still offer paid extended support until January 2020/2023, respectively.

Requirements

PSPDFKit Server runs on a variety of platforms. The following operating systems are supported:

  • macOS Mojave, Catalina, or Big Sur (Apple’s M1-based Macs are not yet supported)

  • Windows 10 Pro, Home, Education, or Enterprise 64-bit

  • Ubuntu, Fedora, Debian, or CentOS. Ubuntu and Debian derivatives such as Kubuntu or Xubuntu are supported as well. Currently only 64-bit Intel (x86_64) processors are supported.

Regardless of your operating system, you’ll need at least 4 GB of RAM.

Installing Docker

PSPDFKit Server is distributed as a Docker container. To run it on your computer, you need to install a Docker runtime distribution for your operating system.

Install and start Docker Desktop for Mac. Please refer to the Docker website for instructions.

Install and start Docker Desktop for Windows. Please refer to the Docker website for instructions.

Install and start Docker Engine. Please refer to the Docker website for instructions on how to install it for your Linux distribution.

After you install Docker, use these instructions to install Docker Compose.

Setting Up PSPDFKit Server

Copy the code snippet below and save it anywhere on your computer in a file called docker-compose.yml:

version: "3.8"

services:
  pspdfkit:
    image: pspdfkit/pspdfkit:latest
    environment:
      PGUSER: pspdfkit
      PGPASSWORD: password
      PGDATABASE: pspdfkit
      PGHOST: db
      PGPORT: 5432
      ACTIVATION_KEY: <YOUR_ACTIVATION_KEY_GOES_HERE>
      API_AUTH_TOKEN: secret
      SECRET_KEY_BASE: secret-key-base
      JWT_PUBLIC_KEY: |
        -----BEGIN PUBLIC KEY-----
        MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94t
        OxsSxIQZMOc1GY8ubuqu2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQ==
        -----END PUBLIC KEY-----
      JWT_ALGORITHM: RS256
      DASHBOARD_USERNAME: dashboard
      DASHBOARD_PASSWORD: secret
    ports:
      - 5000:5000
    depends_on:
      - db
  db:
    image: postgres:13.1
    environment:
      POSTGRES_USER: pspdfkit
      POSTGRES_PASSWORD: password
      POSTGRES_DB: pspdfkit
      POSTGRES_INITDB_ARGS: --data-checksums
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Now open that file in your code editor and replace the <YOUR_ACTIVATION_KEY_GOES_HERE> placeholder on line 12 with your trial activation key.

Starting PSPDFKit Server

Now open a terminal emulator.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use Terminal.app or iTerm2.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use PowerShell.

Use the terminal emulator integrated with your code editor or IDE, or one bundled with your desktop environment.

Go to the directory where you saved the docker-compose.yml file:

cd <path-to-directory-with-docker-compose-yml>

Run the following:

docker-compose up

This command might take a while to run, depending on your internet connection speed. Wait until you see the following message in the terminal:

pspdfkit_1  | Access the web dashboard at http://localhost:5000/dashboard

The PSPDFKit Server is now up and running!

Uploading a Document to PSPDFKit Server

With PSPDFKit Server running, visit http://localhost:5000/dashboard and authenticate using “dashboard” for the username and “secret” for the password. Choose Add Document and upload the document you want to work with.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

Once the document is uploaded, visit http://localhost:5000/dashboard/documents to see the list of available documents. Each document is identified by an ID. Take note of the ID of the document you just uploaded, as you’ll need it shortly.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

The ID should look similar to 7KPS8X13JRB2G841X4V7EQ3T2J.

Installing Node.js

If you haven’t installed Node.js, head to the official guides and follow the instructions. By the end of the installation process, you should be able to run the following command:

node --version

The output should be something like v14. You can ignore any subsequent number.

Generating the Application

You’ll use Express, one of the most common Node.js web frameworks. To create a new Express application, you can use the official generator.

Run:

npx express-generator pspdfkit_example --view=ejs

This command will generate a project structure and instruct you on the steps to follow to install dependencies and start the project.

Once you’ve followed all the steps, you should be able to visit http://localhost:3000 to confirm the application is working as expected.

Adding a Page to View the Document

You need to create a page that will show a document stored inside PSPDFKit Server.

You’ll want this page to be available at http://localhost:3000/documents/:id, where the document ID is the ID automatically assigned by PSPDFKit Server when uploading a document.

To achieve this, create a new route to display a document and mount it in the application.

  1. Create the documents route:

./routes/documents.js
var express = require("express");
var router = express.Router();

router.get("/:documentId", function (req, res, next) {
  res.render("documents/show", { documentId: req.params.documentId });
});

module.exports = router;

Inside the route, retrieve the ID captured by the routing logic and assign it to a documentId variable you can refer to in the view.

  1. Create a corresponding view with some minimal HTML that prints the document ID:

./views/documents/show.ejs
<h1>Show document <%= documentId %></h1>

  1. Mount the new route in the application:

./app.js
 var indexRouter = require('./routes/index');
 var usersRouter = require('./routes/users');
+var documentsRouter = require("./routes/documents");
 // ...
 // rest of the file
 // ...
 app.use('/', indexRouter);
 app.use('/users', usersRouter);
+app.use("/documents", documentsRouter);

Stop and restart the Express server.

You can now visit http://localhost:3000/documents/:id, replacing :id with the ID of the document you uploaded to the PSPDFKit Server dashboard.

The page should contain the text Show document, followed by your document ID.

Creating a JSON Web Token (JWT)

PSPDFKit requires the use of JWTs to authenticate and authorize a viewer session against PSPDFKit Server.

To create JWTs, install the jsonwebtoken dependency:

npm install --save jsonwebtoken

Stop and restart the Express server.

Working with JWTs requires a private and public key pair. The private key is used by the Express application, while the public key is used by PSPDFKit Server.

The public key has already been configured in the PSPDFKit Server docker-compose.yml file via the JWT_PUBLIC_KEY environment variable.

To configure the private key, create a config/pspdfkit/jwt.pem file with the following contents:

./config/pspdfkit/jwt.pem
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94tOxsSxIQZMOc1GY8ubuqu
2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQJAHfi9lEtysRkjNQSBxqzK
hm7JDvLxU1AsQaX1OGctF/fLXzkWiMLsBZ3yLHdPSvl/izbKyGrADv7wrQJrPPhg
gQIhAPQrw5Uh7pQ4RMvkDJff7aHWwWTUuqgsiS/r1/7KHl8VAiEAwFxH2YA3MR/5
Rl5/VJJp6Cv/2IGSgQVCSDZyL5rcBFECIQDc3eGTOxhmtud0T5scnpCD/pD9tngJ
vA90a6/8Z7RFaQIhAIBOjVZUoXvQ+fKoIYKFzsKgZp1BgDkzCs0kE/IQ92ShAiEA
7f4XIbGgIFaSJRpBfa168aeP162EV5oOW+Gyv2IIyK8=
-----END RSA PRIVATE KEY-----

Update ./routes/documents.js to read the private key so that it can be used to sign JWTs and pass them to the view.

In the claims, you pass the document ID, the set of permissions you want to have, and an expiry of one hour:

./routes/documents.js
 var express = require("express");
 var router = express.Router();
+var fs = require("fs");
+var path = require("path");
+var jwt = require("jsonwebtoken");
+var jwtKey = fs.readFileSync(
+  path.resolve(__dirname, "../config/pspdfkit/jwt.pem")
+);

 router.get("/:documentId", function (req, res, next) {
+  var jwt = prepareJwt(req.params.documentId);
-  res.render("documents/show", { documentId: req.params.documentId });
+  res.render("documents/show", { documentId: req.params.documentId, jwt: jwt });
 });
+
+var prepareJwt = function (documentId) {
+  var claims = {
+    document_id: documentId,
+    permissions: ["read-document", "write", "download"],
+  };
+
+  return jwt.sign(claims, jwtKey, {
+    algorithm: "RS256",
+    expiresIn: 3 * 24 * 60 * 60, // 3 days
+  });
+};

 module.exports = router;

The encoded JWT is then assigned to the jwt variable, which can be referenced in the view:


./views/documents/show.ejs
 <h1>Show document <%= documentId %></h1>
+<h1>JWT <%= jwt %></h1

Stop and restart the Express server, and then refresh the page. You should now see a fairly long token printed on the page.

Loading an Existing Document

Update the view to load the SDK, passing the document ID and the JWT:

./views/documents/show.ejs
+<script src="http://localhost:5000/pspdfkit.js"></script>
 <h1>Show document <%= @documentId %></h1>
 <h1>JWT <%= jwt %></h1>
+<!-- 2. Element where PSPDFKit will be mounted. -->
+<div id="pspdfkit" style="width: 100%; max-width: 800px; height: 480px;"></div>
+<!-- 3. Initialize PSPDFKit. -->
+<script>
+  PSPDFKit.load({
+    container: "#pspdfkit",
+    documentId: "<%= documentId %>",
+    authPayload: { jwt: "<%= jwt %>" },
+    instant: true
+  })
+    .then(function(instance) {
+      console.log("PSPDFKit loaded", instance);
+    })
+    .catch(function(error) {
+      console.error(error.message);
+    });
+</script>

Refresh the page, and you should see the PSPDFKit for Web viewer showing the document you just uploaded. If you annotate the document and refresh the page, all changes will be automatically persisted.

Requirements

PSPDFKit Server runs on a variety of platforms. The following operating systems are supported:

  • macOS Mojave, Catalina, or Big Sur (Apple’s M1-based Macs are not yet supported)

  • Windows 10 Pro, Home, Education, or Enterprise 64-bit

  • Ubuntu, Fedora, Debian, or CentOS. Ubuntu and Debian derivatives such as Kubuntu or Xubuntu are supported as well. Currently only 64-bit Intel (x86_64) processors are supported.

Regardless of your operating system, you’ll need at least 4 GB of RAM.

Installing Docker

PSPDFKit Server is distributed as a Docker container. To run it on your computer, you need to install a Docker runtime distribution for your operating system.

Install and start Docker Desktop for Mac. Please refer to the Docker website for instructions.

Install and start Docker Desktop for Windows. Please refer to the Docker website for instructions.

Install and start Docker Engine. Please refer to the Docker website for instructions on how to install it for your Linux distribution.

After you install Docker, use these instructions to install Docker Compose.

Setting Up PSPDFKit Server

Copy the code snippet below and save it anywhere on your computer in a file called docker-compose.yml:

version: "3.8"

services:
  pspdfkit:
    image: pspdfkit/pspdfkit:latest
    environment:
      PGUSER: pspdfkit
      PGPASSWORD: password
      PGDATABASE: pspdfkit
      PGHOST: db
      PGPORT: 5432
      ACTIVATION_KEY: <YOUR_ACTIVATION_KEY_GOES_HERE>
      API_AUTH_TOKEN: secret
      SECRET_KEY_BASE: secret-key-base
      JWT_PUBLIC_KEY: |
        -----BEGIN PUBLIC KEY-----
        MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94t
        OxsSxIQZMOc1GY8ubuqu2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQ==
        -----END PUBLIC KEY-----
      JWT_ALGORITHM: RS256
      DASHBOARD_USERNAME: dashboard
      DASHBOARD_PASSWORD: secret
    ports:
      - 5000:5000
    depends_on:
      - db
  db:
    image: postgres:13.1
    environment:
      POSTGRES_USER: pspdfkit
      POSTGRES_PASSWORD: password
      POSTGRES_DB: pspdfkit
      POSTGRES_INITDB_ARGS: --data-checksums
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Now open that file in your code editor and replace the <YOUR_ACTIVATION_KEY_GOES_HERE> placeholder on line 12 with your trial activation key.

Starting PSPDFKit Server

Now open a terminal emulator.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use Terminal.app or iTerm2.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use PowerShell.

Use the terminal emulator integrated with your code editor or IDE, or one bundled with your desktop environment.

Go to the directory where you saved the docker-compose.yml file:

cd <path-to-directory-with-docker-compose-yml>

Run the following:

docker-compose up

This command might take a while to run, depending on your internet connection speed. Wait until you see the following message in the terminal:

pspdfkit_1  | Access the web dashboard at http://localhost:5000/dashboard

The PSPDFKit Server is now up and running!

Uploading a Document to PSPDFKit Server

With PSPDFKit Server running, visit http://localhost:5000/dashboard and authenticate using “dashboard” for the username and “secret” for the password. Choose Add Document and upload the document you want to work with.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

Once the document is uploaded, visit http://localhost:5000/dashboard/documents to see the list of available documents. Each document is identified by an ID. Take note of the ID of the document you just uploaded, as you’ll need it shortly.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

The ID should look similar to 7KPS8X13JRB2G841X4V7EQ3T2J.

Adding a Page to View the Document

You need to create a page that will show a document stored inside PSPDFKit Server.

You’ll want this page to be available at http://localhost:3000/documents/:id, where the document ID is the ID automatically assigned by PSPDFKit Server when uploading a document.

To achieve this, create a new route to display a document and mount it in the application.

  1. Create the documents route:

./routes/documents.js
var express = require("express");
var router = express.Router();

router.get("/:documentId", function (req, res, next) {
  res.render("documents/show", { documentId: req.params.documentId });
});

module.exports = router;

Inside the route, retrieve the ID captured by the routing logic and assign it to a documentId variable you can refer to in the view.

  1. Create a corresponding view with some minimal HTML that prints the document ID:

./views/documents/show.ejs
<h1>Show document <%= documentId %></h1>

  1. Mount the new route in the application:

./app.js
 var indexRouter = require('./routes/index');
 var usersRouter = require('./routes/users');
+var documentsRouter = require("./routes/documents");
 // ...
 // rest of the file
 // ...
 app.use('/', indexRouter);
 app.use('/users', usersRouter);
+app.use("/documents", documentsRouter);

Stop and restart the Express server.

You can now visit http://localhost:3000/documents/:id, replacing :id with the ID of the document you uploaded to the PSPDFKit Server dashboard.

The page should contain the text Show document, followed by your document ID.

Creating a JSON Web Token (JWT)

PSPDFKit requires the use of JWTs to authenticate and authorize a viewer session against PSPDFKit Server.

To create JWTs, install the jsonwebtoken dependency:

npm install --save jsonwebtoken

Stop and restart the Express server.

Working with JWTs requires a private and public key pair. The private key is used by the Express application, while the public key is used by PSPDFKit Server.

The public key has already been configured in the PSPDFKit Server docker-compose.yml file via the JWT_PUBLIC_KEY environment variable.

To configure the private key, create a config/pspdfkit/jwt.pem file with the following contents:

./config/pspdfkit/jwt.pem
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94tOxsSxIQZMOc1GY8ubuqu
2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQJAHfi9lEtysRkjNQSBxqzK
hm7JDvLxU1AsQaX1OGctF/fLXzkWiMLsBZ3yLHdPSvl/izbKyGrADv7wrQJrPPhg
gQIhAPQrw5Uh7pQ4RMvkDJff7aHWwWTUuqgsiS/r1/7KHl8VAiEAwFxH2YA3MR/5
Rl5/VJJp6Cv/2IGSgQVCSDZyL5rcBFECIQDc3eGTOxhmtud0T5scnpCD/pD9tngJ
vA90a6/8Z7RFaQIhAIBOjVZUoXvQ+fKoIYKFzsKgZp1BgDkzCs0kE/IQ92ShAiEA
7f4XIbGgIFaSJRpBfa168aeP162EV5oOW+Gyv2IIyK8=
-----END RSA PRIVATE KEY-----

Update ./routes/documents.js to read the private key so that it can be used to sign JWTs and pass them to the view.

In the claims, you pass the document ID, the set of permissions you want to have, and an expiry of one hour:

./routes/documents.js
 var express = require("express");
 var router = express.Router();
+var fs = require("fs");
+var path = require("path");
+var jwt = require("jsonwebtoken");
+var jwtKey = fs.readFileSync(
+  path.resolve(__dirname, "../config/pspdfkit/jwt.pem")
+);

 router.get("/:documentId", function (req, res, next) {
+  var jwt = prepareJwt(req.params.documentId);
-  res.render("documents/show", { documentId: req.params.documentId });
+  res.render("documents/show", { documentId: req.params.documentId, jwt: jwt });
 });
+
+var prepareJwt = function (documentId) {
+  var claims = {
+    document_id: documentId,
+    permissions: ["read-document", "write", "download"],
+  };
+
+  return jwt.sign(claims, jwtKey, {
+    algorithm: "RS256",
+    expiresIn: 3 * 24 * 60 * 60, // 3 days
+  });
+};

 module.exports = router;

The encoded JWT is then assigned to the jwt variable, which can be referenced in the view:


./views/documents/show.ejs
 <h1>Show document <%= documentId %></h1>
+<h1>JWT <%= jwt %></h1

Stop and restart the Express server, and then refresh the page. You should now see a fairly long token printed on the page.

Loading an Existing Document

Update the view to load the SDK, passing the document ID and the JWT:

./views/documents/show.ejs
+<script src="http://localhost:5000/pspdfkit.js"></script>
 <h1>Show document <%= @documentId %></h1>
 <h1>JWT <%= jwt %></h1>
+<!-- 2. Element where PSPDFKit will be mounted. -->
+<div id="pspdfkit" style="width: 100%; max-width: 800px; height: 480px;"></div>
+<!-- 3. Initialize PSPDFKit. -->
+<script>
+  PSPDFKit.load({
+    container: "#pspdfkit",
+    documentId: "<%= documentId %>",
+    authPayload: { jwt: "<%= jwt %>" },
+    instant: true
+  })
+    .then(function(instance) {
+      console.log("PSPDFKit loaded", instance);
+    })
+    .catch(function(error) {
+      console.error(error.message);
+    });
+</script>

Refresh the page, and you should see the PSPDFKit for Web viewer showing the document you just uploaded. If you annotate the document and refresh the page, all changes will be automatically persisted.

Requirements

PSPDFKit Server runs on a variety of platforms. The following operating systems are supported:

  • macOS Mojave, Catalina, or Big Sur (Apple’s M1-based Macs are not yet supported)

  • Windows 10 Pro, Home, Education, or Enterprise 64-bit

  • Ubuntu, Fedora, Debian, or CentOS. Ubuntu and Debian derivatives such as Kubuntu or Xubuntu are supported as well. Currently only 64-bit Intel (x86_64) processors are supported.

Regardless of your operating system, you’ll need at least 4 GB of RAM.

Installing Docker

PSPDFKit Server is distributed as a Docker container. To run it on your computer, you need to install a Docker runtime distribution for your operating system.

Install and start Docker Desktop for Mac. Please refer to the Docker website for instructions.

Install and start Docker Desktop for Windows. Please refer to the Docker website for instructions.

Install and start Docker Engine. Please refer to the Docker website for instructions on how to install it for your Linux distribution.

After you install Docker, use these instructions to install Docker Compose.

Setting Up PSPDFKit Server

Copy the code snippet below and save it anywhere on your computer in a file called docker-compose.yml:

version: "3.8"

services:
  pspdfkit:
    image: pspdfkit/pspdfkit:latest
    environment:
      PGUSER: pspdfkit
      PGPASSWORD: password
      PGDATABASE: pspdfkit
      PGHOST: db
      PGPORT: 5432
      ACTIVATION_KEY: <YOUR_ACTIVATION_KEY_GOES_HERE>
      API_AUTH_TOKEN: secret
      SECRET_KEY_BASE: secret-key-base
      JWT_PUBLIC_KEY: |
        -----BEGIN PUBLIC KEY-----
        MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94t
        OxsSxIQZMOc1GY8ubuqu2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQ==
        -----END PUBLIC KEY-----
      JWT_ALGORITHM: RS256
      DASHBOARD_USERNAME: dashboard
      DASHBOARD_PASSWORD: secret
    ports:
      - 5000:5000
    depends_on:
      - db
  db:
    image: postgres:13.1
    environment:
      POSTGRES_USER: pspdfkit
      POSTGRES_PASSWORD: password
      POSTGRES_DB: pspdfkit
      POSTGRES_INITDB_ARGS: --data-checksums
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Now open that file in your code editor and replace the <YOUR_ACTIVATION_KEY_GOES_HERE> placeholder on line 12 with your trial activation key.

Starting PSPDFKit Server

Now open a terminal emulator.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use Terminal.app or iTerm2.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use PowerShell.

Use the terminal emulator integrated with your code editor or IDE, or one bundled with your desktop environment.

Go to the directory where you saved the docker-compose.yml file:

cd <path-to-directory-with-docker-compose-yml>

Run the following:

docker-compose up

This command might take a while to run, depending on your internet connection speed. Wait until you see the following message in the terminal:

pspdfkit_1  | Access the web dashboard at http://localhost:5000/dashboard

The PSPDFKit Server is now up and running!

Uploading a Document to PSPDFKit Server

With PSPDFKit Server running, visit http://localhost:5000/dashboard and authenticate using “dashboard” for the username and “secret” for the password. Choose Add Document and upload the document you want to work with.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

Once the document is uploaded, visit http://localhost:5000/dashboard/documents to see the list of available documents. Each document is identified by an ID. Take note of the ID of the document you just uploaded, as you’ll need it shortly.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

The ID should look similar to 7KPS8X13JRB2G841X4V7EQ3T2J.

Installing Ruby and Ruby on Rails

If you haven’t installed Ruby and Ruby on Rails, head to the official guides and follow the instructions. By the end of the installation process, you should be able to run the following command:

rails --version

The output should be something like Rails 6.1. You can ignore any subsequent number.

Generating the Application

You can start by generating a vanilla Rails application.

Run:

rails new pspdfkit_example

This command will take a minute or two. Once done, you should be able to cd pspdfkit_example and run:

bin/rails server

You can then visit http://localhost:3000 to confirm the application is working as expected.

Adding a Page to View the Document

You need to create a page that will show a document stored inside PSPDFKit Server.

You’ll want this page to be available at http://localhost:3000/documents/:id, where the document ID is the ID automatically assigned by PSPDFKit Server when uploading a document.

To achieve this, you need to update your routes and create a controller and view.

  1. Add a new route to the application:

./config/routes.rb
Rails.application.routes.draw do
   # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
+  resources :documents, only: :show
end

  1. Create a corresponding controller:

./app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
  def show
    @document_id = params['id']
  end
end

Inside the controller, retrieve the ID captured by the routing logic and assign it to a @document_id instance variable you can refer to in the view.

  1. Create a corresponding view with some minimal HTML that prints the document ID:

./app/views/documents/show.html.erb
<h1>Show document <%= @document_id %></h1>

You can now visit http://localhost:3000/documents/:id, replacing :id with the ID of the document you uploaded to the PSPDFKit Server dashboard.

The page should contain the text Show document, followed by your document ID.

Creating a JSON Web Token (JWT)

PSPDFKit requires the use of JWTs to authenticate and authorize a viewer session against PSPDFKit Server.

To create JWTs, add the jwt dependency to the project Gemfile:

./Gemfile
 # Use Active Model has_secure_password
 # gem 'bcrypt', '~> 3.1.7'
+gem 'jwt', '~> 2.2', '>= 2.2.2'

Stop the Rails server with Control-C, run bundle install to install the dependency, and then run bin/rails server to restart it.

Working with JWTs requires a private and public key pair. The private key is used by the Rails application, while the public key is used by PSPDFKit Server.

Create a config/pspdfkit/jwt.pem file with the following contents:

./config/pspdfkit/jwt.pem
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94tOxsSxIQZMOc1GY8ubuqu
2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQJAHfi9lEtysRkjNQSBxqzK
hm7JDvLxU1AsQaX1OGctF/fLXzkWiMLsBZ3yLHdPSvl/izbKyGrADv7wrQJrPPhg
gQIhAPQrw5Uh7pQ4RMvkDJff7aHWwWTUuqgsiS/r1/7KHl8VAiEAwFxH2YA3MR/5
Rl5/VJJp6Cv/2IGSgQVCSDZyL5rcBFECIQDc3eGTOxhmtud0T5scnpCD/pD9tngJ
vA90a6/8Z7RFaQIhAIBOjVZUoXvQ+fKoIYKFzsKgZp1BgDkzCs0kE/IQ92ShAiEA
7f4XIbGgIFaSJRpBfa168aeP162EV5oOW+Gyv2IIyK8=
-----END RSA PRIVATE KEY-----

Add an initializer that will read the private key and store it in the application configuration so that it can be used to sign JWTs.

./config/initializers/pspdfkit.rb
Rails.configuration.x.pspdfkit.jwt_key = OpenSSL::PKey::RSA.new(Rails.root.join("config", "pspdfkit", "jwt.pem").read)

Then update DocumentsController to create a JWT to view the document:

./app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
   def show
     @document_id = params['id']
+    @jwt = prepare_jwt(@document_id)
+  end
+
+  private
+
+  def prepare_jwt(document_id)
+    config = Rails.application.config.x.pspdfkit
+
+    claims = {
+      document_id: document_id,
+      permissions: %w[read-document write download],
+      exp: Time.now.to_i + 60 * 60
+    }
+
+    JWT.encode(claims, config.jwt_key, 'RS256')
   end
 end

In the claims, you pass the document ID, the set of permissions you want to have, and an expiry of one hour.

The encoded JWT is then assigned to the @jwt instance variable, which can be referenced in the view:

./app/views/documents/show.html.erb
 <h1>Show document <%= @document_id %></h1>
+<h1>JWT <%= @jwt %></h1

If you refresh the page, you should now see a fairly long token printed on the page.

Loading an Existing Document

Update the view to load the SDK, passing the document ID and the JWT:

./app/views/documents/show.html.erb
+<script src="http://localhost:5000/pspdfkit.js"></script>
 <h1>Show document <%= @document_id %></h1>
 <h1>JWT <%= @jwt %></h1>
+<!-- 2. Element where PSPDFKit will be mounted. -->
+<div id="pspdfkit" style="width: 100%; height: 480px;"></div>
+<!-- 3. Initialize PSPDFKit. -->
+<script>
+  PSPDFKit.load({
+    container: "#pspdfkit",
+    documentId: "<%= @document_id %>",
+    authPayload: { jwt: "<%= @jwt %>" },
+    instant: true
+  })
+    .then(function(instance) {
+      console.log("PSPDFKit loaded", instance);
+    })
+    .catch(function(error) {
+      console.error(error.message);
+    });
+</script>

Refresh, and you should see the PSPDFKit for Web viewer showing the document you just uploaded. If you annotate the document and refresh the page, all changes will be automatically persisted.

Requirements

PSPDFKit Server runs on a variety of platforms. The following operating systems are supported:

  • macOS Mojave, Catalina, or Big Sur (Apple’s M1-based Macs are not yet supported)

  • Windows 10 Pro, Home, Education, or Enterprise 64-bit

  • Ubuntu, Fedora, Debian, or CentOS. Ubuntu and Debian derivatives such as Kubuntu or Xubuntu are supported as well. Currently only 64-bit Intel (x86_64) processors are supported.

Regardless of your operating system, you’ll need at least 4 GB of RAM.

Installing Docker

PSPDFKit Server is distributed as a Docker container. To run it on your computer, you need to install a Docker runtime distribution for your operating system.

Install and start Docker Desktop for Mac. Please refer to the Docker website for instructions.

Install and start Docker Desktop for Windows. Please refer to the Docker website for instructions.

Install and start Docker Engine. Please refer to the Docker website for instructions on how to install it for your Linux distribution.

After you install Docker, use these instructions to install Docker Compose.

Setting Up PSPDFKit Server

Copy the code snippet below and save it anywhere on your computer in a file called docker-compose.yml:

version: "3.8"

services:
  pspdfkit:
    image: pspdfkit/pspdfkit:latest
    environment:
      PGUSER: pspdfkit
      PGPASSWORD: password
      PGDATABASE: pspdfkit
      PGHOST: db
      PGPORT: 5432
      ACTIVATION_KEY: <YOUR_ACTIVATION_KEY_GOES_HERE>
      API_AUTH_TOKEN: secret
      SECRET_KEY_BASE: secret-key-base
      JWT_PUBLIC_KEY: |
        -----BEGIN PUBLIC KEY-----
        MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94t
        OxsSxIQZMOc1GY8ubuqu2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQ==
        -----END PUBLIC KEY-----
      JWT_ALGORITHM: RS256
      DASHBOARD_USERNAME: dashboard
      DASHBOARD_PASSWORD: secret
    ports:
      - 5000:5000
    depends_on:
      - db
  db:
    image: postgres:13.1
    environment:
      POSTGRES_USER: pspdfkit
      POSTGRES_PASSWORD: password
      POSTGRES_DB: pspdfkit
      POSTGRES_INITDB_ARGS: --data-checksums
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Now open that file in your code editor and replace the <YOUR_ACTIVATION_KEY_GOES_HERE> placeholder on line 12 with your trial activation key.

Starting PSPDFKit Server

Now open a terminal emulator.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use Terminal.app or iTerm2.

Use the terminal emulator integrated with your code editor or IDE. Alternatively, you can use PowerShell.

Use the terminal emulator integrated with your code editor or IDE, or one bundled with your desktop environment.

Go to the directory where you saved the docker-compose.yml file:

cd <path-to-directory-with-docker-compose-yml>

Run the following:

docker-compose up

This command might take a while to run, depending on your internet connection speed. Wait until you see the following message in the terminal:

pspdfkit_1  | Access the web dashboard at http://localhost:5000/dashboard

The PSPDFKit Server is now up and running!

Uploading a Document to PSPDFKit Server

With PSPDFKit Server running, visit http://localhost:5000/dashboard and authenticate using “dashboard” for the username and “secret” for the password. Choose Add Document and upload the document you want to work with.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

Once the document is uploaded, visit http://localhost:5000/dashboard/documents to see the list of available documents. Each document is identified by an ID. Take note of the ID of the document you just uploaded, as you’ll need it shortly.

Screenshot showing the create document modal window in the PSPDFKit Server Dashboard

The ID should look similar to 7KPS8X13JRB2G841X4V7EQ3T2J.

Adding a Page to View the Document

You need to create a page that will show a document stored inside PSPDFKit Server.

You’ll want this page to be available at http://localhost:3000/documents/:id, where the document ID is the ID automatically assigned by PSPDFKit Server when uploading a document.

To achieve this, you need to update your routes and create a controller and view.

  1. Add a new route to the application:

./config/routes.rb
Rails.application.routes.draw do
   # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
+  resources :documents, only: :show
end

  1. Create a corresponding controller:

./app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
  def show
    @document_id = params['id']
  end
end

Inside the controller, retrieve the ID captured by the routing logic and assign it to a @document_id instance variable you can refer to in the view.

  1. Create a corresponding view with some minimal HTML that prints the document ID:

./app/views/documents/show.html.erb
<h1>Show document <%= @document_id %></h1>

You can now visit http://localhost:3000/documents/:id, replacing :id with the ID of the document you uploaded to the PSPDFKit Server dashboard.

The page should contain the text Show document, followed by your document ID.

Creating a JSON Web Token (JWT)

PSPDFKit requires the use of JWTs to authenticate and authorize a viewer session against PSPDFKit Server.

To create JWTs, add the jwt dependency to the project Gemfile:

./Gemfile
 # Use Active Model has_secure_password
 # gem 'bcrypt', '~> 3.1.7'
+gem 'jwt', '~> 2.2', '>= 2.2.2'

Stop the Rails server with Control-C, run bundle install to install the dependency, and then run bin/rails server to restart it.

Working with JWTs requires a private and public key pair. The private key is used by the Rails application, while the public key is used by PSPDFKit Server.

Create a config/pspdfkit/jwt.pem file with the following contents:

./config/pspdfkit/jwt.pem
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBALd41vG5rMzG26hhVxE65kzWC+bYQ94tOxsSxIQZMOc1GY8ubuqu
2iku5/5isaFfG44e+VAe+YIdVeQY7cUkaaUCAwEAAQJAHfi9lEtysRkjNQSBxqzK
hm7JDvLxU1AsQaX1OGctF/fLXzkWiMLsBZ3yLHdPSvl/izbKyGrADv7wrQJrPPhg
gQIhAPQrw5Uh7pQ4RMvkDJff7aHWwWTUuqgsiS/r1/7KHl8VAiEAwFxH2YA3MR/5
Rl5/VJJp6Cv/2IGSgQVCSDZyL5rcBFECIQDc3eGTOxhmtud0T5scnpCD/pD9tngJ
vA90a6/8Z7RFaQIhAIBOjVZUoXvQ+fKoIYKFzsKgZp1BgDkzCs0kE/IQ92ShAiEA
7f4XIbGgIFaSJRpBfa168aeP162EV5oOW+Gyv2IIyK8=
-----END RSA PRIVATE KEY-----

Add an initializer that will read the private key and store it in the application configuration so that it can be used to sign JWTs.

./config/initializers/pspdfkit.rb
Rails.configuration.x.pspdfkit.jwt_key = OpenSSL::PKey::RSA.new(Rails.root.join("config", "pspdfkit", "jwt.pem").read)

Then update DocumentsController to create a JWT to view the document:

./app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
   def show
     @document_id = params['id']
+    @jwt = prepare_jwt(@document_id)
+  end
+
+  private
+
+  def prepare_jwt(document_id)
+    config = Rails.application.config.x.pspdfkit
+
+    claims = {
+      document_id: document_id,
+      permissions: %w[read-document write download],
+      exp: Time.now.to_i + 60 * 60
+    }
+
+    JWT.encode(claims, config.jwt_key, 'RS256')
   end
 end

In the claims, you pass the document ID, the set of permissions you want to have, and an expiry of one hour.

The encoded JWT is then assigned to the @jwt instance variable, which can be referenced in the view:

./app/views/documents/show.html.erb
 <h1>Show document <%= @document_id %></h1>
+<h1>JWT <%= @jwt %></h1

If you refresh the page, you should now see a fairly long token printed on the page.

Loading an Existing Document

Update the view to load the SDK, passing the document ID and the JWT:

./app/views/documents/show.html.erb
+<script src="http://localhost:5000/pspdfkit.js"></script>
 <h1>Show document <%= @document_id %></h1>
 <h1>JWT <%= @jwt %></h1>
+<!-- 2. Element where PSPDFKit will be mounted. -->
+<div id="pspdfkit" style="width: 100%; height: 480px;"></div>
+<!-- 3. Initialize PSPDFKit. -->
+<script>
+  PSPDFKit.load({
+    container: "#pspdfkit",
+    documentId: "<%= @document_id %>",
+    authPayload: { jwt: "<%= @jwt %>" },
+    instant: true
+  })
+    .then(function(instance) {
+      console.log("PSPDFKit loaded", instance);
+    })
+    .catch(function(error) {
+      console.error(error.message);
+    });
+</script>

Refresh, and you should see the PSPDFKit for Web viewer showing the document you just uploaded. If you annotate the document and refresh the page, all changes will be automatically persisted.

Integrating the PSPDFKit .NET Library is simple with the use of the public NuGet repository. Like with most other .NET libraries, you can add PSPDFKit directly from Visual Studio or with the dotnet command-line app.

The following instructions are generic for any .NET product.

Requirements

For details on version support for the PSPDFKit .NET Library, see the compatibility page.

For details on version support for the PSPDFKit .NET Library, see the compatibility page.

For details on version support for the PSPDFKit .NET Library, see the compatibility page.

  1. Create a folder for your application.

  2. Creating a .NET C# console application on all platforms can be done on each platform’s respective command line with:

cd <newly created folder>
dotnet new console

Alternatively, you can use an IDE such as Visual Studio for Windows, or Visual Studio Code on all platforms.

For existing projects, jump straight to the library integration steps below.

Adding the PSPDFKit .NET Library NuGet Package

Using Visual Studio on Windows

It’s possible to add the PSPDFKit .NET Library within the Visual Studio GUI if you’re working in Windows. Please see the Microsoft guide on packages for instructions on how to add a package, and search for PSPDFKit.NET when browsing for the package.

Using the .NET Command-Line Application

A cross-platform solution for adding the PSPDFKit .NET Library to your project would be to use the dotnet command-line application. Run the following command in your project folder to add the PSPDFKit .NET Library package:

dotnet add package PSPDFKit.NET --version 1.4.0

Other Package Installation Options

There are many ways to add a package to a project:

Please refer to the relevant link above for more specific information.

Using the PSPDFKit .NET Library

  1. Now that the PSPDFKit .NET Library is added, you can use the SDK in your application. You need to initialize the SDK prior to calling any other PSPDFKit method. Use the initializeTrial method if you haven’t yet bought a license key, or the initialize method if you have a key:

PSPDFKit.Sdk.InitializeTrial();
  1. Load a document with:

var fileProvider = new FileDataProvider("path/to/document.pdf");
var document = new Document(fileProvider);
  1. Once you have a document loaded, you can use the rest of the library. See the API docs and guides for more information, or try out the Catalog examples (see below).

Building and Running the Catalog App

The PSPDFKit .NET Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit.NET-{version}.zip to your desired location and cd into Example/catalog.

  3. Run the Catalog example:

dotnet run --project Catalog

The PSPDFKit .NET Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit.NET-{version}.zip to your desired location and cd into Example/catalog.

  3. Run the Catalog example:

dotnet run --project Catalog

The PSPDFKit .NET Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit.NET-{version}.zip to your desired location.

  3. From the extracted files, open the Example/Catalog.sln solution in Visual Studio (or an equivalent IDE supporting the .NET Framework).

  4. Choose the solution platform x86 or x64.

  5. Build and run the project from the IDE, or use the following command:

dotnet run --project Catalog

It’s recommended that you integrate the PSPDFKit .NET Library with the package hosted on the public NuGet repository. However, if you don’t have access to the internet on your development machine, or if you have strict CI requirements, then it’s possible to download the PSPDFKit .NET Library from the PSPDFKit servers and integrate it into your .NET project manually.

Requirements

For details on version support for the PSPDFKit .NET Library, see the compatibility page.

For details on version support for the PSPDFKit .NET Library, see the compatibility page.

For details on version support for the PSPDFKit .NET Library, see the compatibility page.

  1. Create a folder for your application.

  2. Creating a .NET C# console application on all platforms can be done on each platform’s respective command line with:

cd <newly created folder>
dotnet new console

Alternatively, you can use an IDE such as Visual Studio for Windows, or Visual Studio Code on all platforms.

For existing projects, jump straight to the library integration steps below.

Creating the PSPDFKit NuGet Source

The following section shows how to set up a configuration to point to a local package you just downloaded in the PSPDFKit .NET Library binary.

The local configuration is described by a file named nuget.config, which is located in the same directory as the solution file (e.g. Test.sln).

  1. Create or modify the nuget.config file.

  2. Place packageSources in the relevant location, or if the file is new, paste all of the following code:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<packageSources>
		<add key="PSPDFKitSource" value="path/to/directoryContainingNupkg" />
	</packageSources>
</configuration>

Edit the value of the contents to correctly refer to the location of the directory containing the PSPDFKit.NET-*.*.*.nupkg package — for example, /Users/me/nugetPackages. These packages can be found in the unzipped binary downloaded earlier in the nuget directory.

Adding the PSPDFKit .NET Library NuGet Package

Using Visual Studio on Windows

It’s possible to add the PSPDFKit .NET Library within the Visual Studio GUI if you’re working in Windows. Please see the Microsoft guide on packages for instructions on how to add a package, and search for PSPDFKit.NET when browsing for the package.

Ensure you’re searching the newly created NuGet configuration, PSPDFKitSource, defined earlier in the nuget.config file, when locating the package.

Using the .NET Command-Line Application

Now that you have the NuGet source, you can add the package to the project:

  • cd into your project solution.

  • Add the package by running:

dotnet add <PROJECT_NAME> package PSPDFKit.NET --version 1.4.0

<PROJECT_NAME> is the project you want to add the package to.

  • Now restore all the newly added packages with dotnet restore. You’ll need an internet connection to retrieve the dependency projects.

Other Package Installation Options

There are many ways to add a package to a project:

Please refer to the relevant link above for more specific information.

Using the PSPDFKit .NET Library

  1. Now that the PSPDFKit .NET Library is added, you can use the SDK in your application. You need to initialize the SDK prior to calling any other PSPDFKit method. Use the initializeTrial method if you haven’t yet bought a license key, or the initialize method if you have a key:

PSPDFKit.Sdk.InitializeTrial();
  1. Load a document with:

var fileProvider = new FileDataProvider("path/to/document.pdf");
var document = new Document(fileProvider);
  1. Once you have a document loaded, you can use the rest of the library. See the API docs and guides for more information, or try out the Catalog examples (see below).

Building and Running the Catalog App

The PSPDFKit .NET Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit.NET-{version}.zip to your desired location and cd into Example/catalog.

  3. Run the Catalog example:

dotnet run --project Catalog

The PSPDFKit .NET Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit.NET-{version}.zip to your desired location and cd into Example/catalog.

  3. Run the Catalog example:

dotnet run --project Catalog

The PSPDFKit .NET Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit.NET-{version}.zip to your desired location.

  3. From the extracted files, open the Example/Catalog.sln solution in Visual Studio (or an equivalent IDE supporting the .NET Framework).

  4. Choose the solution platform x86 or x64.

  5. Build and run the project from the IDE, or use the following command:

dotnet run --project Catalog

Please select the build system you’re using:

Gradle Build System

  1. In your top-level build.gradle file, add the PSPDFKit Maven repository:

allprojects {
	repositories {
		maven {
				url 'https://customers.pspdfkit.com/maven/'
		}
	}
}
  1. In the depending module’s build.gradle file, add the PSPDFKit dependency:

    dependencies {
        implementation 'com.pspdfkit:libraries-java:1.4.0'
    }
    
  2. Add the OCR dependency (optional). This is only necessary if you plan to use the OCR feature.

To use the PSPDFKit OCR feature with the PSPDFKit Java Library, a separate package, libraries-java-ocr, is required.

Add the new package dependency to your build.gradle file:

dependencies {
...
    implementation 'com.pspdfkit:libraries-java-ocr:1.4.0'
}

Maven Build System

  1. In your top-level pom.xml file, add the PSPDFKit Maven repository:

<project ...>

...

<repositories>
	<repository>
		<id>pspdfkit</id>
		<name>PSPDFKit Maven</name>
		<url>https://customers.pspdfkit.com/maven/</url>
	</repository>
</repositories>

...

</project>
  1. In the depending module’s pom.xml file, add the PSPDFKit dependency:

<project ...>

...

<dependencies>
	<dependency>
		<groupId>com.pspdfkit</groupId>
		<artifactId>libraries-java</artifactId>
		<version>1.4.0</version>
	</dependency>
</dependencies>

...

</project>
  1. Add the OCR dependency (optional). This is only necessary if you plan to use the OCR feature.

To use the PSPDFKit OCR feature with the PSPDFKit Java Library, a separate package, libraries-java-ocr, is required.

Add the new package dependency to your project pom.xml file:

 <dependencies>
    ...
    <dependency>
        <groupId>com.pspdfkit</groupId>
        <artifactId>libraries-java-ocr</artifactId>
        <version>1.4.0</version>
    </dependency>

Using the PSPDFKit Java Library

  1. Now that the PSPDFKit Java Library is added, you can use the SDK in your application. You need to initialize the SDK prior to calling any other PSPDFKit method. Use the initializeTrial method if you haven’t yet bought a license key, or the initialize method if you have a key:

public void initializePSPDFKit() throws PSPDFKitInitializeException {
    PSPDFKit.initializeTrial();
}
@Throws(PSPDFKitInitializeException::class)
fun initializePSPDFKit() : Void {
    PSPDFKit.initializeTrial();
}
  1. Load a document with:

File file = new File("path/to/document.pdf");
PdfDocument document = PdfDocument.open(new FileDataProvider(file));
val file = File("path/to/document.pdf")
val document = PdfDocument.open(FileDataProvider(file))
  1. Once you have a document loaded, you can use the rest of the library. See the API docs and guides for more information, or try out the Catalog examples (see below).

Building and Running the Catalog App

The PSPDFKit Java Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit-java-{version}.zip to your desired location and cd into the root of its directory.

  3. cd into the Catalog (cd catalog).

  4. Build and run the Catalog application:

./gradlew runJava

The PSPDFKit Java Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit-java-{version}.zip to your desired location and cd into the root of its directory.

  3. cd into the Catalog (cd catalog).

  4. Build and run the Catalog application:

./gradlew runJava

The PSPDFKit Java Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit-java-{version}.zip to your desired location and cd into the root of its directory.

  3. cd into the Catalog (cd catalog).

  4. Build and run the Catalog application:

gradlew.bat runJava

Only use the manual method if absolutely necessary. Otherwise, please refer to the main Integrating PSPDFKit Java Library guide for more details.

Please select the build system you’re using:

Gradle Build System

If you’re using the Gradle build system, a good example of how to integrate the PSPDFKit Java Library can be seen in the Catalog example distributed in the downloaded ZIP.

Complete the following steps for manual Gradle integration.

  1. Create a folder within your project named libs.

  2. Download the latest release.

  3. In the downloaded ZIP file, there will be a JAR file, pspdfkit-1.4.0.jar. Copy this JAR file into the libs folder you just created.

  4. In your project’s build.gradle folder, add a dependency to the copied JAR file (replace the wildcards with the version number):

dependencies {
	...
	implementation files('libs/pspdfkit-1.4.0.jar')

	// Required by PSPDFKit.
	implementation 'org.json:json:20180813'
	implementation 'org.apache.httpcomponents:httpclient:4.5.9'
	...
}

Now your Gradle project will depend upon the PSPDFKit JAR. More information about declaring dependencies can be found in the Gradle documentation.

  1. Add the OCR dependency (optional). This is only necessary if you plan to use the OCR feature.

To use the PSPDFKit OCR feature with the PSPDFKit Java Library, a separate package, libraries-java-ocr, is required.

Maven Build System

To use the PSPDFKit Java Library with Maven, it’s first necessary to install the PSPDFKit JAR to a Maven repository. Only when this is done can it be a reference for a Maven project.

  1. Download the latest release.

  2. Extract the files from PSPDFKit-Java-binary-1.4.0.zip into a known location.

  3. Within your project, using mvn on the command line, add the PSPDFKit JAR to a repository, replacing both the version (where necessary) and the path to the JAR and POM (extracted from PSPDFKit-Java-binary-1.4.0.zip):

mvn install:install-file -Dfile=/path/to/jar/pspdfkit-*.*.*.jar -DpomFile=/path/to/pom/pspdfkit-pom.xml

This will install the JAR to a local repository. It’s also possible to publish this JAR remotely; please see the Maven guides if this is a requirement.

  1. Add the PSPDFKit Java Library as a dependency of your project. In your project’s pom.xml, add the following, replacing the version with the target version:

...
<dependencies>
	<dependency>
		<groupId>com.pspdfkit.api</groupId>
		<artifactId>pspdfkit</artifactId>
		<version>1.4.0</version>
	</dependency>
</dependencies>
...

Now your Maven project will depend on the PSPDFKit JAR published to the chosen repository.

  1. Add the OCR dependency (optional). This is only necessary if you plan to use the OCR feature.

To use the PSPDFKit OCR feature with the PSPDFKit Java Library, a separate package, libraries-java-ocr, is required.

Using the PSPDFKit Java Library

  1. Now that the PSPDFKit Java Library is added, you can use the SDK in your application. You need to initialize the SDK prior to calling any other PSPDFKit method. Use the initializeTrial method if you haven’t yet bought a license key, or the initialize method if you have a key:

public void initializePSPDFKit() throws PSPDFKitInitializeException {
    PSPDFKit.initializeTrial();
}
@Throws(PSPDFKitInitializeException::class)
fun initializePSPDFKit() : Void {
    PSPDFKit.initializeTrial();
}
  1. Load a document with:

File file = new File("path/to/document.pdf");
PdfDocument document = PdfDocument.open(new FileDataProvider(file));
val file = File("path/to/document.pdf")
val document = PdfDocument.open(FileDataProvider(file))
  1. Once you have a document loaded, you can use the rest of the library. See the API docs and guides for more information, or try out the Catalog examples (see below).

Building and Running the Catalog App

The PSPDFKit Java Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit-java-{version}.zip to your desired location and cd into the root of its directory.

  3. cd into the Catalog (cd catalog).

  4. Build and run the Catalog application:

./gradlew runJava

The PSPDFKit Java Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit-java-{version}.zip to your desired location and cd into the root of its directory.

  3. cd into the Catalog (cd catalog).

  4. Build and run the Catalog application:

./gradlew runJava

The PSPDFKit Java Library comes with an example application called the Catalog app, which contains many useful examples for exploring the different features of PSPDFKit and getting started quickly. You can find the app in the Example folder of the SDK ZIP file.

To build and run the Catalog app, follow these steps.

  1. Download the latest release.

  2. Extract PSPDFKit-java-{version}.zip to your desired location and cd into the root of its directory.

  3. cd into the Catalog (cd catalog).

  4. Build and run the Catalog application: