Compressing PDFs on Linux: using QPDF and Ghostscript in a targeted way

On Linux, you can use a documented QPDF command in the terminal to optimize the structure of a PDF, or have Ghostscript pdfwrite rebuild it. Only checking the saved output shows whether the new file is smaller and can still do everything you need.

Structure optimization or rebuild: which tool fits?

The two programs take fundamentally different approaches. The QPDF command on this page leaves the content of your pages as it is and only saves the file's objects again, as compactly as possible. To do this, it bundles objects into object streams, for example, and recompresses Flate data. It neither downsamples images nor re-encodes them as JPEG. QPDF's optional image optimization is a separate, lossy step that the next section briefly explains. The QPDF documentation describes the individual options.

Ghostscript works differently. With the pdfwrite output device, it reads the PDF and creates a new file from the drawing instructions of each page. Text and vector graphics usually remain text and vector graphics, so the pages do not simply become images. Depending on the settings, however, Ghostscript can recalculate images. In addition, anything that is not part of the visible page image can change. The Ghostscript manual on pdfwrite explains this.

Some programs offer a third approach: they output each page again as an image. This usually loses native text, search and interactive elements. Neither of the two commands on this page works this way.

Three ways to reduce the size of a PDF and what they change in the document
MethodWhat happensImagesText and features
QPDF, structure optimizationObjects and Flate data are stored more compactlyNot downsampled. Optional JPEG re-encoding can cost detail.Page content is not rebuilt; check the result anyway
Ghostscript pdfwrite, rebuildPages are regenerated from their drawing instructionsCan be downsampled depending on the presetText and vectors are usually preserved. Links, forms and metadata can change.
Output pages as imagesEach page becomes an imageDepend on the chosen resolutionNative text, search and interactive elements are usually lost

None of these methods guarantees a smaller file. As a rule of thumb, if your PDF consists mainly of text and vector graphics, start with QPDF. The same applies if images, links or forms should change as little as possible. Ghostscript is an option if large photos or scans make up most of the file size and you can give up some image quality in return. The guide Compressing PDFs without quality loss explains what lossless and lossy mean in practice.

Graphical programs follow the same approaches. According to its own information, PDFsam distinguishes between pure structure optimization in the Basic edition and separate image compression in the Visual and Enhanced editions. Older guides for file manager scripts or interfaces that call Ghostscript in the background sometimes refer to earlier Ubuntu versions. For this reason, do not follow their installation steps without checking them first. According to the manufacturer, PDF24 Creator is only available for Windows and there is no Linux edition.

If you don't want to install anything, you can use the PDF compressor in the browser. It processes the file on your device without uploading it. However, we have not specifically tested it in Linux browsers. The guide Compressing PDFs without uploading explains how browser-local processing differs from true offline work.

Check the versions and write to a separate output file

The commands at a glance

Choose one of the six commands from this guide. You'll see the command unchanged and learn what each part stands for.

The commands come from the official QPDF and Ghostscript manuals. We haven't run them ourselves on Ubuntu or any other distribution. The versions installed on your system may differ from those covered in the online documentation.

This page doesn't run any commands or show terminal output. You'll only see what your system reports when you run a command yourself.

Show the QPDF version

Shows the installed QPDF version. Check it before you use the other commands.

Shows the installed QPDF version.
qpdf --version

You can also select and copy the command directly in the code box.

Parts of the command
qpdfProgram
Calls the QPDF command-line program.
--versionShow version
Prints the version of QPDF running on your system.

If the shell reports that the command wasn't found, QPDF probably isn't installed. The package name and installation depend on your distribution.

Section in the guide

Show the Ghostscript version and output devices

Shows the Ghostscript version and the available output devices.

Shows the Ghostscript version and the available output devices.
gs -h

You can also select and copy the command directly in the code box.

Parts of the command
gsProgram
Calls Ghostscript. On Unix, the program is called gs.
-hHelp
Prints the version, options, formats, available output devices and search path.

