Getting Started on Server-Backed

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

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

<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.1'
    }
    
  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.1'
}

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.1</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.1</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.1.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.1.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.1.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.1.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.1</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:

gradlew.bat runJava

This guide walks you through the steps necessary to start PSPDFKit Processor. It also shows you how to use it to process documents. By the end, you’ll be able to merge two PDF documents into one using Processor’s HTTP API from PHP.

Requirements

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

Starting PSPDFKit Processor

First, open your 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.

Now run the following command:

docker run --rm -t pspdfkit/processor:latest

This command might take a while to run, depending on your internet connection speed. Wait until you see a message like this in the terminal:

[info]  2021-03-02 18:56:45.286  Running PSPDFKit Processor version 2021.1.0. pid=<0.1851.0>

The PSPDFKit Processor is now up and running!

Installing PHP

The interaction with Processor happens via its HTTP API: You send documents and commands in the request and receive the resulting file in the response. To do this, you’ll invoke the API from the PHP script. But first, you need to install PHP for your operating system:

The easiest way to install PHP on macOS is via Homebrew. Follow the instructions on the Homebrew website to install it. Then, to install PHP, run:

brew install php@7.4 && brew link php@7.4

Verify the installation by running the following command in the terminal:

php --version

The output should start with PHP 7.4 — you can ignore the rest of the message.

ℹ️ Note: If the output doesn’t match the above, try restarting your terminal app by typing exit and opening it again.

  1. Download the PHP ZIP archive from the PHP website (pick the x86 Thread Safe build of the 7.4 release).

  2. Create a folder anywhere on your C: drive.

  3. Extract the ZIP archive into the folder you just created.

  4. Open the terminal and switch to that folder:

cd C:\path\to\directory

Now run the .\php.exe --version command. The output should start with PHP 7.4 — you can ignore the rest of the message.

To proceed, you’ll also need to create a PHP configuration file to enable a specific extension. So in the same directory, create a php.ini file with the following content:

[PHP]
extension=curl

Save the file, as you’ll need it shortly.

You can install PHP using your distribution’s package manager:

apt-get update && apt-get install -y php
dnf install -y php

Now run the php --version command. The output should start with PHP 7.4 — you can ignore the rest of the message.

Handling File Uploads

In this example project, the PDF files you’ll merge will be uploaded through a simple webpage via a standard HTML form. Create a file called index.php with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Merge PDFs with PSPDFKit Processor</title>
</head>
<body>
    <p>Upload the files to merge:</p>
    <form enctype="multipart/form-data" action="merge.php" method="post">
        <div>File 1: <input name="file1" type="file" accept="application/pdf"></div>
        <div>File 2: <input name="file2" type="file" accept="application/pdf"></div>
        <input type="submit" value= "Merge PDFs">
    </form>
</body>
</html>

Now open the terminal and type the following command in the same directory where you created the index.php file:

php -S localhost:8000
.\php.exe -c php.ini -S localhost:8000
php -S localhost:8000

Go to http://localhost:8000 in the browser. You should see a webpage similar to this:

A webpage with a form with two file inputs

When you choose files and click the Merge PDFs button, you’ll receive an error. This is because you haven’t yet written any code to handle the form submission.

Create a merge.php file in the same directory and add the following content to it:

<?php
$file1 = $_FILES['file1'];
$file2 = $_FILES['file2'];

echo $file1['name'], ", ", $file2['name'];
?>

Now when you go back to http://localhost:8000, choose the files, and submit the form, you should see the names of the files you picked printed on the screen:

A webpage with two file names

Merging PDFs

You can now use Processor’s API to merge the files uploaded from the browser. Replace the contents of the merge.php file with:

<?php
$file1 = $_FILES["file1"];
$file2 = $_FILES["file2"];

$headers = ["Content-Type" => "multipart/form-data"];
$postFields = [];
$postFields["file"] = curl_file_create(
    $file1["tmp_name"],
    $file1["type"],
    $file1["name"]
);

$postFields["file_to_import"] = curl_file_create(
    $file2["tmp_name"],
    $file2["type"],
    $file2["name"]
);

$postFields["operations"] = json_encode([
    "operations" => [
        [
            "type" => "importDocument",
            "document" => "file_to_import",
            "afterPageIndex" => "last",
        ],
    ],
]);

$request = curl_init();
curl_setopt($request, CURLOPT_URL, "http://localhost:5000/process");
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);

