Compress PDF using PHP

Compress and reduce a PDF file size by up to 90%

PDF

The Compress PDF PHP library by ConvertAPI is a tool that allows for the compression and reduction of PDF file sizes by up to 90%. This PHP library optimizes PDF quality by compressing text, graphics, images, subsetting fonts, and optimizing document structure. It offers various parameters for customization, including compression presets, color and grayscale image compression, and options to remove elements like bookmarks, annotations, forms, and embedded files from the PDF. The PHP library also provides options for optimizing the PDF for web viewing and preserving the PDF/A standard.

Try for FREE

File conversion library for PHP

ConvertAPI provides a PHP library that allows you to perform a Compress PDF conversion with just a few lines of code. Compress PDF documents using PHP programming language with no effort at all!

Execute the following command in your project root:
composer require convertapi/convertapi-php

Or install it manually using ConvertApi autoloader:

Following extensions are required: curl & json
require_once('/path/to/convertapi-php/lib/ConvertApi/autoload.php');

How To Compress PDF using PHP?

You can Compress PDF in a few simple steps:

Compress PDF - complete code snippet for PHP

Once you have your authentication in place, simply copy-paste this pdf to compress conversion code snippet into your PHP project:

// Code snippet is using the ConvertAPI JavaScript Client: https://github.com/ConvertAPI/convertapi-js

// Code snippet is using the ConvertAPI Node.js Client: https://github.com/ConvertAPI/convertapi-nodejs

// Code snippet is using the ConvertAPI PHP Client: https://github.com/ConvertAPI/convertapi-php

// Code snippet is using the ConvertAPI Java Client: https://github.com/ConvertAPI/convertapi-java

// Code snippet is using the ConvertAPI C# Client: https://github.com/ConvertAPI/convertapi-dotnet

# Code snippet is using the ConvertAPI Ruby Client: https://github.com/ConvertAPI/convertapi-ruby

# Code snippet is using the ConvertAPI Python Client: https://github.com/ConvertAPI/convertapi-python

// Code snippet is using the ConvertAPI Go Client: https://github.com/ConvertAPI/convertapi-go

REM Code snippet is using the command line utility program: https://github.com/ConvertAPI/convertapi-cli

<!-- For conversions with the multiple file result please refer to this example: https://repl.it/@ConvertAPI/HTML-Form-with-multiple-file-result -->

Upload the file and see how it works

You can set up the advanced conversion parameters and test the conversion result online using our interactive demo tool. It will auto-generate the code snippet for you!


A detailed guide to compressing PDFs using PHP

PDF Compression became more important than ever in this digital document processing age. More and more digital documents are produced everyday which results in a bulky and space consuming PDF storage. ConvertAPI's PDF Compression tool allows you to shrink the PDF's size using PHP programming language up to 90% of the original without losing the visual quality of the document. In this article, we will explain how to use PHP programming language to compress your PDF documents for sharing or long-term storage.

Best PDF Compression library for PHP

ConvertAPI provides a large suite of PDF tools using a single library for PHP. Using this library you can convert, rotate, merge, split, watermark and encrypt/decrypt your PDFs easily. The compression feature allows you to customize the compression levels by compressing and re-encoding images, removing duplicate objects, restructuring the PDF, subsetting fonts and applying other techniques that we will discuss later in this article. In addition to that, you can safely compress the PDF/A-standardized documents without worrying about losing the PDF/A standard. You can also compress password-protected documents. Without further ado, let's jump straight into some code examples!

How to use PHP programming language to compress a PDF?

  1. Install the ConvertAPI library for PHP into your project
  2. Sign up for a free account and receive your API secret
  3. Set up the conversion using our interactive UI
  4. Copy-paste the generated code snippet into your project

1. SDK library installation

You can install the ConvertAPI library manually or using the composer (preferred method). If you have the Composer installed, simply use this command:

composer require convertapi/convertapi-php

Alternatively, if you wish to install it manually, you must require the ConvertAPI autoloader:

require_once('/path/to/convertapi-php/src/ConvertApi/autoload.php');

Please note that the library uses curl and json dependencies. Using Composer it will be handled automatically. If installing manually, please make sure that these extensions are installed.

2. Retrieve your API Secret

You need to get the API Secret key to start using the library. In order to do so, please sign up for a free account. Once signed up, you will find the API Secret Key in your account dashboard.

API Secret key

3. Set up the compression parameters

Once you have your library installed, let's get to the fun part. To compress a PDF file using PHP you don't need to code anything. Simply visit our interactive demo tool and set up the compression parameters using our friendly UI.

4. Copy-paste the code snippet into your project

Once you are happy with the compression result on our website, you will find an auto generated code snippet at the bottom! Your PDF compression in PHP programming language will look something like this:

ConvertApi::setApiSecret('your-api-secret');
$result = ConvertApi::convert('compress', [
        'File' => '/path/to/my_file.pdf',
        'ColorImageCompression' => 'jpx',
        'ColorImageQuality' => '70',
        'RemoveBookmarks' => 'true',
        'RemoveAnnotations' => 'true',
        'RemoveForms' => 'true',
        'RemovePageLabels' => 'true',
        'RemoveLayers' => 'true',
        'RemoveArticleThreads' => 'true',
        'UnembedBaseFonts' => 'true',
        'SubsetEmbeddedFonts' => 'true',
    ], 'pdf'
);
$result->saveFiles('/path/to/result/dir');

