Crop PDF pages

In this guide we will discover how you can use the Visual PDF API to trim pages of a document, adjust their visible area, size and margins.

Basic page cropping

To use the PDF page cropping tool, you will need to use a crop-pages task in a file processing pipeline.

The options parameter allows you to specify which pages you want to crop, based on their indexes.

    
      // Creating the form data for the pipeline
      const form = new FormData();

      form.append(
        'tasks',
        [
          {
            tool: 'crop-pages',
            // Cropping the first page with a box in position x=10 y=20, with a width of 300 and height of 200
            options: { pages: [{ page: 0, box: [10, 20, 300, 200] }] },
          },
        ],
      );
    
  

Different methodes are available to you to crop pages: crop box and margins.

Cropping with a crop box

This method allows you to directly indicate the new visible area of the pages, based on a position, a width and a height.

It is important to know that on a PDF document, the coordinates are calculated starting from the bottom left corner. To learn more, consult the guide on coordinates and sizes.

A crop box is always represented with the following format: [x, y, width, height].

There are 2 possible ways to indicate the crop box data:

  • absolute coordinates and dimensions: the data is expressed in absolute size (based on the size of the PDF as indicated in its metadata)
            
              // Cropping the first page with a box in position x=10 y=20, with a width of 300 and height of 200
              options: { pages: [{ page: 0, box: [10, 20, 300, 200] }] }
            
          
  • relative coordinates and dimensions: the data is expressed in relative size (percentage of the full page height and width). This method is especially useful when you do not know the dimensions of the document.
            
              // Cropping the first page with a box in position x=5% of page width, y=8% of page height, with a width of 50% and height of 60%
              options: { pages: [{ page: 0, box: ['5w', '8h', '50w', '60h'] }] }
            
          

It is possible to mix these two units as you wish.

Cropping with margins

The API allows you to crop a page by specifying a margin to apply to all edges of the page rather than having to do the calculations yourself.

Here also you can indicate the data in relative or absolute units.

    
      // Cropping the first page specifying a margin
      options: { pages: [{ page: 0, margin: 10 }] }
    
  

You can specify a different margin for each edge of the page ([left, top, right, bottom]):

    
      // Cropping the first page specifying a margin for each edge
      options: { pages: [{ page: 0, margin: [10, 0, 10, 0] }] }