$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$file_size = curl_getinfo($request, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($request);

if ($status != 200) {
    echo "Request to Processor failed with status code " .
        $status .
        ': "' .
        $response .
        '".';
} else {
    header("Content-type: application/pdf");
    header('Content-Disposition: attachment; filename="result.pdf"');
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $file_size);
    header("Accept-Ranges: bytes");
    echo $response;
}
?>

Most of this code, up until you call curl_exec function, constructs a request that will be sent to Processor. Include an input file ("file"), a file you want to import ("file_to_import"), and a list of instructions for Processor so that it knows what to do with these files ("operations"). The operations you send tell Processor that it should import "file_to_import" after the last page of the input file ("file"). In your case, this means the second file will be appended to the first file.

The rest of the code deals with error handling, and if everything goes well, it returns the resulting file back to the browser.

You can check how it works in practice yourself! Go to http://localhost:8000, pick any two PDFs on your disk (or use these two if you don’t have any: file1.pdf, file2.pdf), and click Merge PDFs again. Depending on your browser, it will either automatically download the file for you or ask you for permission to download. In any case, look for the result.pdf file in the downloads folder on your computer. Open that file in any PDF viewer application. If you used the two files from the links above, you should see a five-page PDF document like this:

The result merging document with a cover page

That’s it! Now you know how to use Processor from PHP to perform operations on documents.

This guide walks you through the steps necessary to start PSPDFKit Processor. It also shows you how to use it to process documents. By the end, you’ll be able to merge two PDF documents into one using Processor’s HTTP API from Python.

Requirements

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

Starting PSPDFKit Processor

First, open your 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.

Now run the following command:

docker run --rm -t pspdfkit/processor:latest

This command might take a while to run, depending on your internet connection speed. Wait until you see a message like this in the terminal:

[info]  2021-03-02 18:56:45.286  Running PSPDFKit Processor version 2021.1.0. pid=<0.1851.0>

The PSPDFKit Processor is now up and running!

Installing Python

The interaction with Processor happens via its HTTP API: You send documents and commands in the request and receive the resulting file in the response. To do this, you’ll invoke the API from the Python script. But first, you need to install Python for your operating system:

To install Python, first you need to install the Xcode Command Line Tools. Install them by running the following command:

xcode-select --install

The easiest way to install Python on macOS is via Homebrew. Follow the instructions on the Homebrew website to install it. Then, to install Python, run:

brew install python

Verify the installation by running the following command in the terminal:

python3 --version

The output should start with Python 3.9 — you can ignore the rest of the message.

ℹ️ Note: ️If the output doesn’t match the above, try restarting the terminal app by typing exit and opening it again.

  1. Go to the Python downloads website.

  2. Scroll down to the bottom of the page until you find the Windows installer (64-bit) entry. Click on the link to download the installer.

  3. Open the installer. Make sure to check the Add Python 3.9 to PATH checkbox at the bottom of the window, and click Install Now.

  4. Complete the installation process.

Now start the terminal and run the python --version command. The output should start with Python 3.9 — you can ignore the rest of the message.

You can install Python using your distribution’s package manager:

apt-get update && apt-get install -y python3.9 python3-pip && ln -s /usr/bin/python3.9 /usr/bin/python3
dnf install -y python3 python3-pip

Now run the python3 --version command. The output should start with Python 3.9 — you can ignore the rest of the message.

Merging PDFs

To make HTTP requests to Processor’s API, you need an HTTP client library. For this scenario, you’ll use the excellent Requests package. Install it by running the following command:

python3 -m pip install requests==2.25.1
python -m pip install requests==2.25.1
python3 -m pip install requests==2.25.1

Now you can create a script to merge the PDFs. It’ll take two file paths as command-line arguments, send the files to Processor to merge them, and save the result in another file on disk. Create a merge.py file with the following content:

import sys
import json
import requests

if len(sys.argv) < 3:
    print("Too few arguments.")
    exit(1)

file1 = sys.argv[1]
file2 = sys.argv[2]

parts = {
    "file": open(file1, "rb"),
    "file_to_import": ("file_to_import.pdf", open(file2, "rb"), "application/pdf"),
    "operations": json.dumps(
        {
            "operations": [
                {
                    "type": "importDocument",
                    "afterPageIndex": "last",
                    "document": "file_to_import",
                }
            ]
        }
    ),
}

