View all our code samples

Using Bent in Node

Bent is a functional programming-style HTTP client for Node.js with support for async/await syntax. It offers a simple and expressive API for making HTTP requests and handling responses using functional programming concepts.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Node:

const bent = require('bent')

const convert = async (apiKey, params, endpoint='pdf') => {
    if (!['pdf', 'png', 'jpg', 'webp'].includes(endpoint)) {
        throw new Error('Invalid endpoint')
    }

    const post = bent(`https://api.pdfshift.io/v3/convert/${endpoint}`, 'POST', 'json', 200)

    const response = await post('', params, {'Authorization': 'Basic ' + Buffer.from('api:' + apiKey).toString('base64')});
    
    if ('filename' in params || 'webhook' in params) {
        return response;
    }
    
    const getBuffer = bent('buffer');
    const responseBuffer = await getBuffer(response.pdf.url);
    return responseBuffer;
}

Here's how you can use the above code:

const fs = require('fs');
convert('sk_XXXXXXXXXXXXXX', {'source': 'https://en.wikipedia.org/wiki/REST'})
    .then((binary) => {
        fs.writeFile('result.pdf', binary, 'binary', (err) => {
            if (err) throw err;
        })
    });

We've tested this code with the latest version of Bent and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.