Skip to content

PDF Compress — Go source

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

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

// pdf-compress — the lossless floor for Go with pdfcpu
// (github.com/pdfcpu/pdfcpu). Honest scope note: pdfcpu has no public API to
// decode + re-encode embedded JPEGs, so the Go equivalent of the TS two-pass
// compressor is pass 1 — metadata strip plus an optimize pass that rebuilds
// the file with object streams and prunes unused objects. The
// ChooseImageAction decision is ported verbatim so the JPEG walk can be
// added the moment pdfcpu (or a rasterizer) exposes it.
package pdfcompress

import (
	"bytes"
	"strings"

	"github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)

// PdfToolError mirrors the TS PdfToolError: Kind is 'encrypted' or 'invalid'.
type PdfToolError struct {
	Kind string // "encrypted" | "invalid"
	Msg  string
}

func (e *PdfToolError) Error() string { return e.Msg }

// ClassifyLoadError maps a raw pdfcpu failure to encrypted vs invalid — the
// same /encrypt|password/i heuristic the TS lib applies to the message.
func ClassifyLoadError(msg string) string {
	lower := strings.ToLower(msg)
	if strings.Contains(lower, "encrypt") || strings.Contains(lower, "password") {
		return "encrypted"
	}
	return "invalid"
}

func mapError(err error) error {
	kind := ClassifyLoadError(err.Error())
	msg := "Not a readable PDF file."
	if kind == "encrypted" {
		msg = "This PDF is password-protected. Unlock it first."
	}
	return &PdfToolError{Kind: kind, Msg: msg}
}

// ImageAccounting mirrors the TS per-image outcome type.
type ImageAccounting struct {
	Index   int
	Before  int
	After   int // -1 when the original was kept
	Skipped string // "grew" | "not-jpeg" | "decode-failed" | ""
}

// ChooseImageAction is the pure decision: only baseline single-stream JPEGs
// (/Filter /DCTDecode) are recompressible — anything else (Flate,
// multi-filter arrays, no filter) stays byte-for-byte intact. Ported
// verbatim from chooseImageAction() in src/lib/pdf-compress.ts.
func ChooseImageAction(filter string) string {
	if filter == "DCTDecode" {
		return "recompress"
	}
	return "skip"
}

// stripMetadata clears the Info dict — the lossless metadata strip the TS
// pass-1 floor performs via setTitle('')/setAuthor('')/....
func stripMetadata(ctx *model.Context) {
	if ctx.InfoDict == nil {
		return
	}
	empty := pdfcpu.StringLiteral("")
	ctx.InfoDict.Update(model.Dict{
		"Title":    empty,
		"Author":   empty,
		"Subject":  empty,
		"Keywords": empty,
		"Creator":  empty,
		"Producer": empty,
	})
}

// CompressPdf runs the pass-1 lossless floor: load (refusing encrypted
// inputs), strip metadata, then OptimizeContext re-saves with object
// streams. quality < 1 would enable the JPEG walk; the rasterizer-backed
// re-encode the TS canvas path performs has no clean pdfcpu equivalent, so
// the floor is what this snippet ships — see the scope note above.
func CompressPdf(data []byte, quality float64) ([]byte, error) {
	ctx, err := api.ReadValidateAndOptimize(bytes.NewReader(data), nil)
	if err != nil {
		return nil, mapError(err)
	}
	if ctx.Enc != nil {
		return nil, &PdfToolError{
			Kind: "encrypted",
			Msg:  "This PDF is password-protected. Unlock it first.",
		}
	}
	stripMetadata(ctx)
	var out bytes.Buffer
	if err := api.WriteContext(ctx, &out); err != nil {
		return nil, mapError(err)
	}
	return out.Bytes(), nil
}

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 →