To compress a PDF without losing quality, first rewrite it losslessly (with qpdf: --object-streams=generate --recompress-flate --compression-level=9), which shrinks the file without changing a single pixel or glyph. If that is not enough, the remaining weight is almost always images, and the only way to shrink those is to downsample them to the resolution you actually need and re-encode them, which is lossy but invisible when you pick the right target (around 150 ppi for screens, 300 ppi for print). Ghostscript's -dPDFSETTINGS presets do this for you, but they change more than you might expect, so it pays to know what each one does.

I tested the lossless and image steps below on a deliberately bloated 40-page file built with ReportLab, using pikepdf (which wraps the qpdf library, version 12.4.2) and Pillow. Ghostscript itself was not available in my test environment, so its commands come straight from the Ghostscript 10.x pdfwrite documentation rather than from my own runs; check them against a sample file before you batch-process anything.

What Makes a PDF File Large

A PDF is a container of objects: page content streams (the drawing instructions), fonts, images, and optional extras such as attachments and metadata. File size is almost never spread evenly between them. In order of how often they are the culprit:

  1. Images at far more resolution than the page needs. A 12-megapixel phone photo placed in a 6-inch-wide column is roughly 670 ppi; nobody can see past about 300.
  2. Images stored with the wrong compression. Photos saved as Flate (lossless, zip-style) instead of JPEG can be ten times larger. Scans of black-and-white text stored as full colour are the extreme case.
  3. Fully embedded fonts. Subsetting (embedding only the glyphs used) is the default in most tools, but some exporters embed whole fonts, and a full CJK font can be several megabytes.
  4. Embedded files and attachments, including the original spreadsheet or design file that some exporters tuck inside.
  5. Uncompressed or badly encoded structure. Uncompressed content streams, ASCII85 text encoding (which inflates binary data by 25%), and no object streams.
  6. Incremental saves. Editors that append changes leave old versions of objects in the file until it is fully rewritten.

Find out where the bytes are before compressing

Measure before choosing a tool. This short pikepdf script groups every stream in the file by type:

"""Show where the bytes in a PDF go: images, fonts, page content, embedded files, other."""
import sys
from collections import Counter
import pikepdf

pdf = pikepdf.open(sys.argv[1])
buckets = Counter()
images = []
for obj in pdf.objects:
    if not isinstance(obj, pikepdf.Stream):
        continue
    size = len(obj.read_raw_bytes())
    subtype = obj.get('/Subtype')
    typ = obj.get('/Type')
    if subtype == '/Image':
        buckets['images'] += size
        images.append((size, int(obj.Width), int(obj.Height), repr(obj.get('/Filter'))))
    elif typ == '/EmbeddedFile':
        buckets['embedded files'] += size
    elif any(k in obj for k in ('/Length1', '/Length2', '/Length3')) or subtype in ('/Type1C', '/CIDFontType0C', '/OpenType'):
        buckets['fonts'] += size
    elif typ == '/ObjStm':
        buckets['object streams'] += size
    else:
        buckets['content + other streams'] += size

for k, v in buckets.most_common():
    print(f'{k:<26}{v/1024:>10.0f} KiB')
for size, w, h, f in sorted(images, reverse=True)[:10]:
    print(f'  image {w}x{h} {f} {size/1024:.0f} KiB')

Install it with pip install pikepdf in a virtual environment (any of the tools in our uv vs conda vs pixi comparison will do). On my 21.3 MB test file it printed:

images                         20524 KiB
content + other streams          254 KiB
  image 3000x2000 pikepdf.Array([ "/ASCII85Decode", "/FlateDecode" ]) 20524 KiB

That one line tells you nearly everything: a single 3000×2000 photo, stored with Flate and wrapped in ASCII85, accounts for 96% of the file. On my test page it was placed 6.875 inches wide, which works out to about 436 ppi.

If you have Poppler installed, pdfimages -list file.pdf gives a similar per-image table and includes the effective x-ppi and y-ppi of each image as placed, which is the number you need for choosing a downsampling target. For a quick look at the producer application, PDF version and page count, our PDF metadata viewer shows them without installing anything.

Lossless PDF Compression With qpdf

qpdf never resamples images or alters content; it rewrites the file's structure. The qpdf manual's "Optimizing File Size" section lists the options that produce the smallest output qpdf can make. Leaving out the one lossy option (--optimize-images), the fully lossless command is:

qpdf --compress-streams=y \
     --decode-level=generalized \
     --recompress-flate \
     --compression-level=9 \
     --object-streams=generate \
     input.pdf output.pdf

What each flag does:

Flag Effect
--compress-streams=y Compress any streams left uncompressed
--decode-level=generalized Remove non-specialized filters such as ASCII85 and LZW, then recompress
--recompress-flate Re-run Flate on streams that are already Flate-compressed
--compression-level=9 Highest zlib level (qpdf otherwise uses the library default)
--object-streams=generate Pack objects into compressed object streams (PDF 1.5+)

The equivalent in Python, which is what I actually ran:

import sys
import pikepdf

