Getting Started with JavaScript

PSPDFKit API is offered as a simple HTTP API, so using it from JavaScript is as easy as making an HTTP request. The following will guide you through how to install the required dependencies, and it’ll show you how to make a request.

PSPDFKit API is designed to be used from a server and not a browser, so this guide will show you how to use Node.js and the axios HTTP library to use PSPDFKit API. Keep in mind that you can use any HTTP client you want; this example simply uses axios to demonstrate the principles of interacting with PSPDFKit API.

The first thing you need to do is to create a new Node.js app and install the dependencies.

For the npm init call, you can press return for all of the questions to accept their defaults:

Shell
npm init
npm install axios
npm install form-data

You’ll also need to add document.pdf and logo.png files to the root of your Node.js project (the same folder you’ll be creating the index.js file in). You can use the sample files provided by us — document.pdf and logo.png — or use your own.

Now that you have your dependencies and assets set up, you’re ready to start making requests to PSPDFKit API.

First, create an index.js file, which will contain your code to call PSPDFKit API. You can immediately import your dependencies as well:

JavaScript
const axios = require('axios')
const FormData = require('form-data')
const fs = require('fs')

Next, you’ll prepare the payload.

Preparing the Payload

You can create your FormData object, which contains the instructions and all the files sent to the API. You’ll start with the instructions object:

JavaScript
const formData = new FormData()
formData.append('instructions', JSON.stringify({
  parts: [
    {
      file: "document"
    }
  ],
  actions: [
    {
      type: "watermark",
      image: "company-logo",
      width: "50%"
    },
    {
      type: "watermark",
      text: "Property of PSPDFKit",
      width: 150,
      height: 20,
      left: 0,
      bottom: "100%"
    }
  ]
}))

Here, you add your instructions JSON to your FormData object. In this example, you’ll be adding an image watermark. For more details on the available options specifically related to watermarking, refer to our watermarking guide.

Next, you need to include your source assets, document.pdf and logo.png, with your request:

JavaScript
formData.append('document', fs.createReadStream('document.pdf'))
formData.append('company-logo', fs.createReadStream('logo.png'))

Now, you’ll make the request.

Making the Request

With your FormData object being populated, you can now send the actual request. Make sure to replace the your_api_key_here placeholder with your actual API key if it hasn’t yet been replaced:

JavaScript
axios.post('https://api.pspdfkit.com/build', formData, {
  headers: formData.getHeaders({
    'Authorization': 'Bearer your_api_key_here'
  }),
  responseType: "stream"
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream("result.pdf"))
  })
  .catch(async function (e) {
    console.log(e)
    const errorString = await streamToString(e.response.data)
    console.log(errorString)
  })

function streamToString(stream) {
  const chunks = []
  return new Promise((resolve, reject) => {
    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)))
    stream.on("error", (err) => reject(err))
    stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")))
  })
}

Here, you’re setting the responseType to stream to make sure that the resulting PDF isn’t loaded entirely into memory. You also write the final result to result.pdf. And with that, you’re done. You can now run your code using node index.js, and result.pdf should be created.

While this example made use of our watermarking API, this same approach can be used for all our available tools.

ℹ️ Note: streamToString only exists to format any errors you might receive, as you can’t print the stream directly.

Full Code

For your convenience, here’s the whole code. Just copy it and run it:

JavaScript
const axios = require('axios')
const FormData = require('form-data')
const fs = require('fs')

const formData = new FormData()
formData.append('instructions', JSON.stringify({
  parts: [
    {
      file: "document"
    }
  ],
  actions: [
    {
      type: "watermark",
      image: "company-logo",
      width: "50%"
    },
    {
      type: "watermark",
      text: "Property of PSPDFKit",
      width: 150,
      height: 20,
      left: 0,
      bottom: "100%"
    }
  ]
}))

formData.append('document', fs.createReadStream('document.pdf'))
formData.append('company-logo', fs.createReadStream('logo.png'))

axios.post('https://api.pspdfkit.com/build', formData, {
  headers: formData.getHeaders({
    'Authorization': 'Bearer your_api_key_here'
  }),
  responseType: "stream"
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream("result.pdf"))
  })
  .catch(async function (e) {
    console.log(e)
    const errorString = await streamToString(e.response.data)
    console.log(errorString)
  })

function streamToString(stream) {
  const chunks = []
  return new Promise((resolve, reject) => {
    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)))
    stream.on("error", (err) => reject(err))
    stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")))
  })
}