response = requests.post("http://localhost:5000/process", files=parts)

if response.status_code == 200:
    with open("result.pdf", "wb") as f:
        f.write(response.content)
else:
    print(
        f"Request to Processor failed with status code {response.status_code}: '{response.text}'."
    )

First, the script verifies that the number of arguments is correct and prepares the request data. Include an input file ("file"), a file you want to import ("file_to_import"), and a list of instructions for Processor so that it knows what to do with these files ("operations"). The operations you send tell Processor that it should import "file_to_import" after the last page of the input file ("file"). In your case, this means file2 will be appended to file1.

The rest of the code deals with error handling, and if everything goes well, it saves the result in the result.pdf file in the current working directory.

You can check how it works in practice yourself! Pick any two PDFs on your computer (or use these two if you don’t have any: file1.pdf, file2.pdf), and run the script:

python3 merge.py path/to/file1.pdf path/to/file2.pdf
python merge.py path/to/file1.pdf path/to/file2.pdf
python3 merge.py path/to/file1.pdf path/to/file2.pdf

Make sure to replace path/to/file1.pdf and path/to/file2.pdf with the actual location of the PDF files on your computer.

If you used the two files from the links above, you should see a five-page PDF document like this:

The result merging document with a cover page

That’s it! Now you know how to use Processor from Python to perform operations on documents.

This guide walks you through the steps necessary to start PSPDFKit Processor. It also shows you how to use it to process documents. By the end, you’ll be able to merge two PDF documents into one using Processor’s HTTP API via curl.

Requirements

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

Starting PSPDFKit Processor

First, open your 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.

Now run the following command:

docker run --rm -t pspdfkit/processor:latest

This command might take a while to run, depending on your internet connection speed. Wait until you see a message like this in the terminal:

[info]  2021-03-02 18:56:45.286  Running PSPDFKit Processor version 2021.1.0. pid=<0.1851.0>

The PSPDFKit Processor is now up and running!

Installing curl

The interaction with Processor happens via its HTTP API: You send documents and commands in the request and receive the resulting file in the response. To do this, you’ll first install curl so that it can call the API.

curl is bundled with macOS, so there are no extra steps you need to take to install it.

  1. Go to the curl website and download the curl for 64 bit package.

  2. Create a folder anywhere on your C: drive. Unzip the downloaded package and copy the curl.exe executable from the bin subfolder into the folder you just created.

  3. Open the terminal and switch to the directory where you placed the curl executable:

cd C:\path\to\directory

Now run the .\curl.exe --version command. The output should start with curl 7 — you can ignore the rest of the message.

curl is bundled with most desktop Linux distributions. You can check if it’s installed by running the curl --version command in the terminal. If you get an error, you can install it using your distribution’s package manager:

apt-get update && apt-get install -y curl
dnf install -y curl

Now run the curl --version command. The output should start with curl 7 — you can ignore the rest of the message.

Merging PDFs

Now that everything is set up, you can start using Processor to merge PDFs. More specifically, you’ll add a cover page to the existing document.

Download the example files using the following links: document, cover page. Now move both files to the same directory (if you’re running on Windows, use the same folder where you placed the curl.exe executable), and run the following command to merge the PDFs:

curl -X POST http://localhost:5000/process \
  -F file=@document.pdf \
  -F 'cover-page=@cover.pdf;type=application/pdf' \
  -F operations='{
  "operations": [
    {
      "type": "importDocument",
      "beforePageIndex": "first",
      "document": "cover-page"
    }
  ]
}' \
  -o result.pdf
curl.exe -X POST http://localhost:5000/process `
  -F file=@document.pdf `
  -F 'cover-page=@cover.pdf;type=application/pdf' `
  -F operations='{
  ""operations"": [
    {
      ""type"": ""importDocument"",
      ""beforePageIndex"": ""first"",
      ""document"": ""cover-page""
    }
  ]
}' `
  -o result.pdf
curl -X POST http://localhost:5000/process \
  -F file=@document.pdf \
  -F 'cover-page=@cover.pdf;type=application/pdf' \
  -F operations='{
  "operations": [
    {
      "type": "importDocument",
      "beforePageIndex": "first",
      "document": "cover-page"
    }
  ]
}' \
  -o result.pdf

Open the result.pdf file in any PDF viewer — you should see a five-page PDF document like this:

The result merging document with a cover page

That’s it! Now you know how to use Processor to perform operations on documents.