How to Resize PDF Pages with JavaScript in NodeJS

Learn how to use JavaScript to resize PDF pages using Set Page Boxes API by pdfRest.
Share this page

Why Resize PDF Pages with JavaScript?

The pdfRest Set Page Boxes API Tool allows you to modify the page boxes of a PDF document, specifically the MediaBox, to control the physical dimensions of the pages. This tutorial will guide you through the process of sending an API call to the Set Page Boxes API Tool endpoint using JavaScript in a NodeJS environment to resize all pages of a PDF document.

Imagine you have a PDF document where all pages need to conform to a specific standard dimension for consistent display or processing. By using the Set Page Boxes API Tool and the "all" range, you can efficiently resize all PDF pages to meet your requirements in a single API call.

Resize PDF Pages with JavaScript Code Example

const fs = require('node:fs');
const FormData = require('form-data');
const axios = require('axios');

const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const pdfFilePath = '/path/to/your/file.pdf'; // Replace with the actual path to your PDF file
const outputName = 'resized_all_to_a4_out.pdf';
const pdfWithPageBoxesEndpointUrl = 'https://api.pdfrest.com/pdf-with-page-boxes-set';

// Define the MediaBox adjustments to resize all pages from Letter to A4
// Letter: 612 x 792 points
// A4:    595 x 842 points
const deltaWidthInward = (612 - 595) / 2;   // Positive margin to shrink width inward
const deltaHeightOutward = (792 - 842) / 2;  // Negative margin to expand height outward

const resizeBoxOptions = {
    boxes: [
        {
            box: 'media',
            pages: [
                {
                    range: 'all',
                    left: deltaWidthInward,
                    top: deltaHeightOutward,
                    bottom: deltaHeightOutward,
                    right: deltaWidthInward,
                },
            ],
        },
    ],
};

async function resizePdfPages() {
    try {
        const formData = new FormData();
        formData.append('file', fs.createReadStream(pdfFilePath));
        formData.append('boxes', JSON.stringify(resizeBoxOptions));
        formData.append('output', outputName.replace('.pdf', ''));

        const headers = {
            'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
            'Api-Key': apiKey,
        };

        console.log('Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4...');
        const response = await axios.post(pdfWithPageBoxesEndpointUrl, formData, { headers });

        console.log('Response status code:', response.status);

        if (response.data) {
            console.log('Response data:', JSON.stringify(response.data, null, 2));
        } else {
            console.log('Empty response data');
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
}

resizePdfPages();

Source: GitHub (Note: This example has been modified to focus on resizing all pages)

Breaking Down the Code for Resizing All Pages

The code starts by importing the necessary modules: fs for file system operations, form-data for creating multipart form data, and axios for making HTTP requests.

const fs = require('node:fs');
const FormData = require('form-data');
const axios = require('axios');

const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const pdfFilePath = '/path/to/your/file.pdf'; // Replace with the actual path to your PDF file
const outputName = 'resized_all_to_a4_out.pdf';
const pdfWithPageBoxesEndpointUrl = 'https://api.pdfrest.com/pdf-with-page-boxes-set';

This section defines the API key, input PDF file path, desired output file name, and the API endpoint URL. Remember to replace 'YOUR_API_KEY' with your actual pdfRest API key and '/path/to/your/file.pdf' with the correct path to your PDF file.

// Define the MediaBox adjustments to resize all pages from Letter to A4
// Letter: 612 x 792 points
// A4:    595 x 842 points
const deltaWidthInward = (612 - 595) / 2;   // Positive margin to shrink width inward
const deltaHeightOutward = (792 - 842) / 2;  // Negative margin to expand height outward

const resizeBoxOptions = {
    boxes: [
        {
            box: 'media',
            pages: [
                {
                    range: 'all',
                    left: deltaWidthInward,
                    top: deltaHeightOutward,
                    bottom: deltaHeightOutward,
                    right: deltaWidthInward,
                },
            ],
        },
    ],
};

The resizeBoxOptions object is configured to resize all PDF pages by adjusting the MediaBox. The box key is set to 'media'. Setting range to 'all' ensures these MediaBox adjustments are applied to every page. Positive deltaWidthInward values shrink the width, and positive deltaHeightOutward values expand the height relative to the top and bottom.

async function resizePdfPages() {
    try {
        const formData = new FormData();
        formData.append('file', fs.createReadStream(pdfFilePath));
        formData.append('boxes', JSON.stringify(resizeBoxOptions));
        formData.append('output', outputName.replace('.pdf', ''));

        const headers = {
            'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
            'Api-Key': apiKey,
        };

        console.log('Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4...');
        const response = await axios.post(pdfWithPageBoxesEndpointUrl, formData, { headers });

        console.log('Response status code:', response.status);

        if (response.data) {
            console.log('Response data:', JSON.stringify(response.data, null, 2));
        } else {
            console.log('Empty response data');
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
}

resizePdfPages();

This asynchronous function resizePdfPages creates a FormData object to send the PDF file and the JSON-encoded resizeBoxOptions. It then sets the necessary headers, including the Content-Type for multipart form data and your API key. Finally, it uses axios to send a POST request to the pdfRest API endpoint to resize all PDF pages and logs the response.

Next Steps for Resizing All PDF Pages

This tutorial demonstrated how to use JavaScript (NodeJS) and the pdfRest Set Page Boxes API Tool to resize all pages of a PDF from US Letter to A4 by setting the MediaBox with the range: 'all' option. You can adapt the deltaWidthInward and deltaHeightOutward calculations to resize to other dimensions. This approach efficiently applies the same resizing to every page in your document.

To learn more about the Set Page Boxes API Tool and its capabilities, including setting other page boxes and using different page ranges, you can demo all of the pdfRest API Tools in the API Lab and refer to the API Reference Guide for detailed documentation.

Note: This example uses a multipart API call. JSON payload examples for setting page boxes, including the MediaBox, can be found at GitHub.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.