Accessing Protected Files

To load a PDF from a URL, all you need to do is pass the URL to PSPDFKit’s load method. But what if you want to access a PDF protected by credentials?

Accessing an Authenticated PDF

Sometimes you want to restrict access to your PDFs so they are not publicly available on the internet. The easiest way to achieve this is with HTTP Basic Authentication.

If you try to load a PDF URL that is protected by HTTP Basic Authentication, PSPDFKit will ask you for a username and password. To avoid entering these, you can fetch the PDF yourself, passing the credentials as an Authorization header. Once you’ve received the response, the load method accepts the content as an ArrayBuffer:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
async function loadProtectedPDF(url, username, password) {
  // Base-64 encode your credentials and set them as an `Authorization` header.
  const headers = new Headers();
  const encodedCredentials = btoa(`${username}:${password}`);
  headers.set("Authorization", `Basic ${encodedCredentials}`);

  // Fetch the PDF and read the response as an `ArrayBuffer`.
  const pdfResponse = await fetch(url, { headers });
  const pdf = await pdfResponse.arrayBuffer();

  // Pass the `ArrayBuffer` as a PDF option instead of a URL.
  return PSPDFKit.load({ ...myOtherConfigOptions, pdf });
}

Accessing an Encrypted PDF

The easiest way to securely transfer your PDF is to serve it through HTTPS. This way, the browser will take care of decrypting the secured communication for you.

Additionally, you can encrypt the PDF’s content on the server using your own custom encryption. When you fetch the encrypted PDF, decrypt the data in the browser into an ArrayBuffer. Then pass it to PSPDFKit’s load method and it will render your document:

1
2
3
4
const instance = PSPDFKit.load({
  ...myOtherConfigOptions,
  pdf: myDecryptedArrayBuffer
});