src, dst = sys.argv[1], sys.argv[2]
pikepdf.settings.set_flate_compression_level(9)        # --compression-level=9
with pikepdf.open(src) as pdf:
    pdf.remove_unreferenced_resources()
    pdf.save(
        dst,
        compress_streams=True,                                      # --compress-streams=y
        stream_decode_level=pikepdf.StreamDecodeLevel.generalized,  # --decode-level=generalized
        recompress_flate=True,                                      # --recompress-flate
        object_stream_mode=pikepdf.ObjectStreamMode.generate,       # --object-streams=generate
    )

Result on the test file: 21,290,129 bytes down to 16,831,449, a 21% cut with zero quality change. The page content streams went from 254 KiB to 13 KiB, and the image lost its ASCII85 wrapper. To prove it was lossless I hashed the decoded pixels of every image before and after:

import hashlib, sys
import pikepdf
from pikepdf import PdfImage

def image_hashes(path):
    with pikepdf.open(path) as pdf:
        return [hashlib.sha256(PdfImage(img).as_pil_image().tobytes()).hexdigest()[:16]
                for page in pdf.pages for img in page.get_images().values()]

before, after = image_hashes(sys.argv[1]), image_hashes(sys.argv[2])
print('IDENTICAL' if before == after else 'CHANGED')

It printed IDENTICAL. That 21% is typical of what you should expect from the lossless pass: worthwhile on files from old or sloppy generators, close to nothing on PDFs already written by a modern exporter. qpdf can also use Zopfli for slightly smaller Flate output if it was built with it; the manual quotes Zopfli's own figures of roughly 5% smaller and about 100 times slower.