If the shell reports that the command wasn't found, Ghostscript probably isn't installed. Note your distribution and version so you can trace your results later.

Section in the guide

Save the structure more compactly

Saves the file's objects again, as compactly as possible. Images are neither downsampled nor re-encoded as JPEG.

QPDF command from the documentation: stores the structure more compactly without downsampling images or re-encoding them as JPEG.
qpdf "original.pdf" --object-streams=generate --compress-streams=y --decode-level=generalized --recompress-flate --compression-level=9 "optimiert-qpdf.pdf"

You can also select and copy the command directly in the code box.

Parts of the command
qpdfProgram
Calls the QPDF command-line program.
"original.pdf"Input file
The PDF that's read. The result goes into a separate file.
--object-streams=generateGenerate object streams
Groups suitable objects into object streams and compresses them. The output then has at least PDF version 1.5.
--compress-streams=yCompress streams
Compresses streams with Flate unless they're already compressed another way.
--decode-level=generalizedDecode general filters
Decodes data with supported general filters such as LZW, Flate, ASCII85 and ASCIIHex. JPEG data (DCT) isn't decoded.
--recompress-flateRecompress Flate
Decodes existing Flate streams and compresses them again. This can make writing take longer.
--compression-level=9Compression level
Selects the highest zlib level for Flate within the documented range of 1 to 9. Higher levels take more time. The value has nothing to do with JPEG quality.
"optimiert-qpdf.pdf"Output file
Name of the new file. In the two check commands, it's the input.

Only comparing the byte counts shows whether the new file is smaller. A separate output name doesn't stop you from overwriting an existing file with the same name, so choose a name that isn't in use yet. The command doesn't guarantee that a digital signature stays valid.

Section in the guide

Rebuild the PDF with pdfwrite

Ghostscript reads the PDF and creates a new file from each page's drawing instructions, here using the /ebook preset.

Ghostscript example with the /ebook preset. Image detail and document features can change in the process.
gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -sOutputFile="optimiert-gs.pdf" "original.pdf"

You can also select and copy the command directly in the code box.

Parts of the command
gsProgram
Calls Ghostscript.
-dSAFERAccess control
Restricts access to files and devices. This has been the default since version 9.50. It isn't a general security guarantee.
-dBATCHExit afterwards
Exits Ghostscript once the specified files have been processed, instead of switching to interactive mode.
-dNOPAUSENo pause
Suppresses the prompt and pause at the end of each page.
-sDEVICE=pdfwriteOutput device
Selects pdfwrite, which creates a new PDF. Text and vector graphics are usually preserved. Anything that isn't part of the visible page image can change.
-dPDFSETTINGS=/ebookPreset
Sets a bundle of individual parameters with medium image resolution. The name describes a use case, not a quality level or a guaranteed saving.
-sOutputFile="optimiert-gs.pdf"Output file
Sets the name of the new file.
"original.pdf"Input file
The PDF that Ghostscript reads.

Image details and document features can change, even if the pages look the same. No specific size or quality is promised. Check the saved output and choose an output name that isn't in use yet.

Section in the guide

Check the output's structure

Checks the syntax of the saved output. For the Ghostscript result, replace the file name.

Checks the syntax of the saved output. For the Ghostscript result, replace the file name.
qpdf "optimiert-qpdf.pdf" --check

You can also select and copy the command directly in the code box.

Parts of the command
qpdfProgram
Calls the QPDF command-line program.
"optimiert-qpdf.pdf"File to check
The previously saved output of the QPDF command.
--checkCheck structure
Checks the structure, encryption, linearization and stream encoding.

An exit code of 0 means the check found no errors, 2 means errors, 3 means warnings. The check only covers the file's structure. It doesn't show whether the file looks right, whether forms and links work, or whether it's safe.

Section in the guide

Print the page count

Prints the page count of the saved output. Run the command again with the name of the original and compare the two numbers.