Advanced techniques

Using ConvertAPI you can compress your PDFs by passing a path to local file, the URL of a hosted file, or a file stream. Lets see some examples of these different approaches.

Convert a local file

The simplest and most straightforward way to pass a file to our converter is by specifying a path to your local file. It would look something like this:

ConvertApi::setApiSecret('your-api-secret');
$result = ConvertApi::convert('compress', [
        'File' => '/path/to/my_file.pdf',
    ], 'pdf'
);
$result->saveFiles('/path/to/result/dir');

Convert a remote file accessible via URL

Another useful feature is converting a remote file hosted on a server accessible via URL. An important thing to notice here is that the file must be publicly available and have appropriate headers set in the response: Content-Type: application/pdf. An example of a code snippet would look like this:

ConvertApi::setApiSecret('your-api-secret');
$result = ConvertApi::convert('compress', [
        'File' => 'https://cdn.convertapi.com/cara/testfiles/document-large.pdf',
    ], 'pdf'
);
$result->saveFiles('/path/to/result/dir');

Convert a file stream

Converting a file stream provides the best performance benefits. In order to convert a file stream, please use the following example:

$upload = new \ConvertApi\FileUpload($stream, 'test.txt');

$result = ConvertApi::convert('pdf', ['File' => $upload]);
$savedFiles = $result->saveFiles('/path/to/result/dir');

Conclusion

The number of digital documents has grown over the years. It is important to compress these documents properly for sharing and long-term storage. You can compress PDF documents using PHP programming language with no effort at all! Simply follow the steps described in this article and check out our code examples in the ConvertAPI PHP library on GitHub. If you still have questions, do not hesitate to contact our friendly customer support!

Advanced Compress PDF conversion parameters

Password String

Sets the password to open protected documents.

Presets Collection

Choose compression level from presets. If preset is selected all other compression options are ignored.

Values:   none text archive web ebook printer

ColorImageCompression Collection

Color image compression algorithm.

Values:   none jpg jpx zip

ColorImageQuality Integer

Color image compression quality. The parameter applies only to JPX and JPG compressions.

ColorImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the color image which in turn makes the file smaller.

ColorImageThresholdDpi Integer

Threshold in DPI to activate color images resampling. ColorImageDownsample property must be enabled.

ColorImageResampleDpi Integer

Color image resolution in DPI after Bicubic resampling. ColorImageDownsample property must be enabled.

GrayscaleImageCompression Collection

Grayscale image compression algorithm.

Values:   none jpg jpx zip

GrayscaleImageQuality Integer

Grayscale image compression quality. The parameter applies only to JPX and JPG compressions.

GrayscaleImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the grayscale image which in turn makes the file smaller.

GrayscaleImageThresholdDpi Integer

Threshold in DPI to activate grayscale images resampling. GrayscaleImageDownsample property must be enabled.

GrayscaleImageResampleDpi Integer

Grayscale image resolution in DPI after Bicubic resampling. GrayscaleImageDownsample property must be enabled.

MonochromeImageCompression Collection

Monochrome image compression algorithm.

Values:   none jbig2 jbig2l fax zip

MonochromeImageQuality Integer

Monochrome image compression quality. The parameter applies only to jbig2 and jbig2l compressions.

MonochromeImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the monochrome image which in turn makes the file smaller.

MonochromeImageThresholdDpi Integer

Threshold in DPI to activate Monochrome images resampling. MonochromeImageDownsample property must be enabled.

MonochromeImageResampleDpi Integer

Monochrome image resolution in DPI after Bicubic resampling. MonochromeImageDownsample property must be enabled.

RemoveBookmarks Bool

Remove bookmarks from the PDF file.

RemoveAnnotations Bool

Remove text annotations from the PDF file.

RemoveForms Bool

Remove PDF forms from the PDF file.

RemovePageLabels Bool

Remove page labels from the PDF file.

RemoveLayers Bool

Removes hidden layers and flatten visible ones.

RemoveArticleThreads Bool

Remove article threads from the PDF file.

RemoveTaggedInfo Bool

Remove tagged information from the PDF file.

RemovePageThumbnails Bool

Remove page thumbnails from the PDF file.

RemoveDuplicates Bool

Remove duplicate fonts and color profiles from the PDF file.

RemoveAlternateImages Bool

Removes alternate images and leave only the one for on-screen viewing.

RemoveNamedDestinations Bool

Remove named destinations from the PDF file.

RemoveEmbeddedFiles Bool

Remove embedded/attachments files from the PDF file.

RemovePieceInformation Bool

Remove piece information dictionaries like Adobe Illustrator or Photoshop private data.

UnembedBaseFonts Bool

Specifies whether to remove the base fonts from the PDF file.

SubsetEmbeddedFonts Bool

Output PDF should only contain font characters utilized in the original document, and any unused glyphs from all fonts in the document should be removed.

CreateObjectStreams Bool

Create object streams in the PDF file. An object stream represents a stream that contains a sequence of PDF objects. This allows a greater number of PDF objects to be compressed. Property compatible with Acrobat 6/PDF v1.5 and later.

Optimize Bool

Optimize page content streams in the PDF file.

LzwToFlate Bool

In streams that use LZW encoding, use Flate instead.

Linearize Bool

Linearize PDF file and optimize for fast Web View.

PreservePdfa Bool

Preserve the PDF/A standard in the PDF file.

Try Compress PDF for free!