--linearize (Ghostscript's equivalent is -dFastWebView) reorders the file so a browser can show page one before the download finishes. It is about perceived speed on the web, not size; Ghostscript's docs note it usually makes the file slightly larger.

Ghostscript -dPDFSETTINGS Presets Explained

Ghostscript's pdfwrite device does not edit your PDF; it interprets every page and writes a brand-new file. That is why it can downsample images and re-encode fonts, and also why it can change things you did not ask it to. The basic command:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.7 -dPDFSETTINGS=/ebook \
   -dNOPAUSE -dBATCH -dQUIET -sOutputFile=output.pdf input.pdf

These are the image and font values each preset sets, from the table in the pdfwrite documentation:

Setting /default /screen /ebook /printer /prepress
Downsample colour and grey images no yes yes no no
ColorImageResolution (ppi) 72 72 150 300 300
ColorImageDownsampleType /Subsample /Average /Average /Average /Bicubic
MonoImageResolution (ppi) 300 300 300 1200 1200
EmbedAllFonts true false true true true
CompatibilityLevel 1.7 1.5 1.5 1.7 1.7
ColorConversionStrategy LeaveColorUnchanged RGB RGB UseDeviceIndependentColor LeaveColorUnchanged

Three things in that table surprise most people:

  • /printer and /prepress do not downsample at all. Their 300 ppi resolution values only matter if you also turn downsampling on. If a /printer run makes your file smaller, it is from re-encoding and structure, not resolution.
  • /screen stops embedding all fonts and converts colour to RGB. Text set in a non-embedded font is then rendered with whatever substitute the viewer picks, so the document can look different on another machine.
  • /screen drops images to 72 ppi, which is visibly soft on any modern display. I almost never use it.

The documentation is unusually candid: it says /prepress "does not indicate the highest quality conversion", that every preset alters the input, and that the result closest to the original comes from not setting PDFSETTINGS at all. It recommends setting the individual controls when you have a specific goal.

Compress PDF Without Losing Visible Quality: Custom Ghostscript Settings

For a document that will be read on screens and occasionally printed, this is the command I would start from. It downsamples only images that are well above 200 ppi, uses bicubic resampling, and keeps line art and scanned text sharp:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.7 -dNOPAUSE -dBATCH -dQUIET \
   -dDownsampleColorImages=true -dColorImageResolution=200 \
   -dColorImageDownsampleType=/Bicubic -dColorImageDownsampleThreshold=1.5 \
   -dDownsampleGrayImages=true -dGrayImageResolution=200 \
   -dGrayImageDownsampleType=/Bicubic -dGrayImageDownsampleThreshold=1.5 \
   -dDownsampleMonoImages=true -dMonoImageResolution=600 \
   -dMonoImageDownsampleType=/Subsample \
   -sOutputFile=output.pdf input.pdf

The threshold of 1.5 means an image is only resampled when it exceeds 1.5 times the target, so at a 200 ppi target nothing at or below 300 ppi is touched. Ghostscript's default of PassThroughJPEGImages=true means existing JPEGs that are not being downsampled are copied as they are instead of being decoded and re-compressed, which avoids stacking a second round of JPEG artefacts.

JPEG quality is not a simple command-line flag in pdfwrite. It lives in the image dictionaries, which you set with PostScript passed through -c before the input file is named with -f. The documented dictionary used by the /printer preset is:

gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dQUIET -sOutputFile=output.pdf \
   -c "<< /ColorACSImageDict << /QFactor 0.4 /Blend 1 /ColorTransform 1 /HSamples [1 1 1 1] /VSamples [1 1 1 1] >> >> setdistillerparams" \
   -f input.pdf

Lower QFactor means higher quality and larger files; the default dictionary uses 0.9 with 2×2 chroma subsampling.

Image downsampling trade-offs

To see the shape of the trade-off, I downsampled my test file's 436 ppi image with Pillow (Lanczos) and saved it as JPEG at quality 85:

Version Image File size
Original 3000×2000, Flate + ASCII85 21.3 MB
Lossless rewrite 3000×2000, Flate 16.8 MB
300 ppi, JPEG q85 2062×1375 227 KB
150 ppi, JPEG q85 1031×687 46 KB

Treat those numbers as illustrative: my test image is a synthetic gradient with added noise, which Flate compresses badly and JPEG compresses well, so the gap is larger than you will see on many real files. The direction is universal, though. Once an image is stored at the wrong resolution and with the wrong codec, no amount of lossless tuning comes close to fixing it.

Choose the target by where the document ends up:

Destination Colour/grey target Black-and-white (mono) target
Screen reading, email attachments 150 ppi 300 ppi
Office printing 200–300 ppi 600 ppi
Commercial print Do not downsample; ask the printer Do not downsample
Archive of record Lossless pass only Lossless pass only

Compressing Scanned PDFs

Scanned PDFs are a special case because every page is a picture, so there is no text or vector content to protect. The biggest wins come from storing each page in the right colour mode:

  • Text-only scans should be bilevel (1-bit black and white). CCITT Group 4 or JBIG2 compression stores them far more compactly than colour or greyscale. Ghostscript's pdfwrite uses /CCITTFaxEncode for mono images by default.
  • Pages with photos or highlighter need greyscale or colour, but rarely above 200–300 ppi.

OCRmyPDF is the most practical tool for scans because it adds a searchable text layer and optimises at the same time. Its -O1 level is the default and aims for lossless improvements; -O2 and -O3 enable lossy optimisation and colour quantisation, and --jpeg-quality sets the JPEG target. JBIG2 needs an external encoder such as jbig2enc. If the PDFs feed a search index or a RAG pipeline, check OCR quality after compressing; heavy JPEG artefacts on small text hurt recognition, as we noted when comparing document parsers for RAG.

What Can Break When You Compress a PDF

  • Digital signatures. Any full rewrite invalidates a signature, because the signed bytes change. Compress before signing, never after.
  • PDF/A and PDF/X conformance. A Ghostscript rewrite does not produce PDF/A unless you request it explicitly, so archival files can silently lose their conformance claim.
  • Fonts. /screen does not embed all fonts. Check text rendering on a second machine.
  • Colour. /screen and /ebook convert to RGB, which matters for print-ready CMYK files.
  • Old viewers. Object streams need PDF 1.5. This mattered in 2005; it does not now, but some legacy document systems still choke.

How to Check the Results

  1. Compare sizes and structure. Re-run the weight script on the output, and run qpdf --check output.pdf to confirm the file is structurally valid.
  2. Verify the lossless claim with the pixel-hash script above whenever you only expected structural changes.
  3. Look at it. Zoom to 200% on the densest page (small text inside images, charts with thin lines) in two different viewers. Rendering a page to PNG at the same resolution from both files and flicking between them catches problems quickly.
  4. Search the text. If copy and search worked before, they must still work after.

If you do not want to install anything for a one-off file, our free PDF compressor offers four levels, from low (best quality) to maximum (smallest size). The same rule applies: start with the lowest level that gets you under your size limit and check the result. It is the same principle as minifying HTML: take every free, lossless saving first, and only then trade quality for bytes, on purpose.

Frequently Asked Questions

Can you really compress a PDF without losing any quality?

Yes, but only by how much the file's structure is wasteful. qpdf's lossless options (object streams, Flate recompression, removing ASCII85 wrappers) never change content. On files from modern exporters the saving is small; on old or poorly generated files it can be 20% or more. Large savings beyond that require downsampling images.

Which Ghostscript PDFSETTINGS is best for quality?

None of the presets is "best quality". Ghostscript's own docs say the closest result to the input comes from not setting PDFSETTINGS at all. For a good size-to-quality balance, /ebook (150 ppi) suits screen reading; for print, use custom settings with downsampling to 200–300 ppi.

Why is my PDF still large after compressing?

Usually because the weight is in images that the tool did not downsample (for example, /printer and /prepress do not downsample), in embedded attachments, or in fully embedded fonts. Measure where the bytes are first, then target that object type.

What DPI should I use when compressing a PDF?

150 ppi for documents read on screen or sent by email, 200–300 ppi for office printing, and 300–600 ppi for black-and-white scans of text. For commercial print, do not downsample without asking the printer.

Does compressing a PDF remove its digital signature?

Yes. Rewriting the file changes the signed bytes, so viewers will report the signature as invalid. Compress the document first and sign the final version.

Conclusion

Compressing a PDF without losing quality is a two-step decision. Take the free, provably lossless saving with qpdf first, then measure what is left. If images dominate, downsample them deliberately to the resolution your readers need, using explicit Ghostscript settings rather than a preset you have not read, and verify the output by eye before you replace the original.