Outputs the page count of the saved output. Run the command again with the name of the original and compare the results.
qpdf "optimiert-qpdf.pdf" --show-npages

You can also select and copy the command directly in the code box.

Parts of the command
qpdfProgram
Calls the QPDF command-line program.
"optimiert-qpdf.pdf"File to count
The previously saved output of the QPDF command.
--show-npagesCount pages
Prints the number of pages in the specified file.

The same page count doesn't mean the content, images and features are unchanged. Look at the pages yourself.

Section in the guide

The button only writes the displayed command to the clipboard after you click it. It doesn't read the clipboard, save anything or send anything.

The commands on this page come from the official manuals of QPDF and Ghostscript. We have not run them ourselves on Ubuntu or any other distribution, so this is not a tested Ubuntu guide. First, check which versions are installed on your system. The packages of your distribution may differ from the state described in the current online documentation.

Show the installed versions

Shows the installed QPDF version.
qpdf --version
Shows the Ghostscript version and the available output devices.
gs -h

If the shell reports that a command was not found, the program is probably not installed. The name of the package and how you install it depend on your distribution. Write down your distribution and versions so that you can trace a result later.

Ground rules for every attempt

  • Leave the original untouched. Input and output always get different file names.
  • Give each output a new name that you haven't used before, so that you don't overwrite an earlier file.
  • Start each further attempt from the original again, not from the result of the previous run.
  • Don't use options or scripts that replace the input file directly.

QPDF: optimize the storage structure

QPDF command from the documentation: stores the structure more compactly without downsampling images or re-encoding them as JPEG.
qpdf "original.pdf" --object-streams=generate --compress-streams=y --decode-level=generalized --recompress-flate --compression-level=9 "optimiert-qpdf.pdf"

The command reads original.pdf and writes a new file named optimiert-qpdf.pdf. The options bundle objects into object streams, compress data streams and recompress Flate data at the highest level. Recalculating images is not part of this. Object streams require PDF 1.5. If a recipient explicitly requires an older PDF version, this command is not suitable without changes.

QPDF can also optimize images and re-encode JPEG data at a selectable quality. The option for JPEG quality is available from version 12.1. Both are lossy and can further degrade JPEG images that are already compressed. Only use them if you check the images carefully afterwards.

Ghostscript: rewrite a PDF with a preset

Ghostscript example with the /ebook preset. Image detail and document features can change in the process.
gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -sOutputFile="optimiert-gs.pdf" "original.pdf"

-sDEVICE=pdfwrite selects PDF output, -sOutputFile sets the name of the new file, and the input file goes at the end. -dBATCH and -dNOPAUSE prevent Ghostscript from waiting for input. -dSAFER also appears in this form in the examples of the Ghostscript command-line guide. The /ebook preset is only a starting point and not a recommendation for every file.

Understanding Ghostscript presets correctly

With -dPDFSETTINGS, you select a whole bundle of individual parameters at once. The name of a preset describes a use case. It does not stand for a quality level or for a particular saving.

Presets for -dPDFSETTINGS according to the current Ghostscript manual (as of 10.09.0). Your installed version may differ.
PresetIntended purposeDownsampling of color and grayscale images
/screenScreen viewing, low resolutionActive. Target value 72 dpi, only for images above 1.5 times that value.
/ebookMedium resolutionActive. Target value 150 dpi, only for images above 1.5 times that value.
/printerPrintingNot enabled by default
/prepressPrepressNot enabled by default. Not automatically the most faithful choice.
/defaultGeneral useNot enabled by default

Is /prepress the best quality, then? No. The manual explicitly points out that /prepress is not the most faithful setting. Without -dPDFSETTINGS, the result may stay closer to the original. /prepress is not guaranteed to produce the smallest file either.

The target values for /screen and /ebook do not mean that every image will be exactly 72 or 150 dpi afterwards. Images below the threshold are not downsampled and keep their resolution. This does not necessarily mean that they stay completely unchanged, because the other parameters of the preset, for example for image encoding or colors, can still change them. The -r option is not a substitute for downsampling. It only controls the resolution when Ghostscript has to render parts as a fallback, and it does not shrink embedded images. According to the manual, it is often better to set individual parameters specifically than to rely on a preset.

Don't use one preset for all files. A text document, a photo catalog and a scan respond differently. With scans, it's best to start when you scan the document. The guide Reducing the size of scanned PDFs explains how.

Check text, links, forms and signatures

A PDF that looks the same after compression does not prove that everything stored in it was preserved. Ghostscript rebuilds the file. According to Ghostscript's explanation of PDF optimization, an identical appearance can hide changed instructions and metadata. After using QPDF as well, check the features that matter to you:

  • Select and copy text, and try the search.
  • Click links and bookmarks.
  • If the file is a form, fill in form fields and save them as a test.
  • Check details such as title or author if a recipient evaluates them.
  • If a particular standard such as PDF/A is required, check it with a tool designed for this purpose. None of the commands on this page guarantees this status.

Digitally signed PDFs

Neither of the two commands can guarantee that a digital signature is still valid after the file is rewritten. Compression is therefore not a way to reduce the size of a signed PDF. Keep the signed original unchanged. If someone else signed the document and you need a smaller version, get the unsigned source file or talk to the signer. Agree on any new signature with the issuer or recipient. Adobe on limitations of signed PDFs provides background information. A scanned, visible handwritten signature is not a digital signature.

Removing password protection or editing restrictions is not part of reducing file size, and this page provides no commands for it. Instead, ask the sender for a suitable version. The guide Understanding signatures and forms explains more about handling such documents.

Compare the result size and keep the original

A command that runs without an error message does not tell you anything about the result. Compare the exact size of the original and the output file in bytes, not just rounded figures in MB. Use the compression ratio calculator to calculate the percentage you saved.

Check syntax and page count

Checks the syntax of the saved output. For the Ghostscript result, replace the file name.
qpdf "optimiert-qpdf.pdf" --check

QPDF uses exit code 0 for a check without errors, 2 for errors and 3 for warnings. The check only covers the structure of the file. It does not tell you whether forms, links and images still work and look as they did before.

Outputs the page count of the saved output. Run the command again with the name of the original and compare the results.
qpdf "optimiert-qpdf.pdf" --show-npages

Check in a PDF viewer

  1. Open the saved output file again from its folder.
  2. Go through all pages and compare the page format and orientation with the original.
  3. Look at images, small print and fine lines at high magnification.
  4. Test search, links and forms as described in the previous section.
  5. If possible, also open the file in a second viewer.

Larger, unchanged or empty?

Ghostscript can also make a PDF larger. The file is rebuilt and encoded differently, and the new instructions sometimes need more space than the old ones. QPDF also has little to gain if the file is already stored compactly.

A larger or barely smaller result can still be a valid result. You can only tell whether it is valid by running the same checks on the saved file as on any other output, because size alone says nothing about errors or lost features. In the end, keep the file that is better suited. Often, that is simply the original. An empty, unreadable or corrupted output is different. It is a failed attempt and not particularly strong compression. Don't send this file. Read the messages in the terminal, then start again with the original and a new output name.

If the PDF is still too large for a recipient's limit, the guide PDF won't get smaller describes the next steps. In any case, keep the original until the new version has arrived and been accepted.

Privacy preferences

Choose which optional categories you allow. In this unpublished preview, optional analytics and advertising stay disabled even if you allow them. Document tools work either way, and you can change your choice anytime from the footer.

Necessary settings

Required

Remembers your privacy preference and theme setting in this browser. Document tools stay available whatever you choose for optional categories.

Currently inactive

Optional usage measurement. Currently inactive: allowing it saves your preference but does not turn on any analytics service in this preview.

Currently inactive

Optional advertising. Currently inactive: allowing it saves your preference but does not turn on any advertising service in this preview.

Optional analytics and advertising are disabled.