Skip to content

PDF Compress — C# source

Shrink PDF file sizes in your browser — lossless optimization plus a JPEG quality slider for embedded images. Nothing uploads.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// pdf-compress — two-pass PDF compression with PDFsharp. C# port (canonical
// TS: src/lib/pdf-compress.ts; Go twin: cli/pdf-compress): pass 1 strips
// document metadata and re-saves (the lossless floor); pass 2 would walk
// every page's image XObjects and re-encode baseline JPEGs (/Filter
// /DCTDecode) at a lower quality at identical pixel dimensions. PDFsharp
// exposes the object graph but ships no JPEG re-encoder, so pass 2 stays a
// documented extension point behind the verbatim ChooseImageAction
// decision.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

public static class PdfCompress
{
    /// Load failure kind: "encrypted" (password-protected) or "invalid"
    /// (unparseable) — the C# twin of the TS PdfToolError.code.
    public sealed class PdfToolException : Exception
    {
        public readonly string Code;

        public PdfToolException(string code, string message)
            : base(message)
        {
            Code = code;
        }
    }

    /// Per-image outcome: before/after stream sizes, or why the original
    /// stayed (After == null, Skipped = "grew" | "not-jpeg" |
    /// "decode-failed").
    public sealed class ImageAccounting
    {
        public int Index { get; init; }
        public int Before { get; init; }
        public int? After { get; init; }
        public string Skipped { get; init; }
    }

    private static readonly Regex EncryptOrPassword =
        new("encrypt|password", RegexOptions.IgnoreCase | RegexOptions.Compiled);

    /// Pure classifier — encrypted vs invalid, from the raw error message.
    /// Mirrors classifyLoadError() in src/lib/pdf-errors.ts; null (the TS
    /// undefined) classifies as invalid.
    public static string ClassifyLoadError(string msg) =>
        msg != null && EncryptOrPassword.IsMatch(msg) ? "encrypted" : "invalid";

    /// Map a thrown load/parse error to a user-facing PdfToolException.
    private static PdfToolException MapError(Exception e)
    {
        var kind = ClassifyLoadError(e.Message);
        return new PdfToolException(
            kind,
            kind == "encrypted"
                ? "This PDF is password-protected. Unlock it first."
                : "Not a readable PDF file.");
    }

    /// Pure decision: only baseline single-stream JPEGs (/Filter
    /// /DCTDecode) are recompressible — anything else (Flate, multi-filter
    /// chains, no filter) stays byte-for-byte intact. Ported verbatim from
    /// chooseImageAction() in src/lib/pdf-compress.ts.
    public static string ChooseImageAction(string filter) =>
        filter == "DCTDecode" ? "recompress" : "skip";

    /// Lossless metadata strip — the Info dict entries the TS pass-1 floor
    /// blanks via setTitle('')/setAuthor('')/....
    private static void StripMetadata(PdfDocument doc)
    {
        doc.Info.Title = "";
        doc.Info.Author = "";
        doc.Info.Subject = "";
        doc.Info.Keyword = "";
        doc.Info.Creator = "";
        doc.Info.Producer = "";
    }

    /// Pass 1 always runs (the lossless floor). Pass 2, only when
    /// quality < 1, would walk doc.Pages -> page.Elements.GetDictionary
    /// ("/Resources") -> "/XObject" and re-encode every /Image whose
    /// Filter is exactly /DCTDecode at `quality` — PDFsharp ships no JPEG
    /// re-encoder, so this port ships the floor plus the decision helper
    /// above. PdfReader.Open with PdfDocumentOpenMode.Modify refuses
    /// encrypted inputs the same way the TS load does
    /// (ignoreEncryption: false).
    public static byte[] CompressPdf(byte[] bytes, double quality)
    {
        var images = new List<ImageAccounting>(); // pass 2 not wired
        try
        {
            using var doc = PdfReader.Open(new MemoryStream(bytes), PdfDocumentOpenMode.Modify);
            StripMetadata(doc);
            if (quality < 1 && images.Count != 0)
                throw new InvalidOperationException("unreachable: pass 2 display stub");
            using var outMs = new MemoryStream();
            doc.Save(outMs, stream => { });
            return outMs.ToArray();
        }
        catch (PdfReaderException e)
        {
            throw MapError(e);
        }
        catch (InvalidOperationException)
        {
            throw;
        }
        catch (Exception e)
        {
            throw MapError(e);
        }
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →