Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Compress PDF: shrink pictures and streams while the PDF stays a PDF (#103)

KnifeLemon3525375ad88a
diff --git a/README.ko.md b/README.ko.md
index 75e2cac9..17844567 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -57,7 +57,7 @@
## 기능
- **커서 옆 도넛**: 키를 누른 채 파일을 끌어 형식 위에 놓으면 끝. 파일에 맞는 형식만 나와요.
-- **파일 종류마다 툴바**를 드래그로 배치하고, 품질·크기·DPI·PDF 페이지·동영상·오디오·저장 위치·파일 이름을
+- **파일 종류마다 툴바**를 드래그로 배치하고, 품질·크기·DPI·PDF 페이지와 압축·동영상·오디오·저장 위치·파일 이름을
프리셋으로 정해요.
- **여러 파일을 한 번에** 병렬로 변환해요. 여러 단계가 필요한 변환(HWP → HWPX → DOCX)도 알아서 찾아요.
- **자동 변환 폴더**에 들어온 파일을 바로 변환해요.
@@ -83,7 +83,7 @@
|---|---|
| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR 등; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등), DICOM, OpenEXR, HDR은 읽기 | 위 형식끼리(HEIC⁵), PDF, SVG(벡터화), 크기 조정, 흑백 |
| **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG, FODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹, SVG → EMF, WMF, ODG² |
-| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, SVG²; 합치기, 나누기, 페이지 범위 |
+| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, SVG²; 합치기, 나누기, 페이지 범위, 압축 (더 작은 PDF) |
| **문서**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² |
| **스프레드시트**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV · OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML · XLT, OTS² |
| **프레젠테이션**: PPTX, PPTM, POTX, PPSX · PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX · OTP² |
diff --git a/README.md b/README.md
index 08b5b981..f263d938 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
## Features
- **A donut at the cursor**: hold a key, drag files and drop them on a format. Only formats that fit the files appear.
-- **One toolbar per file type**, arranged by drag and drop, with presets for quality, size, DPI, PDF pages,
+- **One toolbar per file type**, arranged by drag and drop, with presets for quality, size, DPI, PDF pages and compression,
video and audio, output folder and file names.
- **Many files at once**, in parallel. Routes with several steps (HWP → HWPX → DOCX) are found automatically.
- **Watch folders** convert every file that lands in them.
@@ -83,7 +83,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
|---|---|
| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR read | any of these (HEIC⁵), PDF, SVG (traced), resized, grayscale |
| **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG, FODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹, SVG → EMF, WMF, ODG² |
-| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, SVG²; merge, split, page ranges |
+| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, SVG²; merge, split, page ranges, compress (smaller PDFs) |
| **Documents**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² |
| **Spreadsheets**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV · OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML · XLT, OTS² |
| **Presentations**: PPTX, PPTM, POTX, PPSX · PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX · OTP² |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 1760ad50..5179c4eb 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -57,7 +57,7 @@
## 功能
- **光标旁的圆环**,按住按键拖动文件,放到格式上即可。只显示适合这些文件的格式。
-- **每种文件类型一个工具栏**,拖放排列。质量、尺寸、DPI、PDF 页面、视频音频、保存位置和文件名都能用预设设置。
+- **每种文件类型一个工具栏**,拖放排列。质量、尺寸、DPI、PDF 页面和压缩、视频音频、保存位置和文件名都能用预设设置。
- **一次转换多个文件**,并行处理。需要多步的转换(HWP → HWPX → DOCX)会自动找到路线。
- **监视文件夹**,放入的文件自动转换。
- **其他方式** 右键菜单、键盘快捷键、拖放区域和 [`filee` 命令](#命令行)。
@@ -82,7 +82,7 @@
|---|---|
| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、APNG、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC、QOI、DDS、PCX、MNG、CUR 等;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)、DICOM、OpenEXR、HDR 仅读取 | 上述格式互转(HEIC⁵)、PDF、SVG(描摹)、缩放、灰度 |
| **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG、FODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、SVG → DXF/DWG、PDF → EPS/PS¹、SVG → EMF、WMF、ODG² |
-| **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ、SVG²;合并、拆分、页码范围 |
+| **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ、SVG²;合并、拆分、页码范围、压缩(更小的 PDF) |
| **文档**:DOCX、DOCM、DOTX、EML、Outlook MSG · DOC、ODT、FODT、OTT、RTF、WPS、WPD、Pages、ClarisWorks、MacWrite、T602 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML、MSG → EML · ODT、FODT、OTT² |
| **表格**:XLSX、XLSM、XLS、XLT、ODS、CSV、TSV · OTS、FODS、Numbers、ET² | PDF、XLSX、ODS、CSV、TSV、JSON、HWPX、HTML · XLT、OTS² |
| **演示文稿**:PPTX、PPTM、POTX、PPSX · PPT、ODP、OTP、FODP、Keynote² | PDF、PNG、JPG、DOCX、HWPX · OTP² |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index b6c6ca01..d9ed1142 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -8,7 +8,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, MNG, QOI, DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster, MIFF ↔ each other, and **APNG** (Filee's own reader and writer); HEIC (written with FFmpeg), XCF, camera RAW (LibRaw), DICOM (uncompressed ones by Filee's own reader), Photo CD, OpenEXR, Radiance HDR and EMF/WMF (Windows) read |
| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI → PDF |
| ICNS | built in | images → ICNS (16–1024 px), ICNS → images |
-| PDFsharp | built in (library) | images → PDF, merge, split, page ranges |
+| PDFsharp | built in (library) | images → PDF, merge, split, page ranges, **compression** (smaller PDFs, see below) |
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
@@ -28,7 +28,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT), Markdown and markup → PPTX slides |
-| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI → PDF (images through PDF and PDFium) |
+| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI → PDF (images through PDF and PDFium); smaller PDFs when a preset asks for it |
| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video (H.264, HEVC, AV1), video → animated GIF / APNG or a still frame, audio and subtitle extraction, audio ↔ audio (also APE, WavPack, TTA, DSD, DTS, ALAC, …), GIF, APNG and photos → MP4/WEBM/MOV, images → HEIC |
| Calibre | **optional download** (~216 MB, 660 MB on disk) | rare e-book formats: LIT, LRF, CHM, PDB, PML, RB, SNB, TCR, OEB → EPUB; EPUB → MOBI, AZW3, LIT, LRF, PDB, PML, RB, SNB, TCR |
@@ -374,6 +374,49 @@ it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine's
Password-protected PDFs fail with a clear message. Not converted: tables (their cells come out as paragraphs in
reading order), vector drawings on text pages, form fields and annotations other than links.
+## PDF compression
+
+"Compress PDF" (and any PDF → PDF preset with *Compress* set, also with a page range or one file per page) makes a
+PDF smaller while it stays a PDF, for e-mail attachments and upload limits. `Pdf/PdfCompressor.cs` does it with
+PDFsharp and Magick.NET; nothing has to be installed.
+
+| Level | Pictures scaled down to | JPEG quality |
+|---|---|---|
+| Smallest (`Screen`) | 72 dpi | 55 |
+| Balanced (`Ebook`, the preset's) | 150 dpi | 65 |
+| High quality (`Print`) | 300 dpi | 85 |
+
+- **Pictures**: `Pdf/PdfPictureUses.cs` follows the content streams of the pages, of the forms they draw and of
+ annotation appearances (`q`/`Q`/`cm`/`Do`) to find the largest size each picture is drawn at. A picture drawn at more
+ than 1.5 × the level's resolution is scaled down to it (as Ghostscript does); a picture whose drawing can't be
+ followed is taken as large as the page holds it, so it is never scaled down too far. Photos are saved as JPEG at the
+ level's quality, pictures with up to 256 colours (charts, screenshots, logos) losslessly (Flate with PNG
+ prediction). A JPEG that keeps its size is encoded again only when that saves at least 10 %. A picture is replaced
+ only when the result is smaller.
+- **Which pictures**: 8 bits per component, gray, RGB (also ICC-based and calibrated) and CMYK, stored as JPEG, Flate
+ (with or without PNG prediction), RunLength or uncompressed. CMYK JPEGs, 1-bit pictures and masks, indexed
+ (palette) pictures, spot colours, JPEG 2000, JBIG2, CCITT and pictures with a colour-key mask stay as they are.
+- **Transparency**: a soft mask is scaled with its picture and kept lossless, so transparent parts stay transparent.
+- **Duplicates**: a picture stored more than once with the same data (a logo embedded again on every page) is kept once.
+- **Everything else**: every stream is deflated at the highest level when that's smaller; page thumbnails and other
+ applications' private data (`PieceInfo`, such as Illustrator's editing data) are removed, as are unused objects.
+ When the preset doesn't keep metadata, the XMP metadata of pages and pictures goes too. The document's own XMP is
+ written afresh from its document information by PDFsharp, as for every PDF it saves.
+- **Unchanged**: text, fonts, vector drawings, links, bookmarks and form fields. The whole file is compressed as it
+ is; a page range or single pages are first copied into new PDFs, as without compression (which leaves bookmarks and
+ form fields behind), and so is a PDF locked only against changes.
+- **Never bigger**: when nothing gets smaller (a PDF of text only, one compressed before), the PDF is written as it was
+ and the toast (and `filee convert`) says that it couldn't be made smaller. Password-protected PDFs fail with the same
+ message as the other PDF conversions.
+- **Ghostscript** (optional, *Also try Ghostscript* in the preset): when it is installed, the PDF is also run through
+ `pdfwrite` with `-dPDFSETTINGS=/screen`, `/ebook` or `/printer` (the same 72, 150 and 300 dpi) and
+ `-dCompatibilityLevel=1.6`, and the smallest of the two results is kept; when Ghostscript fails, the built-in result
+ stands. It is off by default: Ghostscript rewrites the whole file (fonts are subset again, structure and form fields
+ may change), so it is the user's choice. It also writes object streams, which PDFsharp can't, and its JPEGs are
+ somewhat smaller at the Balanced level.
+- **Not done**: object streams (PDFsharp writes none), font subsetting or removal of unused glyphs, converting
+ colour to gray, flattening transparency or form fields, recompressing JBIG2/CCITT scans.
+
## Office Open XML variants
`Office/OoxmlConverter.cs` converts between the variants of a family (Word, Excel, PowerPoint) by copying the
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index df514816..1a502fbe 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -59,6 +59,7 @@
"error.no_route": "No engine can do this conversion",
"error.cannot_turn": "Rotate and flip work on images only",
"error.conversion_failed": "The engine reported an error",
+ "notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
"engine.reason.not_installed": "Not installed",
"engine.reason.error": "Error while checking",
@@ -66,7 +67,7 @@
"engine.reason.needs_package": "Needs {0}. Install it in Settings → Engines",
"engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, camera RAW and more.\nQuality, size and DPI follow your preset.",
"engine.pdfium.description": "Renders PDF pages to PNG, JPG and TIFF (also multi-page TIFF and GIF) at the preset's resolution.",
- "engine.pdfsharp.description": "Makes PDFs from images and merges, splits or cuts page ranges out of PDFs.",
+ "engine.pdfsharp.description": "Makes PDFs from images and merges, splits or cuts page ranges out of PDFs.\nAlso makes PDFs smaller by scaling down their pictures.",
"engine.rhwp.description": "Renders HWP/HWPX to PDF and converts HWP ↔ HWPX.\nIt also draws documents that reach PDF through HWPX (DOCX, XLSX, PPTX, e-books…).",
"engine.unhwp.description": "Extracts text, Markdown and HTML from HWP and HWPX.",
"engine.markdown.description": "Markdown → HTML and plain text.",
@@ -127,6 +128,7 @@
"preset.flip_vertical.short": "Vertical",
"preset.merge_pdf": "Merge PDF",
"preset.split_pdf": "Split PDF",
+ "preset.compress_pdf": "Compress PDF",
"preset.long_image": "Long image",
"preset.extract": "Extract",
"preset.zip_all": "One ZIP",
@@ -373,6 +375,15 @@
"presets.page_range": "Pages",
"presets.page_range_hint": "All pages, or e.g. 1-3, 5",
"presets.split": "One file per page",
+ "presets.pdf_compression": "Compress",
+ "presets.pdf_compression.None": "Don't compress",
+ "presets.pdf_compression.Screen": "Smallest (pictures at 72 dpi)",
+ "presets.pdf_compression.Ebook": "Balanced (pictures at 150 dpi)",
+ "presets.pdf_compression.Print": "High quality (pictures at 300 dpi)",
+ "presets.pdf_compression_hint": "Pictures are scaled down and saved as JPEG.\nText, fonts and drawings stay as they are.\nIf the result isn't smaller, the original is kept.",
+ "presets.pdf_ghostscript": "Also try Ghostscript (when installed)",
+ "presets.pdf_ghostscript_hint": "Often smaller, but it rewrites the whole file.\nThe smallest result is kept.",
+ "presets.pdf_keep_metadata": "Keep page and picture metadata (XMP)",
"presets.combine_pages_hint": "Puts all pages one under another in a single image.\nVery long results are scaled to the format's limit (JPG 65,500 px, WebP 16,383 px).",
"presets.combine_pages": "Stack the pages into one tall image (when a PDF is converted)",
"presets.trim_page_margins": "Cut the blank space above and below each page",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 911d0f3b..04db8b59 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -59,6 +59,7 @@
"error.no_route": "이 변환을 할 수 있는 엔진이 없어요",
"error.cannot_turn": "회전·반전은 이미지에만 할 수 있어요",
"error.conversion_failed": "엔진에서 오류가 발생했어요",
+ "notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
"engine.reason.not_installed": "설치되지 않음",
"engine.reason.error": "확인 중 오류",
@@ -66,7 +67,7 @@
"engine.reason.needs_package": "{0} 필요 (설정 → 변환 엔진에서 설치)",
"engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, 카메라 RAW 등 이미지를 변환해요.\n품질·크기·DPI는 프리셋대로 맞춰요.",
"engine.pdfium.description": "PDF 페이지를 PNG, JPG, TIFF(여러 페이지 TIFF·GIF 포함)로 프리셋 해상도에 맞춰 그려요.",
- "engine.pdfsharp.description": "이미지로 PDF를 만들고, PDF를 합치거나 나누거나 원하는 페이지만 잘라내요.",
+ "engine.pdfsharp.description": "이미지로 PDF를 만들고, PDF를 합치거나 나누거나 원하는 페이지만 잘라내요.\nPDF 속 이미지를 줄여 파일을 작게 만들기도 해요.",
"engine.rhwp.description": "HWP/HWPX를 PDF로 그리고, HWP ↔ HWPX를 바꿔요.\nHWPX를 거쳐 PDF가 되는 문서(DOCX, XLSX, PPTX, 전자책 등)도 그려요.",
"engine.unhwp.description": "HWP와 HWPX에서 텍스트, 마크다운, HTML을 뽑아내요.",
"engine.markdown.description": "마크다운 → HTML, 텍스트.",
@@ -127,6 +128,7 @@
"preset.flip_vertical.short": "상하",
"preset.merge_pdf": "PDF 병합",
"preset.split_pdf": "PDF 분할",
+ "preset.compress_pdf": "PDF 압축",
"preset.long_image": "긴 이미지",
"preset.extract": "압축 풀기",
"preset.zip_all": "ZIP 하나로",
@@ -373,6 +375,15 @@
"presets.page_range": "페이지",
"presets.page_range_hint": "전체, 또는 예: 1-3, 5",
"presets.split": "페이지마다 파일 하나",
+ "presets.pdf_compression": "압축",
+ "presets.pdf_compression.None": "압축 안 함",
+ "presets.pdf_compression.Screen": "가장 작게 (이미지 72 dpi)",
+ "presets.pdf_compression.Ebook": "균형 (이미지 150 dpi)",
+ "presets.pdf_compression.Print": "고화질 (이미지 300 dpi)",
+ "presets.pdf_compression_hint": "이미지를 줄이고 JPEG로 저장해요.\n글자, 글꼴, 도형은 그대로예요.\n결과가 더 작지 않으면 원본을 그대로 둬요.",
+ "presets.pdf_ghostscript": "Ghostscript로도 해 보기 (설치된 경우)",
+ "presets.pdf_ghostscript_hint": "더 작아질 때가 많지만 파일 전체를 다시 써요.\n가장 작은 결과를 남겨요.",
+ "presets.pdf_keep_metadata": "페이지·이미지 메타데이터(XMP) 유지",
"presets.combine_pages_hint": "모든 페이지를 위아래로 이어 이미지 한 장으로 만들어요.\n너무 길면 형식의 최대 높이에 맞게 줄여요(JPG 65,500px, WebP 16,383px).",
"presets.combine_pages": "모든 페이지를 세로로 이어 한 장으로 (PDF를 변환할 때)",
"presets.trim_page_margins": "페이지마다 위아래 빈 여백 잘라내기",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index d6f4f5b8..63091853 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -59,6 +59,7 @@
"error.no_route": "没有引擎可以完成此转换",
"error.cannot_turn": "只能旋转和翻转图片",
"error.conversion_failed": "转换引擎出错",
+ "notice.pdf_not_smaller": "无法再缩小,已原样复制",
"engine.reason.not_installed": "未安装",
"engine.reason.error": "检查时出错",
@@ -66,7 +67,7 @@
"engine.reason.needs_package": "需要 {0},请在“设置 → 转换引擎”中安装",
"engine.magick.description": "JPG、PNG、WEBP、AVIF、HEIC、TIFF、GIF、APNG、PSD、相机 RAW 等图片。\n质量、尺寸和 DPI 按预设处理。",
"engine.pdfium.description": "按预设分辨率将 PDF 页面渲染为 PNG、JPG、TIFF(也支持多页 TIFF 和 GIF)。",
- "engine.pdfsharp.description": "用图片生成 PDF,合并、拆分 PDF 或截取指定页码。",
+ "engine.pdfsharp.description": "用图片生成 PDF,合并、拆分 PDF 或截取指定页码。\n还能缩小 PDF 中的图片来减小文件。",
"engine.rhwp.description": "将 HWP/HWPX 渲染为 PDF,并在 HWP ↔ HWPX 之间转换。\n经 HWPX 转为 PDF 的文档(DOCX、XLSX、PPTX、电子书等)也由它渲染。",
"engine.unhwp.description": "从 HWP 和 HWPX 中提取文本、Markdown 和 HTML。",
"engine.markdown.description": "Markdown → HTML 和纯文本。",
@@ -127,6 +128,7 @@
"preset.flip_vertical.short": "垂直",
"preset.merge_pdf": "合并 PDF",
"preset.split_pdf": "拆分 PDF",
+ "preset.compress_pdf": "压缩 PDF",
"preset.long_image": "长图",
"preset.extract": "解压",
"preset.zip_all": "打包成一个 ZIP",
@@ -373,6 +375,15 @@
"presets.page_range": "页面",
"presets.page_range_hint": "全部,或如 1-3, 5",
"presets.split": "每页一个文件",
+ "presets.pdf_compression": "压缩",
+ "presets.pdf_compression.None": "不压缩",
+ "presets.pdf_compression.Screen": "最小(图片 72 dpi)",
+ "presets.pdf_compression.Ebook": "均衡(图片 150 dpi)",
+ "presets.pdf_compression.Print": "高质量(图片 300 dpi)",
+ "presets.pdf_compression_hint": "图片会缩小并存为 JPEG。\n文字、字体和图形保持不变。\n结果没有变小时保留原文件。",
+ "presets.pdf_ghostscript": "也试试 Ghostscript(已安装时)",
+ "presets.pdf_ghostscript_hint": "通常更小,但会重写整个文件。\n保留最小的结果。",
+ "presets.pdf_keep_metadata": "保留页面和图片元数据 (XMP)",
"presets.combine_pages_hint": "把所有页面上下相接,生成一张图片。\n过长时会缩小到该格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。",
"presets.combine_pages": "把所有页面上下拼成一张长图(转换 PDF 时)",
"presets.trim_page_margins": "裁掉每页上下的空白",
diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.cs
index 3044df29..f7f9f72c 100644
--- a/src/Filee.App/ViewModels/JobViewModel.cs
+++ b/src/Filee.App/ViewModels/JobViewModel.cs
@@ -41,6 +41,10 @@ public sealed partial class JobViewModel : ObservableObject
[ObservableProperty] private string? _errorDetails;
[ObservableProperty] private bool _canRetry;
+ /// <summary>Notes on files that converted (e.g. a PDF that couldn't be made smaller and was copied), one per line.</summary>
+ [ObservableProperty] private string? _notices;
+ [ObservableProperty] private bool _hasNotices;
+
/// <summary>Source files that failed.</summary>
public IEnumerable<string> FailedSources => Job.Files.Where(f => f.State == FileState.Failed).Select(f => f.SourcePath);
@@ -61,6 +65,11 @@ public sealed partial class JobViewModel : ObservableObject
failed.Select(f => $"{Path.GetFileName(f.SourcePath)} — {FailureText.Reason(_loc, f.ErrorKey, f.ErrorDetail)}"));
CanRetry = _retry is not null && !IsRunning && failed.Count > 0;
+ var noted = Job.Files.Where(f => f.State == FileState.Done && f.NoticeKey is not null).ToList();
+ HasNotices = noted.Count > 0;
+ Notices = noted.Count == 0 ? null : string.Join(Environment.NewLine,
+ noted.Select(f => $"{Path.GetFileName(f.SourcePath)} — {_loc[f.NoticeKey!]}"));
+
Status = Job.State switch
{
JobState.Completed when Job.Files.All(f => f.State == FileState.Skipped) => _loc["toast.skipped"],
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 45382072..6f555339 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -63,6 +63,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
Rotations = Enum.GetValues<ImageRotation>().Select(v => new Choice<ImageRotation>(v, loc[$"presets.rotation.{v}"])).ToList();
Flips = Enum.GetValues<ImageFlip>().Select(v => new Choice<ImageFlip>(v, loc[$"presets.flip.{v}"])).ToList();
PageSizes = Enum.GetValues<PdfPageSize>().Select(v => new Choice<PdfPageSize>(v, loc[$"presets.page_size.{v}"])).ToList();
+ CompressionLevels = Enum.GetValues<PdfCompression>().Select(v => new Choice<PdfCompression>(v, loc[$"presets.pdf_compression.{v}"])).ToList();
Locations = Enum.GetValues<OutputLocation>().Select(v => new Choice<OutputLocation>(v, loc[$"presets.location.{v}"])).ToList();
Conflicts = Enum.GetValues<ConflictPolicy>().Select(v => new Choice<ConflictPolicy>(v, loc[$"presets.conflict.{v}"])).ToList();
TiffCompressions = Enum.GetValues<TiffCompression>().Select(v => new Choice<TiffCompression>(v, v.ToString().ToUpperInvariant())).ToList();
@@ -82,6 +83,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_rotation = Rotations.FirstOrDefault(r => r.Value == _edit.Image.Rotation) ?? Rotations[0];
_flip = Flips.FirstOrDefault(f => f.Value == _edit.Image.Flip) ?? Flips[0];
_pageSize = PageSizes.First(p => p.Value == _edit.Pdf.PageSize);
+ _compressionLevel = CompressionLevels.FirstOrDefault(c => c.Value == _edit.Pdf.Compression) ?? CompressionLevels[0];
+ _compressWithGhostscript = _edit.Pdf.CompressWithGhostscript;
_location = Locations.First(l => l.Value == _edit.Output.Location);
_conflict = Conflicts.First(c => c.Value == _edit.Output.Conflict);
_tiffCompression = TiffCompressions.First(t => t.Value == _edit.Image.TiffCompression);
@@ -139,6 +142,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public IReadOnlyList<Choice<ImageRotation>> Rotations { get; }
public IReadOnlyList<Choice<ImageFlip>> Flips { get; }
public IReadOnlyList<Choice<PdfPageSize>> PageSizes { get; }
+
+ /// <summary>PDF → PDF: don't compress, or the level (pictures at 72, 150 or 300 dpi).</summary>
+ public IReadOnlyList<Choice<PdfCompression>> CompressionLevels { get; }
public IReadOnlyList<Choice<OutputLocation>> Locations { get; }
public IReadOnlyList<Choice<ConflictPolicy>> Conflicts { get; }
public IReadOnlyList<Choice<TiffCompression>> TiffCompressions { get; }
@@ -157,6 +163,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowTurnForPdf), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco),
nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
+ nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec),
nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec),
@@ -265,6 +272,11 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private string _pageRange;
[ObservableProperty] private bool _splitPages;
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPdfCompressionOptions))]
+ private Choice<PdfCompression> _compressionLevel;
+
+ [ObservableProperty] private bool _compressWithGhostscript;
+
/// <summary>PDF → image: one tall image of all pages.</summary>
[ObservableProperty] private bool _combinePages;
[ObservableProperty] private bool _trimPageMargins;
@@ -314,6 +326,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowPdfBuild => TargetId == "pdf";
public bool ShowPdfSplit => TargetId == "pdf";
+ /// <summary>Compression is for PDF → PDF; Ghostscript and metadata only matter while it is on.</summary>
+ public bool ShowPdfCompression => TargetId == "pdf";
+ public bool ShowPdfCompressionOptions => ShowPdfCompression && CompressionLevel.Value != PdfCompression.None;
+
/// <summary>PDF → a single-image format: the pages can be stacked into one tall image (TIFF, GIF, APNG and MNG keep pages).</summary>
public bool ShowPdfCombine => TargetCategory == FormatCategory.Image
&& TargetId is not ("tiff" or "gif" or "apng" or "mng" or "ico" or "cur" or "icns" or "svg" or "pdf");
@@ -401,6 +417,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
pdf.CombinePages = CombinePages;
pdf.TrimPageMargins = TrimPageMargins;
pdf.SplitTallImage = SplitTallImage;
+ pdf.Compression = CompressionLevel.Value;
+ pdf.CompressWithGhostscript = CompressWithGhostscript;
_original.Document.PdfA = PdfA;
var media = _original.Media;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 01686024..7d6c9900 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -216,6 +216,21 @@
<TextBlock Classes="h2" Text="{DynamicResource presets.group.pdf}" />
<CheckBox Content="{DynamicResource presets.merge}" IsChecked="{Binding Merge}" IsVisible="{Binding ShowPdfBuild}" />
<CheckBox Content="{DynamicResource presets.split}" IsChecked="{Binding SplitPages}" IsVisible="{Binding ShowPdfSplit}" />
+ <!-- PDF → PDF: make the file smaller -->
+ <StackPanel Spacing="2" IsVisible="{Binding ShowPdfCompression}">
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.pdf_compression}" />
+ <ComboBox ItemsSource="{Binding CompressionLevels}" SelectedItem="{Binding CompressionLevel}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ </Grid>
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource presets.pdf_compression_hint}" />
+ <StackPanel Spacing="2" Margin="0,6,0,0" IsVisible="{Binding ShowPdfCompressionOptions}">
+ <CheckBox Content="{DynamicResource presets.pdf_ghostscript}" IsChecked="{Binding CompressWithGhostscript}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.pdf_ghostscript_hint}" />
+ <CheckBox Content="{DynamicResource presets.pdf_keep_metadata}" IsChecked="{Binding KeepMetadata}" />
+ </StackPanel>
+ </StackPanel>
<StackPanel Spacing="2" IsVisible="{Binding ShowPdfCombine}">
<CheckBox Content="{DynamicResource presets.combine_pages}" IsChecked="{Binding CombinePages}" />
<TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.combine_pages_hint}" />
diff --git a/src/Filee.App/Views/ToastWindow.axaml b/src/Filee.App/Views/ToastWindow.axaml
index 390c9f91..c0ac3544 100644
--- a/src/Filee.App/Views/ToastWindow.axaml
+++ b/src/Filee.App/Views/ToastWindow.axaml
@@ -83,6 +83,8 @@
</DockPanel>
<TextBlock Classes="caption danger" Text="{Binding ErrorDetails}" TextWrapping="Wrap" MaxLines="4"
IsVisible="{Binding HasErrors}" />
+ <TextBlock Classes="caption" Text="{Binding Notices}" TextWrapping="Wrap" MaxLines="4"
+ IsVisible="{Binding HasNotices}" />
</StackPanel>
</Border>
</DataTemplate>
diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs
index 1e8c94a6..23e928ce 100644
--- a/src/Filee.Cli/Cli.cs
+++ b/src/Filee.Cli/Cli.cs
@@ -152,7 +152,8 @@ internal static class Cli
var source = Shorten(file.SourcePath);
return file.State switch
{
- FileState.Done => $"ok {source} -> {string.Join(", ", file.Outputs.Select(Shorten))}",
+ FileState.Done => $"ok {source} -> {string.Join(", ", file.Outputs.Select(Shorten))}"
+ + (file.NoticeKey is null ? "" : $" ({texts[file.NoticeKey]})"),
FileState.Skipped => $"skip {source} (the output file already exists)",
FileState.Cancelled => $"stop {source} (cancelled)",
_ => $"fail {source}: {Error(file, texts)}",
@@ -195,6 +196,8 @@ internal static class Cli
json.WriteEndArray();
if (file.State is FileState.Failed or FileState.Cancelled)
json.WriteString("error", Error(file, texts));
+ else if (file.NoticeKey is not null)
+ json.WriteString("notice", texts[file.NoticeKey]);
json.WriteEndObject();
}
json.WriteEndArray();
diff --git a/src/Filee.Core/Conversion/ConversionJob.cs b/src/Filee.Core/Conversion/ConversionJob.cs
index 7ef352c3..fcd1f06c 100644
--- a/src/Filee.Core/Conversion/ConversionJob.cs
+++ b/src/Filee.Core/Conversion/ConversionJob.cs
@@ -37,6 +37,12 @@ public sealed class FileResult
/// <summary>Raw error detail for logs / tooltips.</summary>
public string? ErrorDetail { get; set; }
+
+ /// <summary>
+ /// Localization key of a note on a file that converted (e.g. <c>notice.pdf_not_smaller</c>: compressing saved
+ /// nothing, so the PDF was copied as it is), if any.
+ /// </summary>
+ public string? NoticeKey { get; set; }
}
/// <summary>A batch of files converted with one preset.</summary>
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index aac27e41..dc06561f 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -58,13 +58,18 @@ public interface IOutputAllocator
/// <param name="Preset">Options chosen by the user.</param>
/// <param name="Output">Where to write results.</param>
/// <param name="WorkDirectory">Private scratch directory for this job; deleted afterwards.</param>
+/// <param name="Notice">
+/// Records a note on a step that worked, as a localization key (e.g. <c>notice.pdf_not_smaller</c>): shown with the
+/// file's result. Null when nobody listens.
+/// </param>
public sealed record ConversionStep(
string InputPath,
string From,
string To,
Preset Preset,
IOutputAllocator Output,
- string WorkDirectory);
+ string WorkDirectory,
+ Action<string>? Notice = null);
/// <summary>
/// A conversion engine (ImageMagick, LibreOffice, rhwp, ...).
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 590f3337..5c1770f4 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -378,7 +378,7 @@ public sealed class JobQueue : IAsyncDisposable
// Turned once, in step turnAt: every other step gets the preset without rotation and flip,
// also one before it whose engine applies image options but doesn't say it turns.
var preset = s == turnAt ? job.Preset : unturned;
- var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir);
+ var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir, key => file.NoticeKey = key);
outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct));
}
finally
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index c47d818d..7009291a 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -65,6 +65,7 @@ public static class BuiltInData
Id = "pdf-split", NameKey = "preset.split_pdf", TargetFormat = "pdf",
Pdf = { SplitPages = true }, Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}" },
},
+ .. PdfCompressionPresets(),
new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
.. HwpPresets(),
@@ -81,6 +82,19 @@ public static class BuiltInData
.. TracePresets(),
];
+ /// <summary>
+ /// "Compress PDF": pictures at 150 dpi, the rest compressed losslessly (added in settings schema 20). On no default
+ /// donut, the PDF donut is full: users add it in Settings → Toolbar.
+ /// </summary>
+ public static List<Preset> PdfCompressionPresets() =>
+ [
+ new()
+ {
+ Id = "compress-pdf", NameKey = "preset.compress_pdf", TargetFormat = "pdf",
+ Pdf = { Compression = PdfCompression.Ebook }, Output = { FileNamePattern = "{name}_compressed" },
+ },
+ ];
+
/// <summary>Raster → SVG tracing, in colour and as black line art (added in settings schema 16).</summary>
public static List<Preset> TracePresets() =>
[
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 72550948..99b182aa 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -277,6 +277,22 @@ public enum PdfPageSize
Letter,
}
+/// <summary>
+/// How hard a PDF → PDF conversion shrinks the file: pictures are scaled down to the level's resolution and saved as
+/// JPEG at its quality, the rest is compressed losslessly. Text, fonts and drawings stay as they are.
+/// </summary>
+public enum PdfCompression
+{
+ /// <summary>Pages are copied as they are.</summary>
+ None,
+ /// <summary>Smallest: pictures at 72 dpi (reading on screen).</summary>
+ Screen,
+ /// <summary>Balanced: pictures at 150 dpi (e-mail, uploads).</summary>
+ Ebook,
+ /// <summary>High quality: pictures at 300 dpi (printing).</summary>
+ Print,
+}
+
/// <summary>PDF related options.</summary>
public sealed class PdfOptions
{
@@ -312,6 +328,19 @@ public sealed class PdfOptions
/// </summary>
public bool SplitTallImage { get; set; }
+ /// <summary>
+ /// For PDF → PDF: make the file smaller (also with a page range or one file per page). A level from a newer Filee
+ /// reads as <see cref="PdfCompression.None"/>.
+ /// </summary>
+ [JsonConverter(typeof(LenientEnumJsonConverter<PdfCompression>))]
+ public PdfCompression Compression { get; set; }
+
+ /// <summary>
+ /// With <see cref="Compression"/>: also let Ghostscript rewrite the PDF when it is installed, and keep whichever
+ /// result is smaller. Off by default: it rewrites the whole file (fonts, structure), not only the pictures.
+ /// </summary>
+ public bool CompressWithGhostscript { get; set; }
+
public PdfOptions Clone() => (PdfOptions)MemberwiseClone();
}
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 1701b12f..c69e086b 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -50,7 +50,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 17;
+ public const int CurrentSchemaVersion = 20;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 9b0f3880..9d05dc10 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -479,6 +479,29 @@ internal static class SettingsMigrations
}
}
}
+
+ // v20: "Compress PDF" (PDF → a smaller PDF), after "Split PDF" as in a new library, on no donut: the PDF donut
+ // is full. Present already but saved since by a Filee before 20 (back and forth between versions): that
+ // one dropped the compression level and left a preset that copies the pages, so the level is put back.
+ // (Schema 18 and 19 belong to other changes: renumber when they land in a different order.)
+ if (from < 20)
+ {
+ foreach (var compress in BuiltInData.PdfCompressionPresets())
+ {
+ if (presets.FirstOrDefault(p => p.Id == compress.Id) is { } existing)
+ {
+ if (existing.Pdf.Compression == PdfCompression.None && existing.TargetFormat == compress.TargetFormat)
+ {
+ existing.Pdf.Compression = compress.Pdf.Compression;
+ changed = true;
+ }
+ continue;
+ }
+ var split = presets.FindIndex(p => p.Id == "pdf-split");
+ presets.Insert(split < 0 ? presets.Count : split + 1, compress);
+ changed = true;
+ }
+ }
return changed;
}
diff --git a/src/Filee.Engines/Pdf/PdfCompressor.cs b/src/Filee.Engines/Pdf/PdfCompressor.cs
new file mode 100644
index 00000000..3499bf9c
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfCompressor.cs
@@ -0,0 +1,538 @@
+// Makes a PDF smaller while it stays a PDF (PDFsharp + Magick.NET). Pictures drawn at more than the level's resolution
+// are scaled down to it, photos are saved as JPEG at the level's quality and pictures with few colours (charts,
+// screenshots, logos) losslessly; every other stream is deflated at the highest level; page thumbnails, other
+// applications' private data and, when the preset drops metadata, the XMP metadata of pages and pictures are left out
+// (PDFsharp writes the document's own XMP from its document information on every save). Text, fonts and vector
+// drawings stay as they are. A picture is changed only when the result is smaller.
+
+using System.IO.Compression;
+using Filee.Core.Presets;
+using ImageMagick;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.Advanced;
+using PdfSharp.Pdf.Content;
+using PdfSharp.Pdf.Content.Objects;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>Shrinks the pictures and streams of a PDF document in place (before it is saved).</summary>
+internal static class PdfCompressor
+{
+ /// <summary>
+ /// Pictures are scaled down only when they are drawn at more than this many times the level's resolution, like
+ /// Ghostscript does: a picture just above it would lose sharpness for little saving.
+ /// </summary>
+ private const double DownsampleThreshold = 1.5;
+
+ /// <summary>A picture drawn tiny (or with a transformation read wrong) never gets smaller than this, in pixels.</summary>
+ private const int MinimumSide = 8;
+
+ /// <summary>A JPEG that keeps its size is encoded again only when that saves at least this share of it.</summary>
+ private const double MinimumJpegSaving = 0.1;
+
+ /// <summary>Colours up to which a picture is a graphic (kept lossless) rather than a photo (JPEG).</summary>
+ private const int GraphicColors = 256;
+
+ /// <summary>The same for gray pictures, which never have more than 256 shades: a gray photo has many of them.</summary>
+ private const int GraphicGrays = 32;
+
+ /// <summary>Resolution pictures are scaled down to (dpi) and JPEG quality, per level.</summary>
+ public static (int Dpi, int Quality) Settings(PdfCompression level) => level switch
+ {
+ PdfCompression.Screen => (72, 55),
+ PdfCompression.Print => (300, 85),
+ _ => (150, 65),
+ };
+
+ /// <summary>Shrinks <paramref name="document"/>; save it afterwards.</summary>
+ /// <param name="keepMetadata">False drops the XMP metadata of pages, pictures and forms.</param>
+ public static void Compress(PdfDocument document, PdfCompression level, bool keepMetadata, CancellationToken cancellationToken)
+ {
+ var (dpi, quality) = Settings(level);
+ var done = new HashSet<PdfDictionary>(ReferenceEqualityComparer.Instance);
+ foreach (var (image, use) in PdfPictureUses.Find(document))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (done.Add(image))
+ ShrinkPicture(document, image, use, dpi, quality, done);
+ }
+
+ MergeDuplicatePictures(document);
+
+ foreach (var page in document.Pages)
+ {
+ page.Elements.Remove("/Thumb");
+ page.Elements.Remove("/PieceInfo");
+ }
+ document.Internals.Catalog.Elements.Remove("/PieceInfo");
+ // PDFsharp writes the document's XMP afresh from its document information when it saves (as for every PDF it
+ // writes); the old packet would stay in the file unreferenced, so it goes whatever the preset says.
+ document.Internals.Catalog.Elements.Remove("/Metadata");
+
+ foreach (var item in document.Internals.GetAllObjects())
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (item is not PdfDictionary dictionary)
+ continue;
+ if (!keepMetadata && dictionary.Elements.ContainsKey("/Metadata"))
+ dictionary.Elements.Remove("/Metadata");
+ if (dictionary.Stream is not null)
+ Deflate(dictionary);
+ }
+
+ document.Options.CompressContentStreams = true;
+ document.Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
+ document.Options.Layout = PdfWriterLayout.Compact;
+ }
+
+ /// <summary>Scales a picture down and saves it as JPEG or Flate, when that's smaller. Soft masks follow it.</summary>
+ private static void ShrinkPicture(PdfDocument document, PdfDictionary image, PictureUse use, int dpi, int quality, HashSet<PdfDictionary> done)
+ {
+ if (Decode(image) is not { } picture)
+ return;
+ using var pixels = picture.Image;
+ var width = (int)pixels.Width;
+ var height = (int)pixels.Height;
+
+ // Pixels needed to show the picture at the target resolution where it is drawn largest.
+ var scale = Math.Max(use.WidthInches * dpi / width, use.HeightInches * dpi / height);
+ var downsample = scale * DownsampleThreshold < 1;
+ var newWidth = downsample ? Math.Clamp((int)Math.Round(width * scale), Math.Min(MinimumSide, width), width) : width;
+ var newHeight = downsample ? Math.Clamp((int)Math.Round(height * scale), Math.Min(MinimumSide, height), height) : height;
+ downsample = newWidth < width || newHeight < height;
+ if (downsample)
+ pixels.Resize(new MagickGeometry((uint)newWidth, (uint)newHeight) { IgnoreAspectRatio = true });
+
+ var original = image.Stream.Value.Length;
+ // A JPEG that only gets a lower quality is worth it only for a clear saving: it loses detail once more.
+ var limit = !downsample && picture.WasJpeg ? (int)(original * (1 - MinimumJpegSaving)) : original;
+ var graphic = !picture.WasJpeg && pixels.TotalColors <= (picture.Components == 1 ? GraphicGrays : GraphicColors);
+ var encoded = picture.Components == 4 || graphic
+ ? EncodeFlate(pixels, picture.Components)
+ : EncodeJpeg(pixels, picture.Components, quality);
+ if (encoded is null || encoded.Value.Data.Length >= limit)
+ return;
+
+ image.Stream.Value = encoded.Value.Data;
+ image.Elements.SetName("/Filter", encoded.Value.Filter);
+ if (encoded.Value.DecodeParms is { } parms)
+ image.Elements["/DecodeParms"] = Parms(document, parms);
+ else
+ image.Elements.Remove("/DecodeParms");
+ image.Elements.SetInteger("/Width", newWidth);
+ image.Elements.SetInteger("/Height", newHeight);
+ image.Elements.SetInteger("/BitsPerComponent", 8);
+
+ // The soft mask (transparency) may have its own size: scaled by as much as the picture, and kept lossless.
+ if (downsample && Resolve(image.Elements["/SMask"]) is PdfDictionary mask && done.Add(mask))
+ ShrinkMask(document, mask, (double)newWidth / width, (double)newHeight / height);
+ }
+
+ private static void ShrinkMask(PdfDocument document, PdfDictionary mask, double scaleX, double scaleY)
+ {
+ if (Decode(mask) is not { Components: 1, WasJpeg: false } picture)
+ return;
+ using var pixels = picture.Image;
+ var width = (int)Math.Max(1, Math.Round(pixels.Width * scaleX));
+ var height = (int)Math.Max(1, Math.Round(pixels.Height * scaleY));
+ pixels.Resize(new MagickGeometry((uint)width, (uint)height) { IgnoreAspectRatio = true });
+ if (EncodeFlate(pixels, 1) is not { } encoded || encoded.Data.Length >= mask.Stream.Value.Length)
+ return;
+ mask.Stream.Value = encoded.Data;
+ mask.Elements.SetName("/Filter", encoded.Filter);
+ mask.Elements["/DecodeParms"] = Parms(document, encoded.DecodeParms!.Value);
+ mask.Elements.SetInteger("/Width", width);
+ mask.Elements.SetInteger("/Height", height);
+ mask.Elements.SetInteger("/BitsPerComponent", 8);
+ }
+
+ /// <summary>
+ /// Pictures stored more than once with the same data and settings (a logo embedded again on every page) are kept
+ /// once: every reference to a copy points to the first. Soft masks first, so the pictures using them compare equal.
+ /// </summary>
+ private static void MergeDuplicatePictures(PdfDocument document)
+ {
+ var images = document.Internals.GetAllObjects().OfType<PdfDictionary>()
+ .Where(d => d.Stream is not null && d.Elements.GetName("/Subtype") == "/Image" && d.Reference is not null)
+ .ToList();
+ foreach (var pass in new[] { images.Where(Plain).ToList(), images.Where(i => !Plain(i)).ToList() })
+ {
+ var first = new Dictionary<string, PdfDictionary>(StringComparer.Ordinal);
+ var copies = new Dictionary<PdfDictionary, PdfReference>(ReferenceEqualityComparer.Instance);
+ foreach (var image in pass)
+ {
+ var key = string.Join(" ", image.Elements.Keys.Where(k => k != "/Length").Order(StringComparer.Ordinal)
+ .Select(k => k + " " + image.Elements[k])) + " " + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(image.Stream.Value));
+ if (!first.TryAdd(key, image))
+ copies[image] = first[key].Reference!;
+ }
+ if (copies.Count == 0)
+ continue;
+ foreach (var item in document.Internals.GetAllObjects())
+ {
+ if (item is PdfDictionary or PdfArray)
+ Redirect(item, copies, depth: 0);
+ }
+ }
+
+ static bool Plain(PdfDictionary image) => !image.Elements.ContainsKey("/SMask") && !image.Elements.ContainsKey("/Mask");
+ }
+
+ /// <summary>Points references to the copies in <paramref name="copies"/> to the kept picture, in direct objects too.</summary>
+ private static void Redirect(PdfItem container, Dictionary<PdfDictionary, PdfReference> copies, int depth)
+ {
+ if (depth > 32)
+ return;
+ if (container is PdfDictionary dictionary)
+ {
+ foreach (var key in dictionary.Elements.Keys.ToList())
+ {
+ var value = dictionary.Elements[key];
+ if (value is PdfReference { Value: PdfDictionary target } && copies.TryGetValue(target, out var kept))
+ dictionary.Elements[key] = kept;
+ else if (value is PdfDictionary { Reference: null } or PdfArray { Reference: null })
+ Redirect(value, copies, depth + 1);
+ }
+ }
+ else if (container is PdfArray array)
+ {
+ for (var i = 0; i < array.Elements.Count; i++)
+ {
+ var value = array.Elements[i];
+ if (value is PdfReference { Value: PdfDictionary target } && copies.TryGetValue(target, out var kept))
+ array.Elements[i] = kept;
+ else if (value is PdfDictionary { Reference: null } or PdfArray { Reference: null })
+ Redirect(value, copies, depth + 1);
+ }
+ }
+ }
+
+ private static PdfDictionary Parms(PdfDocument document, (int Colors, int Columns) parms)
+ {
+ var dictionary = new PdfDictionary(document);
+ dictionary.Elements.SetInteger("/Predictor", 15);
+ dictionary.Elements.SetInteger("/Colors", parms.Colors);
+ dictionary.Elements.SetInteger("/BitsPerComponent", 8);
+ dictionary.Elements.SetInteger("/Columns", parms.Columns);
+ return dictionary;
+ }
+
+ private sealed record DecodedPicture(MagickImage Image, int Components, bool WasJpeg);
+
+ /// <summary>
+ /// The pixels of a picture Filee can encode again without changing how it looks: 8 bits per component, gray, RGB or
+ /// CMYK (CMYK not from JPEG: Adobe's inverted CMYK JPEGs are easy to get wrong), stored as JPEG, Flate or
+ /// uncompressed. Null for everything else (JBIG2, CCITT, JPEG 2000, 1-bit, indexed, spot colours, colour-key
+ /// masks), which stays as it is.
+ /// </summary>
+ private static DecodedPicture? Decode(PdfDictionary image)
+ {
+ var elements = image.Elements;
+ if (elements.GetName("/Subtype") != "/Image" || elements.GetBoolean("/ImageMask") || elements.GetInteger("/BitsPerComponent") != 8
+ || Resolve(elements["/Mask"]) is PdfArray || elements.ContainsKey("/F"))
+ return null;
+ var width = elements.GetInteger("/Width");
+ var height = elements.GetInteger("/Height");
+ var components = Components(Resolve(elements["/ColorSpace"]));
+ if (width <= 0 || height <= 0 || components == 0 || (long)width * height > 100_000_000)
+ return null;
+
+ var filters = Filters(image);
+ var data = image.Stream.Value;
+ try
+ {
+ if (filters is ["/DCTDecode"])
+ {
+ // ColorTransform overrides how the JPEG's colours are read: rare, so left alone.
+ if (components == 4 || Parms(image) is { } dct && dct.Elements.ContainsKey("/ColorTransform"))
+ return null;
+ var jpeg = new MagickImage(data, MagickFormat.Jpeg);
+ var gray = jpeg.ColorSpace == ColorSpace.Gray || jpeg.ChannelCount == 1;
+ if (jpeg.Width != width || jpeg.Height != height || gray != (components == 1) || jpeg.ColorSpace == ColorSpace.CMYK)
+ {
+ jpeg.Dispose();
+ return null;
+ }
+ return new DecodedPicture(jpeg, components, WasJpeg: true);
+ }
+
+ if (filters is not ([] or ["/FlateDecode"] or ["/RunLengthDecode"]))
+ return null;
+ var raw = filters switch
+ {
+ [] => data,
+ ["/RunLengthDecode"] => UndoRunLength(data),
+ _ => Inflate(data),
+ };
+ if (filters is ["/FlateDecode"] && Parms(image) is { } flate && flate.Elements.GetInteger("/Predictor") > 1)
+ {
+ // PNG prediction of whole pixels only; TIFF prediction (2) is rare in pictures.
+ var parms = flate.Elements;
+ var colors = parms.ContainsKey("/Colors") ? parms.GetInteger("/Colors") : 1;
+ var columns = parms.ContainsKey("/Columns") ? parms.GetInteger("/Columns") : 1;
+ var bits = parms.ContainsKey("/BitsPerComponent") ? parms.GetInteger("/BitsPerComponent") : 8;
+ if (parms.GetInteger("/Predictor") < 10 || colors != components || columns != width || bits != 8
+ || UndoPngPredictor(raw, width * components, height, components) is not { } unpredicted)
+ return null;
+ raw = unpredicted;
+ }
+ var size = width * height * components;
+ if (raw.Length < size)
+ return null;
+ var settings = new MagickReadSettings
+ {
+ Width = (uint)width,
+ Height = (uint)height,
+ Depth = 8,
+ Format = components switch { 1 => MagickFormat.Gray, 3 => MagickFormat.Rgb, _ => MagickFormat.Cmyk },
+ };
+ return new DecodedPicture(new MagickImage(raw.AsSpan(0, size), settings), components, WasJpeg: false);
+ }
+ catch (Exception ex) when (ex is MagickException or InvalidDataException)
+ {
+ return null; // damaged or unusual data: the picture stays as it is
+ }
+ }
+
+ private static (byte[] Data, string Filter, (int Colors, int Columns)? DecodeParms)? EncodeJpeg(MagickImage pixels, int components, int quality)
+ {
+ pixels.Strip();
+ pixels.Quality = (uint)quality;
+ pixels.ColorType = components == 1 ? ColorType.Grayscale : ColorType.TrueColor;
+ var data = pixels.ToByteArray(MagickFormat.Jpeg);
+ // Exactly what the image dictionary says, or the picture would come out wrong: ImageMagick could write a
+ // gray-looking colour picture with one component.
+ return JpegFrame(data) is var (w, h, n) && w == pixels.Width && h == pixels.Height && n == components
+ ? (data, "/DCTDecode", null)
+ : null;
+ }
+
+ private static (byte[] Data, string Filter, (int Colors, int Columns)? DecodeParms)? EncodeFlate(MagickImage pixels, int components)
+ {
+ pixels.Depth = 8;
+ var raw = pixels.ToByteArray(components switch { 1 => MagickFormat.Gray, 3 => MagickFormat.Rgb, _ => MagickFormat.Cmyk });
+ var stride = (int)pixels.Width * components;
+ if (raw.Length != stride * (int)pixels.Height)
+ return null;
+ return (Deflate(PngPredict(raw, stride, (int)pixels.Height, components)), "/FlateDecode", (components, (int)pixels.Width));
+ }
+
+ /// <summary>Deflates an uncompressed stream, or deflates a Flate stream again at the highest level, when smaller.</summary>
+ private static void Deflate(PdfDictionary dictionary)
+ {
+ var type = dictionary.Elements.GetName("/Type");
+ // XMP stays readable for tools that search files for it; object and cross-reference streams are PDFsharp's.
+ if (type is "/Metadata" or "/ObjStm" or "/XRef" || dictionary.Elements.ContainsKey("/F"))
+ return;
+ var filters = Filters(dictionary);
+ var data = dictionary.Stream.Value;
+ if (data.Length < 64)
+ return;
+ try
+ {
+ if (filters.Length == 0)
+ {
+ var packed = Deflate(data);
+ if (packed.Length >= data.Length)
+ return;
+ dictionary.Stream.Value = packed;
+ dictionary.Elements.SetName("/Filter", "/FlateDecode");
+ }
+ else if (filters is ["/FlateDecode"])
+ {
+ // The data stays the same (predictor included), only packed tighter.
+ var packed = Deflate(Inflate(data));
+ if (packed.Length < data.Length)
+ dictionary.Stream.Value = packed;
+ }
+ else if (filters is ["/RunLengthDecode"])
+ {
+ var packed = Deflate(UndoRunLength(data));
+ if (packed.Length >= data.Length)
+ return;
+ dictionary.Stream.Value = packed;
+ dictionary.Elements.SetName("/Filter", "/FlateDecode");
+ }
+ }
+ catch (InvalidDataException)
+ {
+ // damaged stream: left as it is
+ }
+ }
+
+ private static string[] Filters(PdfDictionary dictionary) => Resolve(dictionary.Elements["/Filter"]) switch
+ {
+ PdfName name => [name.Value],
+ PdfArray array => [.. array.Elements.Select(e => Resolve(e) is PdfName n ? n.Value : "?")],
+ _ => [],
+ };
+
+ private static PdfDictionary? Parms(PdfDictionary dictionary) => Resolve(dictionary.Elements["/DecodeParms"]) switch
+ {
+ PdfDictionary parms => parms,
+ PdfArray { Elements.Count: 1 } array => Resolve(array.Elements[0]) as PdfDictionary,
+ _ => null,
+ };
+
+ /// <summary>Components of a colour space Filee re-encodes (gray, RGB, CMYK and their calibrated / ICC forms), else 0.</summary>
+ private static int Components(PdfItem? colorSpace) => colorSpace switch
+ {
+ PdfName { Value: "/DeviceGray" } => 1,
+ PdfName { Value: "/DeviceRGB" } => 3,
+ PdfName { Value: "/DeviceCMYK" } => 4,
+ PdfArray { Elements.Count: > 0 } array => (Resolve(array.Elements[0]) as PdfName)?.Value switch
+ {
+ "/CalGray" => 1,
+ "/CalRGB" => 3,
+ "/ICCBased" when array.Elements.Count > 1 && Resolve(array.Elements[1]) is PdfDictionary icc
+ => icc.Elements.GetInteger("/N") is var n and (1 or 3 or 4) ? n : 0,
+ _ => 0,
+ },
+ _ => 0,
+ };
+
+ /// <summary>The object a reference points to; a name stored as an object of its own (ImageMagick does) as a name.</summary>
+ internal static PdfItem? Resolve(PdfItem? item) => item is PdfReference reference
+ ? reference.Value is PdfNameObject name ? new PdfName(name.Value) : reference.Value
+ : item;
+
+ private static byte[] Inflate(byte[] data)
+ {
+ using var input = new ZLibStream(new MemoryStream(data), CompressionMode.Decompress);
+ using var output = new MemoryStream();
+ input.CopyTo(output);
+ return output.ToArray();
+ }
+
+ private static byte[] Deflate(byte[] data)
+ {
+ using var output = new MemoryStream();
+ using (var zlib = new ZLibStream(output, CompressionLevel.SmallestSize, leaveOpen: true))
+ zlib.Write(data);
+ return output.ToArray();
+ }
+
+ /// <summary>
+ /// RunLengthDecode (ImageMagick writes pictures with it): a length byte n &lt; 128 copies the next n + 1 bytes, n &gt; 128
+ /// repeats the next byte 257 - n times, 128 ends the data.
+ /// </summary>
+ private static byte[] UndoRunLength(byte[] data)
+ {
+ using var output = new MemoryStream(data.Length * 2);
+ var i = 0;
+ while (i < data.Length)
+ {
+ var length = data[i++];
+ if (length == 128)
+ break;
+ if (length < 128)
+ {
+ var count = Math.Min(length + 1, data.Length - i);
+ output.Write(data, i, count);
+ i += count;
+ }
+ else if (i < data.Length)
+ {
+ var value = data[i++];
+ for (var n = 0; n < 257 - length; n++)
+ output.WriteByte(value);
+ }
+ }
+ return output.ToArray();
+ }
+
+ /// <summary>Reverses PNG prediction (/Predictor 10-15): each row starts with its filter type. Null when damaged.</summary>
+ private static byte[]? UndoPngPredictor(byte[] data, int stride, int rows, int bpp)
+ {
+ if (data.Length < (long)(stride + 1) * rows)
+ return null;
+ var result = new byte[stride * rows];
+ var none = new byte[stride];
+ for (var r = 0; r < rows; r++)
+ {
+ var type = data[r * (stride + 1)];
+ var source = data.AsSpan(r * (stride + 1) + 1, stride);
+ var row = result.AsSpan(r * stride, stride);
+ ReadOnlySpan<byte> up = r == 0 ? none : result.AsSpan((r - 1) * stride, stride);
+ for (var x = 0; x < stride; x++)
+ {
+ int a = x >= bpp ? row[x - bpp] : 0, b = up[x], c = x >= bpp ? up[x - bpp] : 0;
+ int predicted;
+ switch (type)
+ {
+ case 0: predicted = 0; break;
+ case 1: predicted = a; break;
+ case 2: predicted = b; break;
+ case 3: predicted = (a + b) / 2; break;
+ case 4: predicted = Paeth(a, b, c); break;
+ default: return null;
+ }
+ row[x] = (byte)(source[x] + predicted);
+ }
+ }
+ return result;
+ }
+
+ /// <summary>PNG-predicts rows (/Predictor 15), each with the filter that leaves the smallest values.</summary>
+ private static byte[] PngPredict(byte[] raw, int stride, int rows, int bpp)
+ {
+ var output = new byte[(stride + 1) * rows];
+ var candidates = new byte[5][];
+ for (var t = 0; t < candidates.Length; t++)
+ candidates[t] = new byte[stride];
+ var none = new byte[stride];
+ for (var r = 0; r < rows; r++)
+ {
+ ReadOnlySpan<byte> row = raw.AsSpan(r * stride, stride);
+ ReadOnlySpan<byte> up = r == 0 ? none : raw.AsSpan((r - 1) * stride, stride);
+ var best = 0;
+ var bestSum = long.MaxValue;
+ for (var type = 0; type < candidates.Length; type++)
+ {
+ var filtered = candidates[type];
+ long sum = 0;
+ for (var x = 0; x < stride; x++)
+ {
+ int a = x >= bpp ? row[x - bpp] : 0, b = up[x], c = x >= bpp ? up[x - bpp] : 0;
+ var predicted = type switch { 0 => 0, 1 => a, 2 => b, 3 => (a + b) / 2, _ => Paeth(a, b, c) };
+ var value = (byte)(row[x] - predicted);
+ filtered[x] = value;
+ sum += value < 128 ? value : 256 - value;
+ }
+ if (sum < bestSum)
+ {
+ bestSum = sum;
+ best = type;
+ }
+ }
+ output[r * (stride + 1)] = (byte)best;
+ candidates[best].CopyTo(output.AsSpan(r * (stride + 1) + 1));
+ }
+ return output;
+ }
+
+ private static int Paeth(int a, int b, int c)
+ {
+ var p = a + b - c;
+ int pa = Math.Abs(p - a), pb = Math.Abs(p - b), pc = Math.Abs(p - c);
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
+ }
+
+ /// <summary>Width, height and components of a JPEG's frame header, or null.</summary>
+ private static (int Width, int Height, int Components)? JpegFrame(byte[] jpeg)
+ {
+ var i = 2;
+ while (i + 9 < jpeg.Length)
+ {
+ if (jpeg[i] != 0xFF)
+ return null;
+ var marker = jpeg[i + 1];
+ var length = (jpeg[i + 2] << 8) | jpeg[i + 3];
+ if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC)
+ return ((jpeg[i + 7] << 8) | jpeg[i + 8], (jpeg[i + 5] << 8) | jpeg[i + 6], jpeg[i + 9]);
+ i += 2 + length;
+ }
+ return null;
+ }
+}
diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
index 4703e760..3d0c4dc7 100644
--- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs
+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
@@ -183,7 +183,7 @@ internal sealed partial class PdfDocumentReader
}
}
- private static InvalidOperationException PasswordProtected() =>
+ internal static InvalidOperationException PasswordProtected() =>
new("The PDF is password-protected. Open it with its password and save a copy without one, then convert that copy.");
private PageContent ReadPage(Page page)
diff --git a/src/Filee.Engines/Pdf/PdfPictureUses.cs b/src/Filee.Engines/Pdf/PdfPictureUses.cs
new file mode 100644
index 00000000..70e88327
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfPictureUses.cs
@@ -0,0 +1,242 @@
+// Where the pictures of a PDF are drawn and how large, for PdfCompressor: the content streams of the pages, of the
+// forms they draw and of annotation appearances are read for "cm" (transformations) and "Do" (draw an XObject). A
+// picture's largest drawn size decides how far it may be scaled down. Pictures whose drawing can't be followed (a
+// content stream PDFsharp can't read) are taken as large as the page lets them be, so they are never scaled down too far.
+
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.Content;
+using PdfSharp.Pdf.Content.Objects;
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>The largest size, in inches, a picture is drawn at (width and height of the picture, wherever it is turned).</summary>
+internal readonly record struct PictureUse(double WidthInches, double HeightInches);
+
+/// <summary>Finds the pictures (image XObjects) of a document and the size they are drawn at.</summary>
+internal sealed class PdfPictureUses
+{
+ private const double PointsPerInch = 72;
+
+ /// <summary>Forms drawing forms deeper than this are not followed (and nothing is drawn that deep in practice).</summary>
+ private const int MaxDepth = 12;
+
+ /// <summary>Forms followed per document at most, against forms drawing each other many times over.</summary>
+ private const int MaxForms = 20_000;
+
+ /// <summary>The part of a transformation that sizes things (no translation): x' = a·x + c·y, y' = b·x + d·y.</summary>
+ private readonly record struct Matrix(double A, double B, double C, double D)
+ {
+ public static readonly Matrix Identity = new(1, 0, 0, 1);
+
+ /// <summary>This transformation applied first, then <paramref name="outer"/> (PDF's "this × outer").</summary>
+ public Matrix Then(Matrix outer) =>
+ new(A * outer.A + B * outer.C, A * outer.B + B * outer.D, C * outer.A + D * outer.C, C * outer.B + D * outer.D);
+ }
+
+ private readonly Dictionary<PdfDictionary, (double Width, double Height)> _drawn = new(ReferenceEqualityComparer.Instance);
+ private readonly HashSet<PdfDictionary> _found = new(ReferenceEqualityComparer.Instance);
+ private readonly HashSet<PdfDictionary> _unsure = new(ReferenceEqualityComparer.Instance);
+ private int _forms;
+
+ /// <summary>Every picture in the resources of the pages, their forms and annotation appearances, with its size.</summary>
+ public static IReadOnlyList<(PdfDictionary Image, PictureUse Use)> Find(PdfDocument document)
+ {
+ var uses = new PdfPictureUses();
+ double pageWidth = 0, pageHeight = 0;
+ foreach (var page in document.Pages)
+ {
+ pageWidth = Math.Max(pageWidth, page.Width.Point);
+ pageHeight = Math.Max(pageHeight, page.Height.Point);
+ var resources = page.Elements.GetDictionary("/Resources");
+ uses.Collect(resources);
+ CSequence? content = null;
+ try
+ {
+ content = ContentReader.ReadContent(page);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ uses.Unsure(resources); // can't be read: its pictures are taken as large as the page
+ }
+ if (content is not null)
+ uses.Walk(content, resources, Matrix.Identity, 0);
+ uses.WalkAnnotations(page);
+ }
+
+ // Not drawn anywhere Filee could follow: as large as the largest page holds it (either way round).
+ var pageWidthInches = Math.Max(pageWidth, 1) / PointsPerInch;
+ var pageHeightInches = Math.Max(pageHeight, 1) / PointsPerInch;
+ var result = new List<(PdfDictionary, PictureUse)>();
+ foreach (var image in uses._found)
+ {
+ var width = Math.Max(1, image.Elements.GetInteger("/Width"));
+ var height = Math.Max(1, image.Elements.GetInteger("/Height"));
+ var dpi = Math.Min(Math.Max(width / pageWidthInches, height / pageHeightInches),
+ Math.Max(width / pageHeightInches, height / pageWidthInches));
+ var drawn = uses._drawn.TryGetValue(image, out var size) ? size : (0, 0);
+ if (!uses._drawn.ContainsKey(image) || uses._unsure.Contains(image))
+ drawn = (Math.Max(drawn.Width, width / dpi), Math.Max(drawn.Height, height / dpi));
+ result.Add((image, new PictureUse(drawn.Width, drawn.Height)));
+ }
+ return result;
+ }
+
+ /// <summary>Remembers the pictures of a resource dictionary.</summary>
+ private void Collect(PdfDictionary? resources)
+ {
+ if (resources?.Elements.GetDictionary("/XObject") is not { } xobjects)
+ return;
+ foreach (var key in xobjects.Elements.Keys)
+ {
+ if (PdfCompressor.Resolve(xobjects.Elements[key]) is PdfDictionary { Stream: not null } xobject
+ && xobject.Elements.GetName("/Subtype") == "/Image")
+ _found.Add(xobject);
+ }
+ }
+
+ private void Unsure(PdfDictionary? resources)
+ {
+ if (resources?.Elements.GetDictionary("/XObject") is not { } xobjects)
+ return;
+ foreach (var key in xobjects.Elements.Keys)
+ {
+ if (PdfCompressor.Resolve(xobjects.Elements[key]) is PdfDictionary xobject)
+ _unsure.Add(xobject);
+ }
+ }
+
+ /// <summary>Follows q / Q / cm and records what Do draws.</summary>
+ private void Walk(CSequence content, PdfDictionary? resources, Matrix start, int depth)
+ {
+ var saved = new Stack<Matrix>();
+ var current = start;
+ foreach (var item in content)
+ {
+ if (item is not COperator op)
+ continue;
+ switch (op.OpCode.OpCodeName)
+ {
+ case OpCodeName.q:
+ saved.Push(current);
+ break;
+ case OpCodeName.Q:
+ if (saved.Count > 0)
+ current = saved.Pop();
+ break;
+ case OpCodeName.cm when op.Operands.Count == 6:
+ current = new Matrix(Number(op.Operands[0]), Number(op.Operands[1]), Number(op.Operands[2]), Number(op.Operands[3])).Then(current);
+ break;
+ case OpCodeName.Do when op.Operands.Count == 1 && op.Operands[0] is CName name:
+ Draw(name.Name, resources, current, depth);
+ break;
+ }
+ }
+ }
+
+ private void Draw(string name, PdfDictionary? resources, Matrix ctm, int depth)
+ {
+ if (resources?.Elements.GetDictionary("/XObject") is not { } xobjects
+ || PdfCompressor.Resolve(xobjects.Elements[name]) is not PdfDictionary { Stream: not null } xobject)
+ return;
+ switch (xobject.Elements.GetName("/Subtype"))
+ {
+ case "/Image":
+ // The picture fills the unit square: its sides become the transformed unit vectors.
+ var width = Math.Sqrt(ctm.A * ctm.A + ctm.B * ctm.B) / PointsPerInch;
+ var height = Math.Sqrt(ctm.C * ctm.C + ctm.D * ctm.D) / PointsPerInch;
+ _found.Add(xobject);
+ _drawn[xobject] = _drawn.TryGetValue(xobject, out var known)
+ ? (Math.Max(known.Width, width), Math.Max(known.Height, height))
+ : (width, height);
+ break;
+ case "/Form":
+ WalkForm(xobject, resources, ctm, depth + 1);
+ break;
+ }
+ }
+
+ private void WalkForm(PdfDictionary form, PdfDictionary? inherited, Matrix parent, int depth)
+ {
+ if (depth > MaxDepth || ++_forms > MaxForms)
+ {
+ Unsure(form.Elements.GetDictionary("/Resources") ?? inherited);
+ return;
+ }
+ // Old PDFs leave out a form's resources: it uses the page's then.
+ var resources = form.Elements.GetDictionary("/Resources") ?? inherited;
+ Collect(resources);
+ CSequence content;
+ try
+ {
+ content = ContentReader.ReadContent(form.Stream.UnfilteredValue);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ Unsure(resources);
+ return;
+ }
+ Walk(content, resources, FormMatrix(form).Then(parent), depth);
+ }
+
+ /// <summary>
+ /// Annotation appearances (stamps, signatures, form fields): the form's bounding box, transformed by its matrix,
+ /// is fitted into the annotation's rectangle.
+ /// </summary>
+ private void WalkAnnotations(PdfPage page)
+ {
+ if (page.Elements.GetArray("/Annots") is not { } annotations)
+ return;
+ foreach (var item in annotations.Elements)
+ {
+ if (PdfCompressor.Resolve(item) is not PdfDictionary annotation
+ || annotation.Elements.GetDictionary("/AP") is not { } appearances
+ || annotation.Elements.GetArray("/Rect") is not { Elements.Count: 4 } rect)
+ continue;
+ var rectWidth = Math.Abs(rect.Elements.GetReal(2) - rect.Elements.GetReal(0));
+ var rectHeight = Math.Abs(rect.Elements.GetReal(3) - rect.Elements.GetReal(1));
+ foreach (var key in new[] { "/N", "/R", "/D" })
+ {
+ switch (PdfCompressor.Resolve(appearances.Elements[key]))
+ {
+ case PdfDictionary { Stream: not null } form:
+ WalkAppearance(form, page, rectWidth, rectHeight);
+ break;
+ case PdfDictionary states:
+ foreach (var state in states.Elements.Keys)
+ {
+ if (PdfCompressor.Resolve(states.Elements[state]) is PdfDictionary { Stream: not null } stateForm)
+ WalkAppearance(stateForm, page, rectWidth, rectHeight);
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ private void WalkAppearance(PdfDictionary form, PdfPage page, double rectWidth, double rectHeight)
+ {
+ var matrix = FormMatrix(form);
+ double boxWidth = 0, boxHeight = 0;
+ if (form.Elements.GetArray("/BBox") is { Elements.Count: 4 } box)
+ {
+ var w = Math.Abs(box.Elements.GetReal(2) - box.Elements.GetReal(0));
+ var h = Math.Abs(box.Elements.GetReal(3) - box.Elements.GetReal(1));
+ boxWidth = Math.Abs(matrix.A) * w + Math.Abs(matrix.C) * h;
+ boxHeight = Math.Abs(matrix.B) * w + Math.Abs(matrix.D) * h;
+ }
+ var fit = boxWidth > 0 && boxHeight > 0 ? new Matrix(rectWidth / boxWidth, 0, 0, rectHeight / boxHeight) : Matrix.Identity;
+ WalkForm(form, page.Elements.GetDictionary("/Resources"), fit, 1);
+ }
+
+ private static Matrix FormMatrix(PdfDictionary form) =>
+ form.Elements.GetArray("/Matrix") is { Elements.Count: 6 } m
+ ? new Matrix(m.Elements.GetReal(0), m.Elements.GetReal(1), m.Elements.GetReal(2), m.Elements.GetReal(3))
+ : Matrix.Identity;
+
+ private static double Number(CObject item) => item switch
+ {
+ CInteger integer => integer.Value,
+ CReal real => real.Value,
+ _ => 0,
+ };
+}
diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
index f3dba224..4f64ac75 100644
--- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs
+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
@@ -1,9 +1,11 @@
-// Builds PDFs from images, splits / extracts PDF pages, and merges PDFs (PDFsharp, MIT).
+// Builds PDFs from images, splits / extracts PDF pages, merges PDFs and makes PDFs smaller (PDFsharp, MIT; the
+// compression itself is in PdfCompressor, with Ghostscript as an optional second try).
using Filee.Core.Conversion;
using Filee.Core.Presets;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
+using Filee.Engines.Vector;
using ImageMagick;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
@@ -11,7 +13,7 @@ using PdfSharp.Pdf.IO;
namespace Filee.Engines.Pdf;
-/// <summary>Image → PDF, PDF → PDF (split / page range) and PDF merging.</summary>
+/// <summary>Image → PDF, PDF → PDF (split / page range / compression) and PDF merging.</summary>
public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransformer
{
private const double PointsPerInch = 72.0;
@@ -33,9 +35,9 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
public EngineStatus GetStatus() => EngineStatus.Available(version: EngineVersions.Library("PDFsharp", typeof(PdfDocument)));
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
- Task.Run(() => step.From == "pdf"
- ? SplitOrExtract(step, progress, cancellationToken)
- : ImageToPdf(step, progress, cancellationToken), cancellationToken);
+ step.From != "pdf" ? Task.Run(() => ImageToPdf(step, progress, cancellationToken), cancellationToken)
+ : step.Preset.Pdf.Compression == PdfCompression.None ? Task.Run(() => SplitOrExtract(step, progress, cancellationToken), cancellationToken)
+ : Task.Run(() => CompressAsync(step, progress, cancellationToken), cancellationToken);
public Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken) =>
Task.Run(() =>
@@ -44,7 +46,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
foreach (var input in inputPaths)
{
cancellationToken.ThrowIfCancellationRequested();
- using var source = PdfReader.Open(input, PdfDocumentOpenMode.Import);
+ using var source = Open(input, PdfDocumentOpenMode.Import);
foreach (var page in source.Pages)
output.AddPage(page);
}
@@ -106,7 +108,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
/// <summary>PDF → PDF: split into single pages, or extract the configured page range.</summary>
private static IReadOnlyList<string> SplitOrExtract(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
{
- using var source = PdfReader.Open(step.InputPath, PdfDocumentOpenMode.Import);
+ using var source = Open(step.InputPath, PdfDocumentOpenMode.Import);
var pages = PageRange.Parse(step.Preset.Pdf.PageRange, source.PageCount);
var written = new List<string>();
@@ -137,6 +139,150 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
return [output];
}
+ /// <summary>
+ /// PDF → a smaller PDF (<see cref="PdfOptions.Compression"/>), also with a page range or one file per page: the whole
+ /// file keeps everything (bookmarks, form fields, links, metadata) and is compressed as it is; selected pages are
+ /// copied into new PDFs first, as without compression. Each result is the smallest of the built-in compression and,
+ /// when the preset asks for it and it is installed, Ghostscript's; when neither is smaller than the pages as they
+ /// were, those are written unchanged and the file gets a notice.
+ /// </summary>
+ private static async Task<IReadOnlyList<string>> CompressAsync(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
+ {
+ var options = step.Preset.Pdf;
+ var scratch = Path.Combine(step.WorkDirectory, "compress-" + Guid.NewGuid().ToString("N")[..8]);
+ Directory.CreateDirectory(scratch);
+
+ // The PDFs to compress: the file itself, or its selected pages copied into new PDFs.
+ var parts = new List<(string Plain, string? Suffix)>();
+ using (var source = Open(step.InputPath, PdfDocumentOpenMode.Import))
+ {
+ var pages = PageRange.Parse(options.PageRange, source.PageCount);
+ if (options.SplitPages)
+ {
+ foreach (var index in pages)
+ {
+ using var single = new PdfDocument();
+ single.AddPage(source.Pages[index]);
+ var path = Path.Combine(scratch, $"page-{index + 1}.pdf");
+ single.Save(path);
+ parts.Add((path, $"_p{index + 1}"));
+ }
+ }
+ else if (pages.SequenceEqual(Enumerable.Range(0, source.PageCount)))
+ {
+ parts.Add((step.InputPath, null));
+ }
+ else
+ {
+ using var extract = new PdfDocument();
+ foreach (var index in pages)
+ extract.AddPage(source.Pages[index]);
+ var path = Path.Combine(scratch, "pages.pdf");
+ extract.Save(path);
+ parts.Add((path, null));
+ }
+ }
+
+ var gs = options.CompressWithGhostscript ? GhostscriptConverter.Locate() : null;
+ var written = new List<string>();
+ var anySmaller = false;
+ for (var i = 0; i < parts.Count; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ var output = step.Output.Allocate("pdf", parts[i].Suffix);
+ if (output is null)
+ continue;
+ anySmaller |= await CompressFileAsync(parts[i].Plain, output, step.Preset, gs, scratch, ct);
+ written.Add(output);
+ progress?.Report((i + 1.0) / parts.Count);
+ }
+ if (written.Count > 0 && !anySmaller)
+ step.Notice?.Invoke("notice.pdf_not_smaller");
+ return written;
+ }
+
+ /// <summary>Writes the smallest of <paramref name="plain"/> and its compressed versions to <paramref name="output"/>.</summary>
+ /// <returns>True when a compressed version was smaller.</returns>
+ private static async Task<bool> CompressFileAsync(string plain, string output, Preset preset, string? gs, string scratch, CancellationToken ct)
+ {
+ var level = preset.Pdf.Compression;
+ var candidates = new List<string>();
+ Exception? failure = null;
+ var builtIn = Path.Combine(scratch, Guid.NewGuid().ToString("N")[..8] + "-filee.pdf");
+ try
+ {
+ using var document = OpenForChanges(plain);
+ PdfCompressor.Compress(document, level, preset.Image.KeepMetadata, ct);
+ document.Save(builtIn);
+ candidates.Add(builtIn);
+ }
+ catch (Exception ex) when (gs is not null && ex is not OperationCanceledException)
+ {
+ failure = ex; // Ghostscript may still manage
+ }
+
+ if (gs is not null)
+ {
+ var rewritten = Path.Combine(scratch, Guid.NewGuid().ToString("N")[..8] + "-gs.pdf");
+ try
+ {
+ await GhostscriptConverter.CompressPdfAsync(gs, plain, rewritten, level, scratch, ct);
+ candidates.Add(rewritten);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException && candidates.Count > 0)
+ {
+ // The built-in result stands.
+ }
+ catch (Exception) when (failure is not null)
+ {
+ throw failure;
+ }
+ }
+
+ var original = new FileInfo(plain).Length;
+ var best = candidates.Select(path => new FileInfo(path)).MinBy(file => file.Length);
+ if (best is not null && best.Length < original)
+ {
+ File.Copy(best.FullName, output, overwrite: true);
+ return true;
+ }
+ File.Copy(plain, output, overwrite: true);
+ return false;
+ }
+
+ /// <summary>
+ /// Opens a PDF to change it. One locked only against changes (it opens without a password) has its pages copied
+ /// into a new PDF instead, as when pages are split or extracted: bookmarks and form fields stay behind then.
+ /// </summary>
+ private static PdfDocument OpenForChanges(string path)
+ {
+ try
+ {
+ return PdfReader.Open(path, PdfDocumentOpenMode.Modify);
+ }
+ catch (PdfReaderException ex) when (ex.Message.Contains("owner password", StringComparison.OrdinalIgnoreCase))
+ {
+ using var source = Open(path, PdfDocumentOpenMode.Import);
+ var copy = new PdfDocument();
+ foreach (var page in source.Pages)
+ copy.AddPage(page);
+ return copy;
+ }
+ }
+
+ /// <summary>Opens a PDF; a password-protected one fails with the message the other PDF conversions give.</summary>
+ internal static PdfDocument Open(string path, PdfDocumentOpenMode mode)
+ {
+ try
+ {
+ return PdfReader.Open(path, mode);
+ }
+ catch (PdfReaderException ex) when (ex.Message.Contains("password", StringComparison.OrdinalIgnoreCase))
+ {
+ throw PdfDocumentReader.PasswordProtected();
+ }
+ }
+
/// <summary>
/// Encodes a frame for embedding. JPEG sources stay JPEG (no generational loss beyond one re-encode at high quality);
/// everything else is embedded losslessly as PNG.
diff --git a/src/Filee.Engines/Vector/GhostscriptConverter.cs b/src/Filee.Engines/Vector/GhostscriptConverter.cs
index 8a5da4e1..06f06f5a 100644
--- a/src/Filee.Engines/Vector/GhostscriptConverter.cs
+++ b/src/Filee.Engines/Vector/GhostscriptConverter.cs
@@ -1,9 +1,11 @@
// PostScript and EPS with Ghostscript (AGPL-3.0, a separate program downloaded on demand into engines/ghostscript).
// EPS/PS → PDF with pdfwrite; PDF → EPS/PS with eps2write/ps2write; EPS/PS → PNG with pngalpha, which keeps a
// transparent background (through PDF the page would be drawn on white paper). Everything else (EPS → JPG,
-// SVG → EPS, …) is planned through PDF or PNG by the route planner.
+// SVG → EPS, …) is planned through PDF or PNG by the route planner. "Compress PDF" may also run a PDF through pdfwrite
+// (PdfSharpConverter calls CompressPdfAsync; there is no PDF → PDF edge here, so routes don't change).
using Filee.Core.Conversion;
+using Filee.Core.Presets;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
using ImageMagick;
@@ -92,6 +94,26 @@ public sealed class GhostscriptConverter : IConverter, IImageTransformer
File.Move(target, output, overwrite: true);
}
+ /// <summary>
+ /// Rewrites a PDF smaller with pdfwrite's settings for the level (/screen, /ebook, /printer: pictures at 72, 150 and
+ /// 300 dpi, Filee's levels too). Used by <see cref="Pdf.PdfSharpConverter"/> for "Compress PDF" when the preset asks
+ /// for Ghostscript; the caller keeps the result only when it is smaller.
+ /// </summary>
+ internal static async Task CompressPdfAsync(string gs, string input, string output, PdfCompression level, string workDirectory,
+ CancellationToken cancellationToken)
+ {
+ var settings = level switch
+ {
+ PdfCompression.Screen => "/screen",
+ PdfCompression.Print => "/printer",
+ _ => "/ebook",
+ };
+ var target = Path.Combine(NewScratch(workDirectory), "out.pdf");
+ List<string> args = ["-sDEVICE=pdfwrite", "-dPDFSETTINGS=" + settings, "-dCompatibilityLevel=1.6", "-dAutoRotatePages=/None"];
+ await RunAsync(gs, args, target, input, cancellationToken, progress: null);
+ File.Move(target, output, overwrite: true);
+ }
+
private static async Task<IReadOnlyList<string>> ToPdfAsync(string gs, ConversionStep step, CancellationToken ct, IProgress<double>? progress)
{
var output = step.Output.Allocate("pdf");
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index aabfe58b..2e8c3f22 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -684,6 +684,37 @@ public class RenderTests
Assert.True(preset.Image.KeepEnclosedBackground);
}
+ [AvaloniaFact]
+ public void Preset_editor_shows_and_saves_pdf_compression()
+ {
+ TestServices.EnsureInitialized("ko");
+ var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "compress-pdf");
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<Filee.Core.Localization.ILocalizer>());
+ Assert.True(vm.ShowPdfCompression);
+ Assert.True(vm.ShowPdfCompressionOptions);
+ Assert.Equal(Filee.Core.Presets.PdfCompression.Ebook, vm.CompressionLevel.Value);
+ Assert.Equal(["None", "Screen", "Ebook", "Print"], vm.CompressionLevels.Select(c => c.Value.ToString()));
+ var window = new PresetEditorWindow { DataContext = vm, Height = 900 };
+ window.Show();
+ Pump();
+ Save(window, "preset-compress-pdf-ko.png");
+ window.Close();
+
+ vm.CompressionLevel = vm.CompressionLevels.Single(c => c.Value == Filee.Core.Presets.PdfCompression.Screen);
+ vm.CompressWithGhostscript = true;
+ vm.KeepMetadata = false;
+ Assert.True(vm.Apply());
+ Assert.Equal(Filee.Core.Presets.PdfCompression.Screen, preset.Pdf.Compression);
+ Assert.True(preset.Pdf.CompressWithGhostscript);
+ Assert.False(preset.Image.KeepMetadata);
+
+ // Off: Ghostscript and metadata have nothing to do. Other targets don't compress PDFs at all.
+ vm.CompressionLevel = vm.CompressionLevels[0];
+ Assert.False(vm.ShowPdfCompressionOptions);
+ vm.Target = vm.Targets.Single(t => t.Value == "png");
+ Assert.False(vm.ShowPdfCompression);
+ }
+
[AvaloniaTheory]
[InlineData("en")]
[InlineData("ko")]
diff --git a/tests/Filee.App.Tests/ToastWindowTests.cs b/tests/Filee.App.Tests/ToastWindowTests.cs
index 72784ad5..5dd64d32 100644
--- a/tests/Filee.App.Tests/ToastWindowTests.cs
+++ b/tests/Filee.App.Tests/ToastWindowTests.cs
@@ -51,6 +51,21 @@ public class ToastWindowTests
}
}
+ [AvaloniaFact]
+ public void A_note_on_a_converted_file_is_shown_under_the_card()
+ {
+ TestServices.EnsureInitialized("en");
+ var conversion = new ConversionJob(["C:/scan.pdf", "C:/photos.pdf"], new Preset { TargetFormat = "pdf" }, "Compress PDF");
+ conversion.Files[0].State = FileState.Done;
+ conversion.Files[0].NoticeKey = "notice.pdf_not_smaller";
+ conversion.Files[1].State = FileState.Done;
+ var job = new JobViewModel(conversion, AppHost.Get<ILocalizer>(), AppHost.Get<IPlatformServices>(), _ => { });
+
+ Assert.True(job.HasNotices);
+ Assert.Equal("scan.pdf — Couldn't make it smaller, so it was copied as it is", job.Notices);
+ Assert.False(job.HasErrors);
+ }
+
private static int Cards(ToastWindow toast) =>
toast.GetVisualDescendants().OfType<ItemsControl>().Single(c => c.Name == "Jobs").ItemsPanelRoot?.Children.Count ?? 0;
diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs
index fd57353f..7d2c6af6 100644
--- a/tests/Filee.Cli.Tests/CliTests.cs
+++ b/tests/Filee.Cli.Tests/CliTests.cs
@@ -76,6 +76,30 @@ public sealed class CliTests : IDisposable
Assert.EndsWith("a.webp", file.GetProperty("outputs")[0].GetString());
}
+ [Fact]
+ public async Task Compress_pdf_says_when_a_pdf_cant_get_smaller()
+ {
+ var source = Path.Combine(_folder, "scan.pdf");
+ using (var image = new ImageMagick.MagickImage("gradient:#C04020-#2060C0", 1800, 1800))
+ {
+ image.AddNoise(ImageMagick.NoiseType.Gaussian, 0.6);
+ image.Density = new ImageMagick.Density(600);
+ image.Write(source, ImageMagick.MagickFormat.Pdf);
+ }
+
+ var (code, output, errors) = await Run("convert", source, "--preset", "compress-pdf", "--json");
+ Assert.Equal(Cli.Success, code);
+ var compressed = Path.Combine(_folder, "scan_compressed.pdf");
+ Assert.True(new FileInfo(compressed).Length < new FileInfo(source).Length / 2, errors);
+ using (var json = JsonDocument.Parse(output))
+ Assert.False(json.RootElement.GetProperty("files")[0].TryGetProperty("notice", out _));
+
+ // Compressed already: written unchanged, with a note.
+ (code, output, _) = await Run("convert", compressed, "--preset", "compress-pdf");
+ Assert.Equal(Cli.Success, code);
+ Assert.Contains("scan_compressed_compressed.pdf (Couldn't make it smaller", output);
+ }
+
[Fact]
public async Task A_folder_converts_the_files_filee_knows()
{
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 36e7c4bc..963a1e45 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -570,6 +570,63 @@ public class UserDataStoreTests
Assert.Single(presets, p => p.Id == "rotate-left"); // repaired, not added twice
}
+ [Fact]
+ public void Version_17_libraries_get_compress_pdf_after_split_pdf_on_no_donut()
+ {
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id == "compress-pdf");
+ var profiles = BuiltInData.CreateProfiles();
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(17, presets, profiles));
+
+ var compress = presets.Single(p => p.Id == "compress-pdf");
+ Assert.Equal(("pdf", PdfCompression.Ebook, false), (compress.TargetFormat, compress.Pdf.Compression, compress.Pdf.CompressWithGhostscript));
+ Assert.Equal("pdf-split", presets[presets.IndexOf(compress) - 1].Id); // where a new library has it
+ Assert.DoesNotContain(profiles, p => p.PresetIds.Contains("compress-pdf"));
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "pdf").PresetIds, profiles.Single(p => p.Id == "pdf").PresetIds);
+ Assert.False(SettingsMigrations.ApplyToLibrary(17, presets, profiles)); // once only
+ }
+
+ [Fact]
+ public void Back_from_an_older_Filee_compress_pdf_compresses_again_and_keeps_the_users_changes()
+ {
+ // What a Filee before 20 leaves after saving: the compression level dropped, the rest as it was.
+ var presets = BuiltInData.CreatePresets();
+ var compress = presets.Single(p => p.Id == "compress-pdf");
+ compress.Pdf.Compression = PdfCompression.None;
+ compress.Name = "Shrink";
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(17, presets, BuiltInData.CreateProfiles()));
+
+ Assert.Equal(PdfCompression.Ebook, compress.Pdf.Compression);
+ Assert.Equal("Shrink", compress.Name);
+ Assert.Single(presets, p => p.Id == "compress-pdf");
+ }
+
+ [Fact]
+ public void Pdf_compression_survives_a_save_and_load_and_a_newer_level_reads_as_none()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ var preset = store.Presets.Single(p => p.Id == "compress-pdf");
+ preset.Pdf.Compression = PdfCompression.Print;
+ preset.Pdf.CompressWithGhostscript = true;
+ store.SaveLibrary();
+
+ var reloaded = new UserDataStore(dir.Path);
+ reloaded.Load();
+ var pdf = reloaded.Presets.Single(p => p.Id == "compress-pdf").Pdf;
+ Assert.Equal((PdfCompression.Print, true), (pdf.Compression, pdf.CompressWithGhostscript));
+
+ var path = Path.Combine(dir.Path, "presets.json");
+ File.WriteAllText(path, File.ReadAllText(path).Replace("\"compression\": \"Print\"", "\"compression\": \"Extreme\""));
+ var newer = new UserDataStore(dir.Path);
+ newer.Load();
+ Assert.Equal(PdfCompression.None, newer.FindPreset("compress-pdf")!.Pdf.Compression);
+ Assert.False(File.Exists(path + ".broken"));
+ }
+
[Fact]
public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles()
{
diff --git a/tests/Filee.Engines.Tests/PdfCompressionTests.cs b/tests/Filee.Engines.Tests/PdfCompressionTests.cs
new file mode 100644
index 00000000..bdea2285
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PdfCompressionTests.cs
@@ -0,0 +1,373 @@
+// PDF → smaller PDF ("Compress PDF"): pictures scaled down to the level's resolution where they are drawn (also inside
+// forms), soft masks kept, text untouched, page ranges and one file per page, nothing made bigger, password-protected
+// files refused like the other PDF conversions, and Ghostscript's rewrite when it is installed. The PDFs are built in
+// the tests: photos (noise, so they don't compress to nothing) drawn small at a high resolution, and Helvetica text.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Pdf;
+using Filee.Engines.Vector;
+using ImageMagick;
+using PdfSharp.Drawing;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.IO;
+using PigDocument = UglyToad.PdfPig.PdfDocument;
+
+namespace Filee.Engines.Tests;
+
+public class PdfCompressionTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const string Sentence = "Quarterly report with photos";
+
+ private static bool GhostscriptInstalled => GhostscriptConverter.Locate() is not null;
+
+ /// <summary>A photo-like picture: a gradient with noise, so JPEG and Flate can't make it tiny.</summary>
+ private static string Photo(string folder, string name, uint width, uint height, MagickFormat format, bool transparentCorner = false)
+ {
+ using var image = new MagickImage("gradient:#C04020-#2060C0", width, height);
+ image.AddNoise(NoiseType.Gaussian, 0.6);
+ if (transparentCorner)
+ {
+ image.Alpha(AlphaOption.Set);
+ using var pixels = image.GetPixels();
+ pixels.SetArea(0, 0, width / 4, height / 4, new byte[width / 4 * (height / 4) * image.ChannelCount]);
+ }
+ image.Quality = 95;
+ var path = Path.Combine(folder, name);
+ image.Write(path, format);
+ return path;
+ }
+
+ /// <summary>
+ /// <paramref name="pages"/> pages, each with a line of text and a 2400 × 1600 picture drawn 3 × 2 inches (800 dpi).
+ /// </summary>
+ private static string ReportPdf(string folder, int pages = 1, MagickFormat format = MagickFormat.Jpeg, bool transparent = false)
+ {
+ var picture = Photo(folder, format == MagickFormat.Jpeg ? "photo.jpg" : "photo.png", 2400, 1600, format, transparent);
+ var pdf = new PdfBuilder();
+ for (var i = 1; i <= pages; i++)
+ {
+ pdf.NewPage();
+ pdf.Line($"{Sentence} {i}", 14, pdf.Font(), 72, 72);
+ pdf.Picture(picture, 72, 100, 216, 144);
+ }
+ return pdf.Save(Path.Combine(folder, "report.pdf"));
+ }
+
+ private static Preset Compress(PdfCompression level = PdfCompression.Ebook, bool ghostscript = false) => new()
+ {
+ TargetFormat = "pdf",
+ Pdf = { Compression = level, CompressWithGhostscript = ghostscript },
+ Output = { FileNamePattern = "{name}_compressed" },
+ };
+
+ private static void AssertDone(ConversionJob job)
+ {
+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));
+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");
+ }
+
+ /// <summary>Width and height in pixels of every picture on every page, with whether it has a soft mask.</summary>
+ private static List<(int Width, int Height, bool Masked)> Pictures(string path)
+ {
+ using var pdf = PigDocument.Open(path);
+ return pdf.GetPages().SelectMany(p => p.GetImages())
+ .Select(i => (i.WidthInSamples, i.HeightInSamples, i.MaskImage is not null))
+ .ToList();
+ }
+
+ private static List<string> Texts(string path)
+ {
+ using var pdf = PigDocument.Open(path);
+ return pdf.GetPages().Select(p => p.Text).ToList();
+ }
+
+ [Theory]
+ [InlineData(PdfCompression.Screen, 216)]
+ [InlineData(PdfCompression.Ebook, 450)]
+ [InlineData(PdfCompression.Print, 900)]
+ public async Task Pictures_are_scaled_to_the_level_resolution_and_text_stays(PdfCompression level, int expectedWidth)
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, pages: 2);
+
+ var job = await fx.ConvertAsync([source], Compress(level));
+
+ AssertDone(job);
+ var output = job.Outputs.Single();
+ Assert.Equal("report_compressed.pdf", Path.GetFileName(output));
+ Assert.True(new FileInfo(output).Length < new FileInfo(source).Length / 4, $"{new FileInfo(output).Length} of {new FileInfo(source).Length}");
+ Assert.Equal(Texts(source), Texts(output));
+ Assert.All(Pictures(output), p => Assert.InRange(p.Width, expectedWidth - 2, expectedWidth + 2));
+ Assert.All(Pictures(output), p => Assert.Equal(p.Width * 2 / 3, p.Height, 2.0));
+ Assert.Null(job.Files.Single().NoticeKey);
+ }
+
+ [Fact]
+ public async Task A_picture_embedded_on_every_page_is_stored_once()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, pages: 3, format: MagickFormat.Png, transparent: true);
+ using (var input = PdfReader.Open(source, PdfDocumentOpenMode.Import))
+ Assert.Equal(6, ImagesOf(input).Count); // three pictures, three soft masks
+
+ var job = await fx.ConvertAsync([source], Compress());
+
+ AssertDone(job);
+ using var output = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);
+ Assert.Equal(2, ImagesOf(output).Count);
+ Assert.Equal(3, Pictures(job.Outputs.Single()).Count(p => p.Masked));
+ }
+
+ [Fact]
+ public async Task A_transparent_picture_keeps_its_soft_mask()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, format: MagickFormat.Png, transparent: true);
+ Assert.True(Pictures(source).Single().Masked);
+
+ var job = await fx.ConvertAsync([source], Compress(PdfCompression.Screen));
+
+ AssertDone(job);
+ var output = job.Outputs.Single();
+ Assert.True(new FileInfo(output).Length < new FileInfo(source).Length);
+ var picture = Pictures(output).Single();
+ Assert.True(picture.Masked);
+ Assert.InRange(picture.Width, 214, 218);
+
+ using var pdf = PigDocument.Open(output);
+ var mask = pdf.GetPage(1).GetImages().Single().MaskImage!;
+ Assert.Equal(picture.Width, mask.WidthInSamples);
+ // The transparent corner is still transparent, the rest still opaque.
+ Assert.True(mask.TryGetPng(out var png));
+ using var alpha = new MagickImage(png);
+ using var values = alpha.GetPixels();
+ Assert.True(values.GetPixel(2, 2).GetChannel(0) < 16);
+ Assert.True(values.GetPixel((int)alpha.Width - 3, (int)alpha.Height - 3).GetChannel(0) > 240);
+ }
+
+ [Fact]
+ public async Task Gray_pictures_stay_gray()
+ {
+ var dir = fx.NewFolder();
+ var photo = Photo(dir, "gray.jpg", 2000, 2000, MagickFormat.Jpeg);
+ using (var gray = new MagickImage(photo))
+ {
+ gray.Grayscale();
+ gray.Write(photo, MagickFormat.Jpeg);
+ }
+ var pdf = new PdfBuilder().NewPage();
+ pdf.Picture(photo, 72, 72, 144, 144);
+ var source = pdf.Save(Path.Combine(dir, "gray.pdf"));
+
+ var job = await fx.ConvertAsync([source], Compress());
+
+ AssertDone(job);
+ using var output = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);
+ var image = ImagesOf(output).Single();
+ Assert.Equal("/DeviceGray", image.Elements.GetName("/ColorSpace"));
+ Assert.Equal(300, image.Elements.GetInteger("/Width"));
+ Assert.Equal("/DCTDecode", image.Elements.GetName("/Filter"));
+ }
+
+ [Fact]
+ public async Task Pictures_in_forms_are_sized_where_the_form_draws_them()
+ {
+ var dir = fx.NewFolder();
+ var photo = Photo(dir, "photo.jpg", 3000, 3000, MagickFormat.Jpeg);
+ var source = Path.Combine(dir, "form.pdf");
+ using (var document = new PdfDocument())
+ {
+ var page = document.AddPage();
+ // The form holds the picture at 1000 × 1000 points; the page draws the form at a tenth: 100 pt = 1.39 in.
+ var form = new XForm(document, XUnit.FromPoint(1000), XUnit.FromPoint(1000));
+ using (var image = XImage.FromFile(photo))
+ using (var formGraphics = XGraphics.FromForm(form))
+ formGraphics.DrawImage(image, 0, 0, 1000, 1000);
+ using (var graphics = XGraphics.FromPdfPage(page))
+ graphics.DrawImage(form, 72, 72, 100, 100);
+ document.Save(source);
+ }
+
+ var job = await fx.ConvertAsync([source], Compress(PdfCompression.Ebook));
+
+ AssertDone(job);
+ using var output = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);
+ // 100 pt at 150 dpi = 208 px.
+ Assert.InRange(ImagesOf(output).Single().Elements.GetInteger("/Width"), 206, 210);
+ }
+
+ [Fact]
+ public async Task Page_ranges_and_one_file_per_page_are_compressed_too()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, pages: 3);
+
+ var range = Compress();
+ range.Pdf.PageRange = "2";
+ var one = await fx.ConvertAsync([source], range);
+ var split = Compress();
+ split.Pdf.SplitPages = true;
+ var each = await fx.ConvertAsync([source], split);
+
+ AssertDone(one);
+ Assert.Equal([$"{Sentence} 2"], Texts(one.Outputs.Single()));
+ Assert.InRange(Pictures(one.Outputs.Single()).Single().Width, 448, 452);
+ AssertDone(each);
+ Assert.Equal(["report_compressed_p1.pdf", "report_compressed_p2.pdf", "report_compressed_p3.pdf"],
+ each.Outputs.Select(Path.GetFileName).Order(StringComparer.Ordinal));
+ Assert.All(each.Outputs, o => Assert.InRange(Pictures(o).Single().Width, 448, 452));
+ }
+
+ [Fact]
+ public async Task Bookmarks_survive_when_the_whole_file_is_compressed()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, pages: 2);
+ using (var document = PdfReader.Open(source, PdfDocumentOpenMode.Modify))
+ {
+ document.Outlines.Add("Second page", document.Pages[1]);
+ document.Save(source);
+ }
+
+ var job = await fx.ConvertAsync([source], Compress());
+
+ AssertDone(job);
+ using var output = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);
+ Assert.Equal("Second page", output.Outlines.Single().Title);
+ }
+
+ [Fact]
+ public async Task Page_metadata_goes_only_when_the_preset_drops_it()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir);
+ using (var document = PdfReader.Open(source, PdfDocumentOpenMode.Modify))
+ {
+ document.Pages[0].Elements["/Metadata"] = Xmp(document, "filee-page-xmp").Reference;
+ // A large packet, as image editors leave them: PDFsharp writes the document's XMP afresh, so the old one goes.
+ document.Internals.Catalog.Elements["/Metadata"] = Xmp(document, "filee-document-xmp" + new string(' ', 20_000)).Reference;
+ document.Save(source);
+ }
+
+ var keep = await fx.ConvertAsync([source], Compress());
+ var drop = Compress();
+ drop.Image.KeepMetadata = false;
+ drop.Output.FileNamePattern = "{name}_stripped";
+ var dropped = await fx.ConvertAsync([source], drop);
+
+ AssertDone(keep);
+ AssertDone(dropped);
+ Assert.Contains("filee-page-xmp", Latin1(keep.Outputs.Single()));
+ Assert.DoesNotContain("filee-page-xmp", Latin1(dropped.Outputs.Single()));
+ Assert.DoesNotContain("filee-document-xmp", Latin1(keep.Outputs.Single()));
+ Assert.DoesNotContain("filee-document-xmp", Latin1(dropped.Outputs.Single()));
+
+ static PdfDictionary Xmp(PdfDocument document, string text)
+ {
+ var xmp = new PdfDictionary(document);
+ xmp.Elements.SetName("/Type", "/Metadata");
+ xmp.Elements.SetName("/Subtype", "/XML");
+ xmp.CreateStream(System.Text.Encoding.ASCII.GetBytes($"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><!-- {text} --></x:xmpmeta>"));
+ document.Internals.AddObject(xmp);
+ return xmp;
+ }
+ }
+
+ [Fact]
+ public async Task A_pdf_that_cant_get_smaller_is_copied_as_it_is_with_a_notice()
+ {
+ var dir = fx.NewFolder();
+ // Compressed once already: nothing left to gain the second time.
+ var once = (await fx.ConvertAsync([ReportPdf(dir)], Compress(PdfCompression.Screen))).Outputs.Single();
+
+ var job = await fx.ConvertAsync([once], Compress(PdfCompression.Screen));
+
+ AssertDone(job);
+ Assert.Equal(File.ReadAllBytes(once), File.ReadAllBytes(job.Outputs.Single()));
+ Assert.Equal("notice.pdf_not_smaller", job.Files.Single().NoticeKey);
+ }
+
+ [Fact]
+ public async Task A_pdf_without_pictures_never_gets_bigger()
+ {
+ var dir = fx.NewFolder();
+ var pdf = new PdfBuilder().NewPage();
+ var y = 72.0;
+ for (var i = 0; i < 40; i++)
+ y = pdf.Paragraph($"Line {i}: the quick brown fox jumps over the lazy dog.", 10, pdf.Font(), 72, y, 450, 14);
+ var source = pdf.Save(Path.Combine(dir, "text.pdf"));
+
+ var job = await fx.ConvertAsync([source], Compress(PdfCompression.Screen));
+
+ AssertDone(job);
+ Assert.True(new FileInfo(job.Outputs.Single()).Length <= new FileInfo(source).Length);
+ Assert.Equal(Texts(source), Texts(job.Outputs.Single()));
+ }
+
+ [Fact]
+ public async Task Password_protected_pdf_fails_with_a_clear_message()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir);
+ PdfBuilder.Protect(source, "1234");
+
+ var job = await fx.ConvertAsync([source], Compress());
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("password", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);
+ Assert.Empty(job.Outputs);
+ }
+
+ [Fact]
+ public async Task A_pdf_locked_only_against_changes_is_compressed_like_a_split_one()
+ {
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, pages: 2);
+ using (var document = PdfReader.Open(source, PdfDocumentOpenMode.Modify))
+ {
+ document.SecuritySettings.OwnerPassword = "owner";
+ document.Save(source);
+ }
+
+ var job = await fx.ConvertAsync([source], Compress());
+
+ AssertDone(job);
+ Assert.True(new FileInfo(job.Outputs.Single()).Length < new FileInfo(source).Length / 4);
+ Assert.Equal(Texts(source), Texts(job.Outputs.Single()));
+ }
+
+ [Fact]
+ public async Task Ghostscript_is_used_when_asked_and_installed()
+ {
+ Assert.SkipUnless(GhostscriptInstalled, "Ghostscript is not installed (pwsh build/fetch-engines.ps1 -Only ghostscript).");
+ var dir = fx.NewFolder();
+ var source = ReportPdf(dir, pages: 2);
+
+ var job = await fx.ConvertAsync([source], Compress(PdfCompression.Screen, ghostscript: true));
+
+ AssertDone(job);
+ var output = job.Outputs.Single();
+ Assert.True(new FileInfo(output).Length < new FileInfo(source).Length / 4);
+ Assert.Equal(Texts(source).Select(Words), Texts(output).Select(Words));
+ Assert.All(Pictures(output), p => Assert.True(p.Width <= 300, $"{p.Width} px"));
+ }
+
+ [Fact]
+ public void Compression_adds_no_route()
+ {
+ // PDF → PDF stays one PDFsharp step; Ghostscript is called from it, never planned.
+ var planner = fx.Catalog.CreatePlanner(["ghostscript"]);
+ Assert.Equal("pdfsharp", string.Join(',', planner.Plan("pdf", "pdf")!.Steps.Select(s => s.Converter.Id)));
+ Assert.Equal("pdfium", string.Join(',', planner.Plan("pdf", "png")!.Steps.Select(s => s.Converter.Id)));
+ Assert.Equal("ghostscript", string.Join(',', planner.Plan("pdf", "eps")!.Steps.Select(s => s.Converter.Id)));
+ Assert.Equal("docx-writer", string.Join(',', planner.Plan("pdf", "docx")!.Steps.Select(s => s.Converter.Id)));
+ }
+
+ private static string Words(string text) => string.Concat(text.Where(c => !char.IsWhiteSpace(c)));
+
+ private static string Latin1(string path) => System.Text.Encoding.Latin1.GetString(File.ReadAllBytes(path));
+
+ private static List<PdfDictionary> ImagesOf(PdfDocument document) =>
+ [.. document.Internals.GetAllObjects().OfType<PdfDictionary>().Where(d => d.Elements.GetName("/Subtype") == "/Image")];
+}