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.

PDF → PPTX: a picture of each page on its own slide (#96)

KnifeLemone52db60f5148
diff --git a/README.ko.md b/README.ko.md
index 75e2cac9..ecff8809 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -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, PPTX(페이지마다 그림 한 장), SVG²; 합치기, 나누기, 페이지 범위 |
| **문서**: 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..0d42046d 100644
--- a/README.md
+++ b/README.md
@@ -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, PPTX (a picture of each page), SVG²; merge, split, page ranges |
| **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..754801fe 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -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、PPTX(每页一张图片)、SVG²;合并、拆分、页码范围 |
| **文档**: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/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 9965fd3d..843fcc0f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -40,7 +40,9 @@
3. **Drop** – the slice under the cursor is a preset. `ConversionService.Start` enqueues a `ConversionJob`.
The drop is always reported as *Copy* so Explorer never deletes the source files.
4. **Plan** – for every file, `RoutePlanner` finds the cheapest chain of converter edges from the source format to
- the target (at most 3 hops). Engine priority (Settings → Engines) breaks ties.
+ the target (at most 3 hops). Engine priority (Settings → Engines) breaks ties. Some edges are limited: tracing
+ only starts from raster images (`ImageSourcesOnly`), and PDF → PPTX picture slides are only ever a route of their
+ own (`DirectOnly`), never a step of a longer one.
5. **Run** – `JobQueue` runs steps with per-engine concurrency limits. Intermediate files live in a temp folder;
final outputs are named by `OutputPathResolver` (pattern, folder, conflict policy; the source is never overwritten).
"Merge into one PDF" converts each file to PDF and merges with PDFsharp.
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index b6c6ca01..d2c15753 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -18,6 +18,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/PPSX), PDF, HTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |
| **DOCX writer** | built in | **HWPX (and HWP through rhwp), PDF, HTML, EPUB, MOBI/AZW3, FB2, Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants) → DOCX** |
| PDF text | built in (PdfPig) | **PDF → TXT** (reading order, also two columns; no OCR) |
+| PDF slides | built in (PDFium, PdfPig) | **PDF → PPTX**: a picture of each page on its own slide (looks like the PDF, not editable), the page's text in the speaker notes |
| E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML** |
| Data | built in (System.Text.Json, YamlDotNet, Tomlyn, System.Xml) | **JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other** (CSV for tables); **vCard ↔ CSV**; spreadsheets and contacts reach JSON / YAML / TOML / XML through CSV |
| **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ → EPUB, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) |
@@ -374,6 +375,33 @@ 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 → PPTX
+
+`Pdf/PdfSlidesConverter.cs` turns a PDF into a PowerPoint deck of pictures: every page is rendered (PDFium, as for
+PDF → images) and becomes one picture on its own slide. The slides look exactly like the PDF but are **not
+editable**: there are no text boxes to change, the PDF's layout is not rebuilt. PDF → DOCX is the editable route.
+
+- **Slide size** is the first page's own size (an A4 portrait PDF gives A4 portrait slides, a PDF exported from a
+ 16:9 deck gives 16:9 slides), within PowerPoint's limits of 1 to 56 inches a side. Every page, also one of another
+ size or orientation (pages turned in the PDF are shown turned), is fitted onto the slide without cropping and
+ centred on white.
+- **Resolution** is the preset's render DPI, at least 150 and at most 600; a page larger than 25 megapixels at that
+ resolution (a poster) is rendered at a lower one. The preset's page range picks the pages.
+- **Pictures** are JPEG at the preset's quality (90 by default, as the "PPTX (slides)" preset sets it). Pages are
+ rendered on white, as PDF viewers show them, so they have no transparency that would need PNG, and JPEG keeps a
+ long deck at a size that is easy to send (an A4 text page at 150 dpi is a few hundred KB).
+- **Speaker notes** hold the page's text, read like PDF → TXT (reading order, the invisible OCR layer of scans
+ included), so it can still be searched and copied. Pages without text get no notes; when PdfPig cannot read a PDF
+ that PDFium renders, the deck is written without notes.
+- The package (`Pdf/PictureDeckWriter.cs`) is written by hand: presentation, one slide master with a blank layout,
+ a theme, the slides with their pictures, a notes master and notes slides, and the document properties. The tests
+ validate it with the Open XML SDK and read it back with Filee's own PPTX reader.
+- The edge is `DirectOnly`: the route planner uses it only for a PDF converted to PPTX. A Word document or an image is
+ never turned into picture slides through PDF, and a picture deck is never a step towards ODP, PPSX or another
+ format (a test checks that every other pair of formats keeps its route).
+
+Password-protected PDFs fail with the same message as PDF → DOCX.
+
## 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..c18acf95 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -75,6 +75,7 @@
"engine.hwpx-writer.description": "Writes HWPX from Word, Excel, PowerPoint, PDF, HTML, e-books and Markdown.\nThe first step of turning documents into PDF without Office.",
"engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.",
"engine.pdf-text.description": "Extracts the text of PDFs in reading order, also from two-column pages (no OCR for scans).",
+ "engine.pdf-slides.description": "Turns PDFs into PowerPoint slides: each page becomes a picture on its own slide (looks like the PDF, not editable), with the page text in the speaker notes.",
"engine.email.description": "E-mails (EML, Outlook MSG) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.\nMSG to EML.",
"engine.data.description": "JSON, JSON Lines, YAML, TOML, XML and CSV into each other.\nvCard contacts to CSV and back.\nComments are dropped. CSV holds tables only.",
"engine.vector.description": "SVG and SVGZ to vector PDF, images and DXF; pictures traced into SVG; Illustrator files saved with PDF content.",
@@ -128,6 +129,7 @@
"preset.merge_pdf": "Merge PDF",
"preset.split_pdf": "Split PDF",
"preset.long_image": "Long image",
+ "preset.pdf_slides": "PPTX (slides)",
"preset.extract": "Extract",
"preset.zip_all": "One ZIP",
"preset.extract_subtitles": "Extract subtitles",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 911d0f3b..0d04167f 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -75,6 +75,7 @@
"engine.hwpx-writer.description": "워드, 엑셀, 파워포인트, PDF, HTML, 전자책, 마크다운을 HWPX로 써요.\n오피스 없이 문서를 PDF로 바꾸는 첫 단계예요.",
"engine.docx-writer.description": "PDF, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.",
"engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요.\n2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).",
+ "engine.pdf-slides.description": "PDF를 파워포인트 슬라이드로 바꿔요. 페이지마다 그림 한 장으로 슬라이드에 넣어서 PDF와 똑같이 보여요(편집은 안 돼요).\n페이지 글자는 슬라이드 노트에 넣어요.",
"engine.email.description": "이메일(EML, Outlook MSG)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.\nMSG는 EML로도 바꿔요.",
"engine.data.description": "JSON, JSON Lines, YAML, TOML, XML, CSV를 서로 바꿔요.\nvCard 연락처를 CSV로, CSV를 vCard로 바꿔요.\n주석은 빠져요. CSV는 표 모양 데이터만 담아요.",
"engine.vector.description": "SVG·SVGZ를 벡터 PDF, 이미지, DXF로 바꾸고 그림을 SVG로 벡터화해요. PDF 내용이 들어 있는 일러스트레이터 파일도 변환해요.",
@@ -128,6 +129,7 @@
"preset.merge_pdf": "PDF 병합",
"preset.split_pdf": "PDF 분할",
"preset.long_image": "긴 이미지",
+ "preset.pdf_slides": "PPTX (슬라이드)",
"preset.extract": "압축 풀기",
"preset.zip_all": "ZIP 하나로",
"preset.extract_subtitles": "자막 추출",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index d6f4f5b8..60b96a21 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -75,6 +75,7 @@
"engine.hwpx-writer.description": "把 Word、Excel、PowerPoint、PDF、HTML、电子书和 Markdown 写成 HWPX。\n这是不用 Office 把文档转为 PDF 的第一步。",
"engine.docx-writer.description": "用 PDF、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。",
"engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。",
+ "engine.pdf-slides.description": "将 PDF 转换为 PowerPoint 幻灯片。每页作为一张图片放在单独的幻灯片上,外观与 PDF 相同(不可编辑),页面文字放入演讲者备注。",
"engine.email.description": "将电子邮件(EML、Outlook MSG)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。\nMSG 也可转为 EML。",
"engine.data.description": "JSON、JSON Lines、YAML、TOML、XML、CSV 互相转换。\nvCard 联系人与 CSV 互转。\n注释不保留。CSV 仅支持表格数据。",
"engine.vector.description": "将 SVG、SVGZ 转为矢量 PDF、图片和 DXF,并可将图片描摹为 SVG。也支持包含 PDF 内容的 Illustrator 文件。",
@@ -128,6 +129,7 @@
"preset.merge_pdf": "合并 PDF",
"preset.split_pdf": "拆分 PDF",
"preset.long_image": "长图",
+ "preset.pdf_slides": "PPTX(幻灯片)",
"preset.extract": "解压",
"preset.zip_all": "打包成一个 ZIP",
"preset.extract_subtitles": "提取字幕",
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index aac27e41..0e4da67c 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -22,8 +22,13 @@ namespace Filee.Core.Conversion;
/// The opposite: never used in routes that start from a raster image. PDF → SVG through LibreOffice keeps a PDF's
/// vectors, but a photo that became a PDF would only come back as a picture inside an SVG, so images are traced.
/// </param>
+/// <param name="DirectOnly">
+/// The edge is a route of its own only: the file being converted is a <paramref name="From"/> file and
+/// <paramref name="To"/> is what the user asked for. PDF → PPTX puts pictures of the pages on slides; a Word document
+/// rendered to PDF must not become pictures on slides, and a picture deck must not be a step towards ODP or PPSX.
+/// </param>
public readonly record struct ConversionEdge(
- string From, string To, int Cost = 10, bool ImageSourcesOnly = false, bool NotForImageSources = false);
+ string From, string To, int Cost = 10, bool ImageSourcesOnly = false, bool NotForImageSources = false, bool DirectOnly = false);
/// <summary>Whether an engine can currently be used.</summary>
/// <param name="IsAvailable">True if conversions can run.</param>
diff --git a/src/Filee.Core/Conversion/RoutePlanner.cs b/src/Filee.Core/Conversion/RoutePlanner.cs
index dcec4a72..48573bd2 100644
--- a/src/Filee.Core/Conversion/RoutePlanner.cs
+++ b/src/Filee.Core/Conversion/RoutePlanner.cs
@@ -89,7 +89,8 @@ public sealed class RoutePlanner
foreach (var (converter, edge, edgeCost) in EdgesFrom(node))
{
- if (edge.To == edge.From || (edge.ImageSourcesOnly && !imageSource) || (edge.NotForImageSources && imageSource))
+ if (edge.To == edge.From || (edge.ImageSourcesOnly && !imageSource) || (edge.NotForImageSources && imageSource)
+ || (edge.DirectOnly && (node != from || edge.To != to)))
continue;
var next = cost + edgeCost;
if (dist.TryGetValue(edge.To, out var known) && known <= next)
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index c47d818d..fd6ed8a3 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}" },
},
+ .. PdfSlidesPresets(),
new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
.. HwpPresets(),
@@ -81,6 +82,15 @@ public static class BuiltInData
.. TracePresets(),
];
+ /// <summary>
+ /// PDF → PowerPoint with a picture of each page on its own slide (added in settings schema 18). JPEG at 90 like the
+ /// JPG preset; the render DPI is the PDF default (150), which the converter never goes below.
+ /// </summary>
+ public static List<Preset> PdfSlidesPresets() =>
+ [
+ new() { Id = "pdf-slides", NameKey = "preset.pdf_slides", TargetFormat = "pptx", Image = { Quality = 90 } },
+ ];
+
/// <summary>Raster → SVG tracing, in colour and as black line art (added in settings schema 16).</summary>
public static List<Preset> TracePresets() =>
[
@@ -289,7 +299,7 @@ public static class BuiltInData
{
Id = "pdf", NameKey = "profile.pdf",
Extensions = ["pdf"],
- PresetIds = ["to-png", "to-jpg", "pdf-long-image", "to-docx", "to-txt", "to-md", "to-epub", "to-hwpx", "to-hwp", "to-tiff", "pdf-split", "merge-pdf"],
+ PresetIds = [.. PdfDonut],
},
new()
{
@@ -316,6 +326,17 @@ public static class BuiltInData
},
];
+ /// <summary>
+ /// The PDF donut. Settings schema 18 put "PPTX (slides)" after DOCX in place of TIFF (a donut holds 12 slices); TIFF
+ /// stays a preset to add in Settings → Toolbar.
+ /// </summary>
+ public static readonly IReadOnlyList<string> PdfDonut =
+ ["to-png", "to-jpg", "pdf-long-image", "to-docx", "pdf-slides", "to-txt", "to-md", "to-epub", "to-hwpx", "to-hwp", "pdf-split", "merge-pdf"];
+
+ /// <summary>The PDF donut of settings schema 9 to 17, which schema 18 replaces when the user never changed it.</summary>
+ public static readonly IReadOnlyList<string> PdfDonutBefore18 =
+ ["to-png", "to-jpg", "pdf-long-image", "to-docx", "to-txt", "to-md", "to-epub", "to-hwpx", "to-hwp", "to-tiff", "pdf-split", "merge-pdf"];
+
/// <summary>Excel, OpenDocument and CSV sheets (split from "office" in settings schema 5).</summary>
public static ToolbarProfile SpreadsheetProfile() => new()
{
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 1701b12f..2caa6807 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 = 18;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
@@ -89,7 +89,7 @@ public sealed class AppSettings
public List<string> EnginePriority { get; set; } =
[
"magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",
- "pdf-text", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg",
+ "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg",
"pandoc", "ghostscript", "calibre", "libreoffice",
];
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 9b0f3880..a97fbc85 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -292,6 +292,16 @@ internal static class SettingsMigrations
InsertBefore(settings.EnginePriority, "model3d", settings.EnginePriority.Contains("archive") ? "archive" : "pandoc");
}
+ // v18: built-in "pdf-slides" engine (PDF → PPTX, a picture of each page per slide), after "pdf-text".
+ if (settings.SchemaVersion < 18 && !settings.EnginePriority.Contains("pdf-slides"))
+ {
+ var text = settings.EnginePriority.IndexOf("pdf-text");
+ if (text >= 0)
+ settings.EnginePriority.Insert(text + 1, "pdf-slides");
+ else
+ InsertBefore(settings.EnginePriority, "pdf-slides", "pandoc");
+ }
+
if (settings.Triggers.Count == 0)
settings.Triggers = TriggerGesture.Defaults();
@@ -479,9 +489,32 @@ internal static class SettingsMigrations
}
}
}
+
+ // v18: PDF → PPTX ("PPTX (slides)", a picture of each page per slide), on the PDF donut after DOCX. The default
+ // PDF donut is full: one the user never changed takes it in place of TIFF, as a new library has it; a donut
+ // the user changed gets it when it has room.
+ if (from < 18)
+ changed |= AddPdfSlides(presets, profiles);
return changed;
}
+ private static bool AddPdfSlides(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ if (presets.All(p => p.Id != "pdf-slides"))
+ {
+ var at = presets.FindIndex(p => p.Id == "pdf-split");
+ presets.Insert(at < 0 ? presets.Count : at + 1, BuiltInData.PdfSlidesPresets().Single());
+ changed = true;
+ }
+ if (profiles.FirstOrDefault(p => p.Id == "pdf") is { } pdf && pdf.PresetIds.SequenceEqual(BuiltInData.PdfDonutBefore18))
+ {
+ pdf.PresetIds = [.. BuiltInData.PdfDonut];
+ return true;
+ }
+ return Offer(presets, profiles, "pdf", "pdf-slides", "to-docx") || changed;
+ }
+
private static bool AddData(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 0a2e3a42..33b16281 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -47,6 +47,7 @@ public static class EngineRegistry
new FontConverter(),
new DocxWriterConverter(),
new PdfTextConverter(),
+ new PdfSlidesConverter(),
new EmlConverter(),
new DataConverter(),
new SubtitleConverter(),
diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
index 4703e760..f25d868c 100644
--- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs
+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
@@ -183,9 +183,41 @@ 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.");
+ /// <summary>
+ /// The text of each page in <paramref name="pages"/> (zero-based), read like <see cref="ReadText"/> (reading order,
+ /// invisible OCR text included) but page by page, with running heads and page numbers kept: "" for a page without
+ /// text. Paragraphs are separated by an empty line, lines end with CR LF.
+ /// </summary>
+ public static IReadOnlyList<string> PageTexts(string path, IReadOnlyList<int> pages, CancellationToken cancellationToken = default)
+ {
+ var reader = new PdfDocumentReader(path, "", textOnly: true);
+ try
+ {
+ using var pdf = PdfDocument.Open(path, new ParsingOptions { UseLenientParsing = true, SkipMissingFonts = true });
+ var texts = new List<string>(pages.Count);
+ foreach (var index in pages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var page = reader.ReadPage(pdf.GetPage(index + 1));
+ if (page.Scanned)
+ {
+ texts.Add("");
+ continue;
+ }
+ page.Items = ReadingOrder(page.Items);
+ texts.Add(PlainText(reader.Build([page], null)).TrimEnd());
+ }
+ return texts;
+ }
+ catch (PdfDocumentEncryptedException)
+ {
+ throw PasswordProtected();
+ }
+ }
+
private PageContent ReadPage(Page page)
{
var crop = page.CropBox.Bounds;
diff --git a/src/Filee.Engines/Pdf/PdfSlidesConverter.cs b/src/Filee.Engines/Pdf/PdfSlidesConverter.cs
new file mode 100644
index 00000000..e6bd9933
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfSlidesConverter.cs
@@ -0,0 +1,165 @@
+// PDF → PPTX: one slide per page showing the page as a picture, so the slides look exactly like the PDF (they are not
+// editable). Pages are rendered with PDFium (via PDFtoImage) at the preset's resolution and written by
+// PictureDeckWriter; the text of each page (PdfPig, reading order, like PDF → TXT) goes into the slide's speaker notes,
+// so it can still be searched and copied.
+//
+// - Slide size: the first page's own size, so A4 portrait gives portrait slides and a 16:9 PDF 16:9 slides. Every
+// page, also one of another size or orientation, is fitted onto the slide without cropping and centred on white.
+// - Resolution: the preset's render DPI, at least 150 (sharp on a projector) and at most 600; a page over 25
+// megapixels at that resolution (a poster) is rendered smaller, so memory and file size stay reasonable.
+// - Pictures are JPEG at the preset's quality (90 by default). Pages are rendered on white as every PDF viewer shows
+// them, so they have no transparency that would need PNG, and JPEG keeps a 100-page deck a manageable size.
+// - The edge is DirectOnly: only a PDF becomes picture slides, and a picture deck is never a step towards another
+// format (ODP, PPSX, ...).
+
+using Filee.Core.Conversion;
+using Filee.Engines.Infrastructure;
+using PDFtoImage;
+using PDFtoImage.Exceptions;
+using SkiaSharp;
+
+// PDFtoImage marks its API for the platforms PDFium ships for; Filee only targets desktop platforms, all covered.
+#pragma warning disable CA1416
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>PDF → PPTX with a picture of each page on its own slide.</summary>
+public sealed class PdfSlidesConverter : IConverter
+{
+ internal const int MinDpi = 150;
+ internal const int MaxDpi = 600;
+
+ /// <summary>A page larger than this many pixels at the preset's resolution is rendered at a lower one.</summary>
+ internal const double MaxPagePixels = 25_000_000;
+
+ public string Id => "pdf-slides";
+ public string DisplayName => "PDF slides (built-in)";
+
+ /// <summary>PDFium renders one page at a time anyway; one deck at a time keeps memory predictable.</summary>
+ public int MaxParallelism => 1;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("pdf", "pptx", DirectOnly: true)];
+
+ public EngineStatus GetStatus() =>
+ EngineStatus.Available("PDF → PPTX", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("PDFtoImage", typeof(Conversion))}");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ var pdf = File.ReadAllBytes(step.InputPath);
+ int pageCount;
+ IList<System.Drawing.SizeF> sizes;
+ try
+ {
+ pageCount = Conversion.GetPageCount(pdf, null);
+ sizes = Conversion.GetPageSizes(pdf, null);
+ }
+ catch (PdfPasswordProtectedException)
+ {
+ throw PdfDocumentReader.PasswordProtected();
+ }
+ var pages = PageRange.Parse(step.Preset.Pdf.PageRange, pageCount);
+ if (pages.Count == 0)
+ throw new InvalidOperationException("The PDF has no pages.");
+
+ var output = step.Output.Allocate("pptx");
+ if (output is null)
+ return [];
+
+ var notes = PageTexts(step.InputPath, pages, cancellationToken);
+ progress?.Report(0.1);
+ var dpi = Math.Clamp(step.Preset.Pdf.RenderDpi, MinDpi, MaxDpi);
+ var quality = Math.Clamp(step.Preset.Image.Quality, 1, 100);
+
+ PictureDeckWriter? deck = null;
+ try
+ {
+ var done = 0;
+ // Pages that render at the same resolution go through PDFium together (one document load).
+ foreach (var run in Runs(pages, page => PageDpi(sizes[page].Width, sizes[page].Height, dpi)))
+ {
+ var options = new RenderOptions(Dpi: run.Dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White);
+ var index = 0;
+ foreach (var bitmap in Conversion.ToImages(pdf, run.Pages, null, options))
+ {
+ using (bitmap)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var page = run.Pages[index++];
+ var (width, height) = Shown(sizes[page], bitmap);
+ if (deck is null)
+ {
+ var (slideWidth, slideHeight) = PictureDeckWriter.SlideSize(width, height);
+ deck = new PictureDeckWriter(output, slideWidth, slideHeight);
+ }
+ using var jpeg = bitmap.Encode(SKEncodedImageFormat.Jpeg, quality);
+ deck.AddSlide(jpeg.AsSpan(), width, height, $"Page {page + 1}", notes?[done]);
+ }
+ done++;
+ progress?.Report(0.1 + 0.85 * done / pages.Count);
+ }
+ }
+ (deck ?? throw new InvalidOperationException("PDFium rendered no page of the PDF.")).Save();
+ }
+ finally
+ {
+ deck?.Dispose();
+ }
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+
+ /// <summary>
+ /// Resolution for a page of <paramref name="width"/> × <paramref name="height"/> points: <paramref name="dpi"/>, or
+ /// less when the page would exceed <see cref="MaxPagePixels"/>.
+ /// </summary>
+ internal static int PageDpi(double width, double height, int dpi)
+ {
+ var pixels = width / 72 * dpi * (height / 72 * dpi);
+ if (pixels <= MaxPagePixels || pixels <= 0)
+ return dpi;
+ return Math.Max(1, (int)Math.Floor(dpi * Math.Sqrt(MaxPagePixels / pixels)));
+ }
+
+ /// <summary>Consecutive pages with the same resolution.</summary>
+ private static List<(int Dpi, List<int> Pages)> Runs(IReadOnlyList<int> pages, Func<int, int> dpiOf)
+ {
+ var runs = new List<(int Dpi, List<int> Pages)>();
+ foreach (var page in pages)
+ {
+ var dpi = dpiOf(page);
+ if (runs.Count == 0 || runs[^1].Dpi != dpi)
+ runs.Add((dpi, []));
+ runs[^1].Pages.Add(page);
+ }
+ return runs;
+ }
+
+ /// <summary>
+ /// The page's size in points as it is shown: PDFium turns pages that are stored rotated, so the rendering tells
+ /// whether width and height swap.
+ /// </summary>
+ private static (double Width, double Height) Shown(System.Drawing.SizeF size, SKBitmap bitmap)
+ {
+ double width = size.Width, height = size.Height;
+ var landscapePage = width > height;
+ var landscapePicture = bitmap.Width > bitmap.Height;
+ return width != height && bitmap.Width != bitmap.Height && landscapePage != landscapePicture ? (height, width) : (width, height);
+ }
+
+ /// <summary>
+ /// Text of every page for the speaker notes, or null when PdfPig can't read the file: the pictures (PDFium) are the
+ /// conversion, the notes an extra that must not make it fail.
+ /// </summary>
+ private static IReadOnlyList<string>? PageTexts(string path, IReadOnlyList<int> pages, CancellationToken cancellationToken)
+ {
+ try
+ {
+ return PdfDocumentReader.PageTexts(path, pages, cancellationToken);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ return null;
+ }
+ }
+}
diff --git a/src/Filee.Engines/Pdf/PictureDeckWriter.cs b/src/Filee.Engines/Pdf/PictureDeckWriter.cs
new file mode 100644
index 00000000..9cc1009c
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PictureDeckWriter.cs
@@ -0,0 +1,367 @@
+// Writes a PowerPoint presentation (PPTX, PresentationML / ECMA-376) whose slides each show one picture, fitted and
+// centred, with optional speaker notes: the package PDF → PPTX needs. Written by hand like the DOCX writer (the Open XML
+// SDK is only used by the tests, which validate the output with it), as small as PowerPoint, LibreOffice Impress and
+// Keynote accept: presentation, one slide master with one blank layout, a theme, presentation / view / table style
+// properties, the slides with their pictures, a notes master and notes slides when there is text, and the document
+// properties.
+//
+// Slides and pictures are written into the ZIP as they come, so a long PDF never has all its pages in memory; the
+// parts that list them (presentation, content types) follow at the end.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using Filee.Engines.Hwp.Hwpx;
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>A PPTX of picture slides, written slide by slide.</summary>
+internal sealed class PictureDeckWriter : IDisposable
+{
+ /// <summary>EMU (English Metric Units) per point: 914400 per inch.</summary>
+ public const double EmuPerPoint = 12700;
+
+ /// <summary>Smallest slide side PowerPoint allows (1 inch, ST_SlideSizeCoordinate).</summary>
+ public const long MinSlideSide = 914400;
+
+ /// <summary>Largest slide side PowerPoint allows (56 inches, ST_SlideSizeCoordinate).</summary>
+ public const long MaxSlideSide = 51206400;
+
+ private const string Declaration = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
+ private const string Relationships = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
+ private const string PresentationTypes = "application/vnd.openxmlformats-officedocument.presentationml.";
+
+ /// <summary>Namespaces of every PresentationML part.</summary>
+ private const string Namespaces =
+ "xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" " +
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" " +
+ "xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\"";
+
+ /// <summary>The group every shape tree starts with.</summary>
+ private const string TreeStart =
+ "<p:spTree><p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>" +
+ "<p:grpSpPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"0\" cy=\"0\"/></a:xfrm></p:grpSpPr>";
+
+ private const string ColorMap =
+ "<p:clrMap bg1=\"lt1\" tx1=\"dk1\" bg2=\"lt2\" tx2=\"dk2\" accent1=\"accent1\" accent2=\"accent2\" accent3=\"accent3\" " +
+ "accent4=\"accent4\" accent5=\"accent5\" accent6=\"accent6\" hlink=\"hlink\" folHlink=\"folHlink\"/>";
+
+ /// <summary>Notes pages are portrait Letter-like, as in PowerPoint (7.5 × 10 inches).</summary>
+ private const long NotesWidth = 6858000;
+ private const long NotesHeight = 9144000;
+
+ private readonly string _path;
+ private readonly string _temp;
+ private readonly FileStream _file;
+ private readonly ZipArchive _zip;
+ private readonly List<bool> _slideHasNotes = [];
+ private bool _saved;
+
+ /// <param name="path">The PPTX to write; it appears only once <see cref="Save"/> has finished.</param>
+ /// <param name="slideWidth">Slide width in EMU, within <see cref="MinSlideSide"/>..<see cref="MaxSlideSide"/>.</param>
+ /// <param name="slideHeight">Slide height in EMU.</param>
+ public PictureDeckWriter(string path, long slideWidth, long slideHeight)
+ {
+ _path = path;
+ SlideWidth = Math.Clamp(slideWidth, MinSlideSide, MaxSlideSide);
+ SlideHeight = Math.Clamp(slideHeight, MinSlideSide, MaxSlideSide);
+ _temp = path + ".tmp";
+ _file = File.Create(_temp);
+ _zip = new ZipArchive(_file, ZipArchiveMode.Create);
+ }
+
+ public long SlideWidth { get; }
+ public long SlideHeight { get; }
+
+ /// <summary>
+ /// Slide size for a page of <paramref name="width"/> × <paramref name="height"/> points: the page's own size, so an
+ /// A4 page gives an A4 portrait slide and a 16:9 page a 16:9 slide. Pages larger than PowerPoint's 56 inches are
+ /// scaled down and pages smaller than 1 inch scaled up, keeping the shape as far as those limits allow.
+ /// </summary>
+ public static (long Width, long Height) SlideSize(double width, double height)
+ {
+ double cx = Math.Max(1, width) * EmuPerPoint;
+ double cy = Math.Max(1, height) * EmuPerPoint;
+ var shrink = Math.Min(1, MaxSlideSide / Math.Max(cx, cy));
+ cx *= shrink;
+ cy *= shrink;
+ var grow = Math.Max(1, MinSlideSide / Math.Min(cx, cy));
+ cx *= grow;
+ cy *= grow;
+ return (Math.Clamp((long)Math.Round(cx), MinSlideSide, MaxSlideSide), Math.Clamp((long)Math.Round(cy), MinSlideSide, MaxSlideSide));
+ }
+
+ /// <summary>
+ /// Where a picture of <paramref name="width"/> × <paramref name="height"/> (any unit) goes on the slide: as large as
+ /// fits without cropping, centred (EMU).
+ /// </summary>
+ public (long X, long Y, long Width, long Height) Fit(double width, double height)
+ {
+ var scale = Math.Min(SlideWidth / Math.Max(width, 1e-6), SlideHeight / Math.Max(height, 1e-6));
+ var cx = Math.Clamp((long)Math.Round(width * scale), 1, SlideWidth);
+ var cy = Math.Clamp((long)Math.Round(height * scale), 1, SlideHeight);
+ return ((SlideWidth - cx) / 2, (SlideHeight - cy) / 2, cx, cy);
+ }
+
+ /// <summary>
+ /// Adds a slide showing <paramref name="jpeg"/>, fitted and centred like <see cref="Fit"/> for a picture of
+ /// <paramref name="width"/> × <paramref name="height"/>, with <paramref name="notes"/> (lines separated by CR LF or
+ /// LF) as its speaker notes when there are any.
+ /// </summary>
+ public void AddSlide(ReadOnlySpan<byte> jpeg, double width, double height, string name, string? notes)
+ {
+ var number = _slideHasNotes.Count + 1;
+ var hasNotes = !string.IsNullOrWhiteSpace(notes);
+ _slideHasNotes.Add(hasNotes);
+
+ using (var media = _zip.CreateEntry($"ppt/media/image{number}.jpeg", CompressionLevel.NoCompression).Open())
+ media.Write(jpeg);
+
+ var (x, y, cx, cy) = Fit(width, height);
+ var slide = new StringBuilder($"<p:sld {Namespaces}><p:cSld>").Append(TreeStart)
+ .Append("<p:pic><p:nvPicPr>")
+ .Append($"<p:cNvPr id=\"2\" name=\"{Escape(name)}\" descr=\"{Escape(name)}\"/>")
+ .Append("<p:cNvPicPr><a:picLocks noChangeAspect=\"1\"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>")
+ .Append("<p:blipFill><a:blip r:embed=\"rId2\"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>")
+ .Append($"<p:spPr><a:xfrm><a:off x=\"{N(x)}\" y=\"{N(y)}\"/><a:ext cx=\"{N(cx)}\" cy=\"{N(cy)}\"/></a:xfrm>")
+ .Append("<a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></p:spPr></p:pic>")
+ .Append("</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>");
+ Write($"ppt/slides/slide{number}.xml", slide.ToString());
+ List<(string, string, string)> relationships =
+ [
+ ("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml"),
+ ("rId2", "image", $"../media/image{number}.jpeg"),
+ ];
+ if (hasNotes)
+ relationships.Add(("rId3", "notesSlide", $"../notesSlides/notesSlide{number}.xml"));
+ Write($"ppt/slides/_rels/slide{number}.xml.rels", Rels([.. relationships]));
+
+ if (!hasNotes)
+ return;
+ var body = new StringBuilder();
+ foreach (var line in notes!.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'))
+ body.Append(line.Length == 0 ? "<a:p/>" : $"<a:p><a:r><a:t>{Escape(line)}</a:t></a:r></a:p>");
+ Write($"ppt/notesSlides/notesSlide{number}.xml",
+ $"<p:notes {Namespaces}><p:cSld>{TreeStart}" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"2\" name=\"Slide Image Placeholder 1\"/><p:cNvSpPr><a:spLocks noGrp=\"1\" noRot=\"1\" noChangeAspect=\"1\"/></p:cNvSpPr>" +
+ "<p:nvPr><p:ph type=\"sldImg\"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"3\" name=\"Notes Placeholder 2\"/><p:cNvSpPr><a:spLocks noGrp=\"1\"/></p:cNvSpPr>" +
+ "<p:nvPr><p:ph type=\"body\" idx=\"1\"/></p:nvPr></p:nvSpPr><p:spPr/>" +
+ $"<p:txBody><a:bodyPr/><a:lstStyle/>{body}</p:txBody></p:sp>" +
+ "</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:notes>");
+ Write($"ppt/notesSlides/_rels/notesSlide{number}.xml.rels", Rels(
+ ("rId1", "notesMaster", "../notesMasters/notesMaster1.xml"),
+ ("rId2", "slide", $"../slides/slide{number}.xml")));
+ }
+
+ /// <summary>Writes the parts that list the slides and moves the finished file into place.</summary>
+ public void Save()
+ {
+ if (_slideHasNotes.Count == 0)
+ throw new InvalidOperationException("A presentation needs at least one slide.");
+ var notes = _slideHasNotes.Contains(true);
+ var slides = _slideHasNotes.Count;
+
+ // Presentation: master, notes master, slides, sizes. Relationship ids: 1-5 fixed parts, 6 the notes master,
+ // slides from 7.
+ var presentation = new StringBuilder($"<p:presentation {Namespaces} saveSubsetFonts=\"1\">")
+ .Append("<p:sldMasterIdLst><p:sldMasterId id=\"2147483648\" r:id=\"rId1\"/></p:sldMasterIdLst>");
+ if (notes)
+ presentation.Append("<p:notesMasterIdLst><p:notesMasterId r:id=\"rId6\"/></p:notesMasterIdLst>");
+ presentation.Append("<p:sldIdLst>");
+ for (var i = 0; i < slides; i++)
+ presentation.Append($"<p:sldId id=\"{256 + i}\" r:id=\"rId{7 + i}\"/>");
+ presentation.Append("</p:sldIdLst>")
+ .Append($"<p:sldSz cx=\"{N(SlideWidth)}\" cy=\"{N(SlideHeight)}\"/>")
+ .Append($"<p:notesSz cx=\"{N(NotesWidth)}\" cy=\"{N(NotesHeight)}\"/>")
+ .Append("</p:presentation>");
+ Write("ppt/presentation.xml", presentation.ToString());
+
+ var relationships = new List<(string, string, string)>
+ {
+ ("rId1", "slideMaster", "slideMasters/slideMaster1.xml"),
+ ("rId2", "theme", "theme/theme1.xml"),
+ ("rId3", "presProps", "presProps.xml"),
+ ("rId4", "viewProps", "viewProps.xml"),
+ ("rId5", "tableStyles", "tableStyles.xml"),
+ };
+ if (notes)
+ relationships.Add(("rId6", "notesMaster", "notesMasters/notesMaster1.xml"));
+ for (var i = 0; i < slides; i++)
+ relationships.Add(($"rId{7 + i}", "slide", $"slides/slide{i + 1}.xml"));
+ Write("ppt/_rels/presentation.xml.rels", Rels([.. relationships]));
+
+ Write("ppt/slideMasters/slideMaster1.xml", SlideMaster());
+ Write("ppt/slideMasters/_rels/slideMaster1.xml.rels", Rels(
+ ("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml"),
+ ("rId2", "theme", "../theme/theme1.xml")));
+ Write("ppt/slideLayouts/slideLayout1.xml",
+ $"<p:sldLayout {Namespaces} type=\"blank\" preserve=\"1\"><p:cSld name=\"Blank\">{TreeStart}</p:spTree></p:cSld>" +
+ "<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>");
+ Write("ppt/slideLayouts/_rels/slideLayout1.xml.rels", Rels(("rId1", "slideMaster", "../slideMasters/slideMaster1.xml")));
+ Write("ppt/theme/theme1.xml", Theme());
+ if (notes)
+ {
+ Write("ppt/notesMasters/notesMaster1.xml", NotesMaster());
+ // A master of its own needs a theme of its own (PowerPoint's notes masters use theme2 as well).
+ Write("ppt/notesMasters/_rels/notesMaster1.xml.rels", Rels(("rId1", "theme", "../theme/theme2.xml")));
+ Write("ppt/theme/theme2.xml", Theme());
+ }
+ Write("ppt/presProps.xml", $"<p:presentationPr {Namespaces}/>");
+ Write("ppt/viewProps.xml",
+ $"<p:viewPr {Namespaces}><p:normalViewPr><p:restoredLeft sz=\"15620\"/><p:restoredTop sz=\"94660\"/></p:normalViewPr>" +
+ "<p:gridSpacing cx=\"76200\" cy=\"76200\"/></p:viewPr>");
+ Write("ppt/tableStyles.xml",
+ "<a:tblStyleLst xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" def=\"{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}\"/>");
+
+ var now = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
+ Write("docProps/core.xml",
+ "<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" " +
+ "xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" " +
+ "xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
+ $"<dcterms:created xsi:type=\"dcterms:W3CDTF\">{now}</dcterms:created>" +
+ $"<dcterms:modified xsi:type=\"dcterms:W3CDTF\">{now}</dcterms:modified></cp:coreProperties>");
+ Write("docProps/app.xml",
+ "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\">" +
+ $"<Application>Filee</Application><Slides>{N(slides)}</Slides><Notes>{N(_slideHasNotes.Count(n => n))}</Notes></Properties>");
+
+ Write("_rels/.rels", Rels(
+ ("rId1", "officeDocument", "ppt/presentation.xml"),
+ ("rId2", "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml"),
+ ("rId3", "extended-properties", "docProps/app.xml")));
+ Write("[Content_Types].xml", ContentTypes(slides, notes));
+
+ _zip.Dispose();
+ _file.Dispose();
+ File.Move(_temp, _path, overwrite: true);
+ _saved = true;
+ }
+
+ public void Dispose()
+ {
+ if (_saved)
+ return;
+ _zip.Dispose();
+ _file.Dispose();
+ try { File.Delete(_temp); } catch (IOException) { }
+ }
+
+ private string ContentTypes(int slides, bool notes)
+ {
+ var sb = new StringBuilder("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">")
+ .Append("<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>")
+ .Append("<Default Extension=\"xml\" ContentType=\"application/xml\"/>")
+ .Append("<Default Extension=\"jpeg\" ContentType=\"image/jpeg\"/>");
+ void Override(string part, string type) => sb.Append($"<Override PartName=\"/{part}\" ContentType=\"{type}\"/>");
+ Override("ppt/presentation.xml", PresentationTypes + "presentation.main+xml");
+ Override("ppt/slideMasters/slideMaster1.xml", PresentationTypes + "slideMaster+xml");
+ Override("ppt/slideLayouts/slideLayout1.xml", PresentationTypes + "slideLayout+xml");
+ for (var i = 1; i <= slides; i++)
+ Override($"ppt/slides/slide{i}.xml", PresentationTypes + "slide+xml");
+ Override("ppt/theme/theme1.xml", "application/vnd.openxmlformats-officedocument.theme+xml");
+ if (notes)
+ {
+ Override("ppt/notesMasters/notesMaster1.xml", PresentationTypes + "notesMaster+xml");
+ Override("ppt/theme/theme2.xml", "application/vnd.openxmlformats-officedocument.theme+xml");
+ for (var i = 1; i <= slides; i++)
+ {
+ if (_slideHasNotes[i - 1])
+ Override($"ppt/notesSlides/notesSlide{i}.xml", PresentationTypes + "notesSlide+xml");
+ }
+ }
+ Override("ppt/presProps.xml", PresentationTypes + "presProps+xml");
+ Override("ppt/viewProps.xml", PresentationTypes + "viewProps+xml");
+ Override("ppt/tableStyles.xml", PresentationTypes + "tableStyles+xml");
+ Override("docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml");
+ Override("docProps/app.xml", "application/vnd.openxmlformats-officedocument.extended-properties+xml");
+ return sb.Append("</Types>").ToString();
+ }
+
+ /// <summary>A white background, no placeholders and default text styles: the slides only hold their picture.</summary>
+ private static string SlideMaster()
+ {
+ static string Level(string size, string font, string align = "") =>
+ $"<a:lvl1pPr{align}><a:defRPr sz=\"{size}\"><a:solidFill><a:schemeClr val=\"tx1\"/></a:solidFill>" +
+ $"<a:latin typeface=\"+{font}-lt\"/><a:ea typeface=\"+{font}-ea\"/><a:cs typeface=\"+{font}-cs\"/></a:defRPr></a:lvl1pPr>";
+
+ return $"<p:sldMaster {Namespaces}><p:cSld>" +
+ "<p:bg><p:bgPr><a:solidFill><a:srgbClr val=\"FFFFFF\"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>" +
+ $"{TreeStart}</p:spTree></p:cSld>{ColorMap}" +
+ "<p:sldLayoutIdLst><p:sldLayoutId id=\"2147483649\" r:id=\"rId1\"/></p:sldLayoutIdLst>" +
+ $"<p:txStyles><p:titleStyle>{Level("4400", "mj", " algn=\"ctr\"")}</p:titleStyle>" +
+ $"<p:bodyStyle>{Level("2800", "mn")}</p:bodyStyle><p:otherStyle>{Level("1800", "mn")}</p:otherStyle></p:txStyles>" +
+ "</p:sldMaster>";
+ }
+
+ /// <summary>The notes page: the slide's picture in the upper part (shaped like the slide), the notes below.</summary>
+ private string NotesMaster()
+ {
+ // The slide image fills a 6 × 4 inch box at the top, centred; the notes take the lower half of the page.
+ const long boxLeft = 685800, boxTop = 457200, boxWidth = 5486400, boxHeight = 3657600;
+ var scale = Math.Min((double)boxWidth / SlideWidth, (double)boxHeight / SlideHeight);
+ var cx = (long)Math.Round(SlideWidth * scale);
+ var cy = (long)Math.Round(SlideHeight * scale);
+ var x = boxLeft + (boxWidth - cx) / 2;
+ var y = boxTop + (boxHeight - cy) / 2;
+ return $"<p:notesMaster {Namespaces}><p:cSld>{TreeStart}" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"2\" name=\"Slide Image Placeholder 1\"/><p:cNvSpPr><a:spLocks noGrp=\"1\" noRot=\"1\" noChangeAspect=\"1\"/></p:cNvSpPr>" +
+ "<p:nvPr><p:ph type=\"sldImg\" idx=\"2\"/></p:nvPr></p:nvSpPr>" +
+ $"<p:spPr><a:xfrm><a:off x=\"{N(x)}\" y=\"{N(y)}\"/><a:ext cx=\"{N(cx)}\" cy=\"{N(cy)}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom>" +
+ "<a:noFill/><a:ln w=\"12700\"><a:solidFill><a:prstClr val=\"black\"/></a:solidFill></a:ln></p:spPr></p:sp>" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"3\" name=\"Notes Placeholder 2\"/><p:cNvSpPr><a:spLocks noGrp=\"1\"/></p:cNvSpPr>" +
+ "<p:nvPr><p:ph type=\"body\" sz=\"quarter\" idx=\"1\"/></p:nvPr></p:nvSpPr>" +
+ "<p:spPr><a:xfrm><a:off x=\"685800\" y=\"4343400\"/><a:ext cx=\"5486400\" cy=\"4114800\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></p:spPr>" +
+ "<p:txBody><a:bodyPr vert=\"horz\" lIns=\"91440\" tIns=\"45720\" rIns=\"91440\" bIns=\"45720\" rtlCol=\"0\"/><a:lstStyle/><a:p/></p:txBody></p:sp>" +
+ $"</p:spTree></p:cSld>{ColorMap}" +
+ "<p:notesStyle><a:lvl1pPr marL=\"0\" algn=\"l\" defTabSz=\"914400\" rtl=\"0\" eaLnBrk=\"1\" latinLnBrk=\"0\" hangingPunct=\"1\">" +
+ "<a:defRPr sz=\"1200\" kern=\"1200\"><a:solidFill><a:schemeClr val=\"tx1\"/></a:solidFill>" +
+ "<a:latin typeface=\"+mn-lt\"/><a:ea typeface=\"+mn-ea\"/><a:cs typeface=\"+mn-cs\"/></a:defRPr></a:lvl1pPr></p:notesStyle>" +
+ "</p:notesMaster>";
+ }
+
+ /// <summary>Office's default colours and fonts; three plain entries in each style list, the least the schema takes.</summary>
+ private static string Theme()
+ {
+ static string Color(string name, string value) => $"<a:{name}><a:srgbClr val=\"{value}\"/></a:{name}>";
+ const string fill = "<a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill>";
+ var lines = string.Concat(new[] { "6350", "12700", "19050" }.Select(w => $"<a:ln w=\"{w}\">{fill}</a:ln>"));
+ return "<a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Office Theme\"><a:themeElements>" +
+ "<a:clrScheme name=\"Office\">" +
+ "<a:dk1><a:sysClr val=\"windowText\" lastClr=\"000000\"/></a:dk1><a:lt1><a:sysClr val=\"window\" lastClr=\"FFFFFF\"/></a:lt1>" +
+ Color("dk2", "44546A") + Color("lt2", "E7E6E6") + Color("accent1", "4472C4") + Color("accent2", "ED7D31") +
+ Color("accent3", "A5A5A5") + Color("accent4", "FFC000") + Color("accent5", "5B9BD5") + Color("accent6", "70AD47") +
+ Color("hlink", "0563C1") + Color("folHlink", "954F72") + "</a:clrScheme>" +
+ "<a:fontScheme name=\"Office\">" +
+ "<a:majorFont><a:latin typeface=\"Calibri Light\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:majorFont>" +
+ "<a:minorFont><a:latin typeface=\"Calibri\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:minorFont></a:fontScheme>" +
+ "<a:fmtScheme name=\"Office\">" +
+ $"<a:fillStyleLst>{fill}{fill}{fill}</a:fillStyleLst>" +
+ $"<a:lnStyleLst>{lines}</a:lnStyleLst>" +
+ "<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>" +
+ $"<a:bgFillStyleLst>{fill}{fill}{fill}</a:bgFillStyleLst></a:fmtScheme>" +
+ "</a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>";
+ }
+
+ /// <summary>A relationships part; a relationship type without a scheme is one of the officeDocument types.</summary>
+ private static string Rels(params (string Id, string Type, string Target)[] relationships)
+ {
+ var sb = new StringBuilder("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
+ foreach (var (id, type, target) in relationships)
+ {
+ var fullType = type.Contains("://", StringComparison.Ordinal) ? type : Relationships + type;
+ sb.Append($"<Relationship Id=\"{id}\" Type=\"{fullType}\" Target=\"{target}\"/>");
+ }
+ return sb.Append("</Relationships>").ToString();
+ }
+
+ private void Write(string name, string xml)
+ {
+ using var writer = new StreamWriter(_zip.CreateEntry(name, CompressionLevel.Optimal).Open(), new UTF8Encoding(false));
+ writer.Write(Declaration);
+ writer.Write(xml);
+ }
+
+ private static string Escape(string text) => HwpxWriter.Escape(text);
+
+ private static string N(long value) => value.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/tests/Filee.Core.Tests/RoutePlannerTests.cs b/tests/Filee.Core.Tests/RoutePlannerTests.cs
index 973f56b5..5110fdaf 100644
--- a/tests/Filee.Core.Tests/RoutePlannerTests.cs
+++ b/tests/Filee.Core.Tests/RoutePlannerTests.cs
@@ -51,6 +51,22 @@ public class RoutePlannerTests
Assert.Equal(["pdf→svg"], planner.Plan("pdf", "svg")!.Steps.Select(s => $"{s.From}→{s.To}"));
}
+ [Fact]
+ public void Direct_only_edges_are_never_a_step_of_a_longer_route()
+ {
+ // PDF → PPTX puts pictures of the pages on slides: only for a PDF the user asked to turn into PPTX.
+ var slides = new FakeConverter("slides", new ConversionEdge("pdf", "pptx", DirectOnly: true));
+ var word = new FakeConverter("word", new ConversionEdge("docx", "pdf"));
+ var office = new FakeConverter("office", new ConversionEdge("pptx", "odp"), new ConversionEdge("pptx", "ppsx"));
+ var planner = new RoutePlanner([slides, word, office]);
+
+ Assert.Equal(["pdf→pptx"], planner.Plan("pdf", "pptx")!.Steps.Select(s => $"{s.From}→{s.To}"));
+ Assert.Null(planner.Plan("docx", "pptx")); // not after another step
+ Assert.Null(planner.Plan("pdf", "odp")); // nor before one
+ Assert.Null(planner.Plan("pdf", "ppsx"));
+ Assert.Equal(["pptx→odp"], planner.Plan("pptx", "odp")!.Steps.Select(s => $"{s.From}→{s.To}"));
+ }
+
[Fact]
public void Cheaper_route_wins()
{
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 36e7c4bc..e740a53e 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -148,7 +148,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
}
@@ -200,7 +200,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
var ids = store.Profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));
Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));
@@ -345,8 +345,9 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- // ... and, from schema 15, the 3D model engine before Pandoc (no CAD or archive engine in this list).
- Assert.Equal(["magick", "email", "data", "vector", "model3d", "pandoc", "libreoffice"], store.Settings.EnginePriority);
+ // ... and, from schema 15, the 3D model engine before Pandoc (no CAD or archive engine in this list), from
+ // schema 18 the PDF slides engine there too (no PDF text engine).
+ Assert.Equal(["magick", "email", "data", "vector", "model3d", "pdf-slides", "pandoc", "libreoffice"], store.Settings.EnginePriority);
}
[Fact]
@@ -525,6 +526,70 @@ public class UserDataStoreTests
Assert.Equal("rotate-left", presets[background + 1].Id);
}
+ /// <summary>Presets and donuts as a Filee before PDF → PPTX wrote them (schema 17).</summary>
+ private static (List<Preset> Presets, List<ToolbarProfile> Profiles) Version17Library()
+ {
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id == "pdf-slides");
+ var profiles = BuiltInData.CreateProfiles();
+ profiles.Single(p => p.Id == "pdf").PresetIds = [.. BuiltInData.PdfDonutBefore18];
+ return (presets, profiles);
+ }
+
+ [Fact]
+ public void Version_17_libraries_get_pptx_slides_on_the_unchanged_pdf_donut_in_place_of_tiff()
+ {
+ var (presets, profiles) = Version17Library();
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(17, presets, profiles));
+
+ var slides = presets.Single(p => p.Id == "pdf-slides");
+ Assert.Equal(("pptx", "preset.pdf_slides"), (slides.TargetFormat, slides.NameKey));
+ Assert.Equal("pdf-split", presets[presets.IndexOf(slides) - 1].Id); // where a new library has it
+ var pdf = profiles.Single(p => p.Id == "pdf").PresetIds;
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "pdf").PresetIds, pdf);
+ Assert.Equal(pdf.IndexOf("to-docx") + 1, pdf.IndexOf("pdf-slides"));
+ Assert.DoesNotContain("to-tiff", pdf);
+ Assert.NotNull(presets.SingleOrDefault(p => p.Id == "to-tiff")); // still a preset to add again
+ Assert.False(SettingsMigrations.ApplyToLibrary(17, presets, profiles)); // once only
+ }
+
+ [Fact]
+ public void A_pdf_donut_the_user_changed_gets_pptx_slides_only_when_it_has_room()
+ {
+ // Full, but not the default: the user's choice of twelve stays.
+ var (presets, profiles) = Version17Library();
+ var pdf = profiles.Single(p => p.Id == "pdf");
+ pdf.PresetIds[pdf.PresetIds.IndexOf("to-tiff")] = "to-webp";
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(17, presets, profiles)); // the preset is added
+ Assert.DoesNotContain("pdf-slides", pdf.PresetIds);
+ Assert.Contains("to-webp", pdf.PresetIds);
+
+ // With room: after DOCX.
+ (presets, profiles) = Version17Library();
+ pdf = profiles.Single(p => p.Id == "pdf");
+ pdf.PresetIds.RemoveAll(id => id is "to-md" or "to-epub");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(17, presets, profiles));
+ Assert.Equal(pdf.PresetIds.IndexOf("to-docx") + 1, pdf.PresetIds.IndexOf("pdf-slides"));
+ Assert.Contains("to-tiff", pdf.PresetIds);
+ }
+
+ [Fact]
+ public void Version_17_settings_get_the_pdf_slides_engine_after_pdf_text()
+ {
+ using var dir = new TempDir();
+ File.WriteAllText(Path.Combine(dir.Path, "settings.json"),
+ """{ "schemaVersion": 17, "enginePriority": ["magick", "pdfium", "docx-writer", "pdf-text", "email", "pandoc", "libreoffice"] }""");
+
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+
+ Assert.Equal(["magick", "pdfium", "docx-writer", "pdf-text", "pdf-slides", "email", "pandoc", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
+ }
+
[Fact]
public void A_rotation_from_a_newer_Filee_reads_as_none_and_the_other_presets_still_load()
{
diff --git a/tests/Filee.Engines.Tests/PdfSlidesTests.cs b/tests/Filee.Engines.Tests/PdfSlidesTests.cs
new file mode 100644
index 00000000..03498a89
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PdfSlidesTests.cs
@@ -0,0 +1,300 @@
+// PDF → PPTX with a picture of each page on its own slide: slide count and size, pictures fitted and centred, the page
+// range, the speaker notes, the Open XML SDK validator, Filee's own PPTX reader as a second reader, clear failures, and
+// routes: the picture deck is reached from a PDF only and is never a step towards another format.
+// The test PDFs are generated (PdfPig's writer, PDFsharp for rotation and passwords) and use the standard 14 fonts.
+
+using System.IO.Compression;
+using System.Xml.Linq;
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Validation;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Hwp.Hwpx.Pptx;
+using Filee.Engines.Pdf;
+using ImageMagick;
+using PdfSharp.Pdf.IO;
+using P = DocumentFormat.OpenXml.Presentation;
+
+namespace Filee.Engines.Tests;
+
+public class PdfSlidesTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const double A4Width = 595, A4Height = 842;
+
+ /// <summary>A PDF with one page per size, each with "Page n" and a line of text on it.</summary>
+ private static string MakePdf(string folder, params (double Width, double Height)[] pages)
+ {
+ var pdf = new PdfBuilder();
+ for (var i = 0; i < pages.Length; i++)
+ {
+ pdf.NewPage(pages[i].Width, pages[i].Height);
+ pdf.Line($"Page {i + 1}", 18, pdf.Font(bold: true), 40, 60);
+ pdf.Line($"Text on page number {i + 1} of the deck.", 11, pdf.Font(), 40, 90);
+ }
+ return pdf.Save(Path.Combine(folder, "deck.pdf"));
+ }
+
+ private async Task<ConversionJob> RunAsync(string input, Preset? preset = null) =>
+ await fx.ConvertAsync([input], preset ?? new Preset { TargetFormat = "pptx" });
+
+ private async Task<string> ConvertAsync(string input, Preset? preset = null)
+ {
+ var job = await RunAsync(input, preset);
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var output = job.Outputs.Single();
+ Assert.Equal(".pptx", Path.GetExtension(output));
+ return output;
+ }
+
+ /// <summary>What a slide shows: its picture's name, place and pixel size, and the speaker notes.</summary>
+ private sealed record Slide(string Name, long X, long Y, long Width, long Height, int PixelWidth, int PixelHeight, string Notes);
+
+ private static (long Width, long Height, List<Slide> Slides) Read(string pptx)
+ {
+ using var document = PresentationDocument.Open(pptx, false);
+ var presentation = document.PresentationPart!;
+ var size = presentation.Presentation!.SlideSize!;
+ var slides = new List<Slide>();
+ foreach (var id in presentation.Presentation.SlideIdList!.Elements<P.SlideId>())
+ {
+ var part = (SlidePart)presentation.GetPartById(id.RelationshipId!.Value!);
+ var picture = Assert.Single(part.Slide!.Descendants<P.Picture>());
+ Assert.Empty(part.Slide!.Descendants<P.Shape>()); // nothing but the page
+ var image = (ImagePart)part.GetPartById(picture.BlipFill!.Blip!.Embed!.Value!);
+ Assert.Equal("image/jpeg", image.ContentType);
+ MagickImageInfo info;
+ using (var stream = image.GetStream())
+ info = new MagickImageInfo(stream);
+ Assert.Equal(MagickFormat.Jpeg, info.Format);
+ var xfrm = picture.ShapeProperties!.Transform2D!;
+ slides.Add(new Slide(picture.NonVisualPictureProperties!.NonVisualDrawingProperties!.Name!.Value!,
+ xfrm.Offset!.X!.Value, xfrm.Offset.Y!.Value, xfrm.Extents!.Cx!.Value, xfrm.Extents.Cy!.Value,
+ (int)info.Width, (int)info.Height, part.NotesSlidePart?.NotesSlide?.InnerText ?? ""));
+ }
+ return (size.Cx!.Value, size.Cy!.Value, slides);
+ }
+
+ /// <summary>
+ /// No schema or semantic error for PowerPoint (Open XML SDK), every part has a content type and every relationship
+ /// a target.
+ /// </summary>
+ private static void ValidPackage(string pptx)
+ {
+ using (var document = PresentationDocument.Open(pptx, false))
+ {
+ var errors = new OpenXmlValidator(FileFormatVersions.Microsoft365).Validate(document)
+ .Select(e => $"{e.Part?.Uri} {e.Path?.XPath}: {e.Description}")
+ .ToList();
+ Assert.True(errors.Count == 0, string.Join("\n", errors));
+ }
+
+ XNamespace types = "http://schemas.openxmlformats.org/package/2006/content-types";
+ XNamespace rels = "http://schemas.openxmlformats.org/package/2006/relationships";
+ using var zip = ZipFile.OpenRead(pptx);
+ var contentTypes = XDocument.Load(zip.GetEntry("[Content_Types].xml")!.Open()).Root!;
+ var overrides = contentTypes.Elements(types + "Override").Select(o => ((string)o.Attribute("PartName")!).TrimStart('/')).ToHashSet();
+ var defaults = contentTypes.Elements(types + "Default").Select(d => (string)d.Attribute("Extension")!).ToHashSet();
+ foreach (var entry in zip.Entries.Where(e => e.FullName != "[Content_Types].xml"))
+ Assert.True(overrides.Contains(entry.FullName) || defaults.Contains(Path.GetExtension(entry.FullName).TrimStart('.')), $"{entry.FullName} has no content type");
+ Assert.All(overrides, part => Assert.NotNull(zip.GetEntry(part)));
+ foreach (var entry in zip.Entries.Where(e => e.FullName.EndsWith(".rels", StringComparison.Ordinal)))
+ {
+ var folder = entry.FullName[..entry.FullName.IndexOf("_rels/", StringComparison.Ordinal)];
+ foreach (var target in XDocument.Load(entry.Open()).Root!.Elements(rels + "Relationship").Select(r => (string)r.Attribute("Target")!))
+ {
+ var resolved = new Uri(new Uri("pptx:///" + folder), target).AbsolutePath.TrimStart('/');
+ Assert.True(zip.GetEntry(resolved) is not null, $"{entry.FullName} → {target}");
+ }
+ }
+ }
+
+ [Fact]
+ public async Task Every_page_becomes_a_picture_slide_shaped_like_the_first_page()
+ {
+ var pptx = await ConvertAsync(MakePdf(fx.NewFolder(), (A4Width, A4Height), (A4Width, A4Height), (A4Width, A4Height)));
+
+ ValidPackage(pptx);
+ var (width, height, slides) = Read(pptx);
+ // A4 portrait: the slide is the page's own size (points × 12700 EMU).
+ Assert.Equal((7556500, 10693400), (width, height));
+ Assert.Equal(["Page 1", "Page 2", "Page 3"], slides.Select(s => s.Name));
+ Assert.All(slides, s => Assert.Equal((0, 0, width, height), (s.X, s.Y, s.Width, s.Height)));
+ // 150 dpi (the default): 595 pt = 8.26 in → about 1240 px.
+ Assert.All(slides, s => Assert.InRange(s.PixelWidth, 1238, 1241));
+ Assert.All(slides, s => Assert.Equal(A4Height / A4Width, (double)s.PixelHeight / s.PixelWidth, 2));
+ // The page's text is in the speaker notes, so it can be searched and copied.
+ for (var i = 0; i < slides.Count; i++)
+ {
+ Assert.Contains($"Page {i + 1}", slides[i].Notes);
+ Assert.Contains($"Text on page number {i + 1} of the deck.", slides[i].Notes);
+ }
+ }
+
+ [Fact]
+ public async Task Pages_of_another_size_or_orientation_are_fitted_and_centred()
+ {
+ // A 16:9 first page (PowerPoint's widescreen size, 13.33 × 7.5 in) then an A4 portrait page.
+ var pptx = await ConvertAsync(MakePdf(fx.NewFolder(), (960, 540), (A4Width, A4Height)));
+
+ ValidPackage(pptx);
+ var (width, height, slides) = Read(pptx);
+ Assert.Equal((12192000, 6858000), (width, height));
+ Assert.Equal((0, 0, width, height), (slides[0].X, slides[0].Y, slides[0].Width, slides[0].Height));
+ // The portrait page is as tall as the slide and centred across it.
+ var portrait = slides[1];
+ Assert.Equal((0, height), (portrait.Y, portrait.Height));
+ Assert.Equal(height * A4Width / A4Height, portrait.Width, 1.0);
+ Assert.Equal((width - portrait.Width) / 2, portrait.X);
+ }
+
+ [Fact]
+ public async Task A_page_turned_in_the_pdf_is_shown_turned()
+ {
+ var folder = fx.NewFolder();
+ var path = MakePdf(folder, (A4Width, A4Height), (A4Width, A4Height));
+ using (var document = PdfReader.Open(path, PdfDocumentOpenMode.Modify))
+ {
+ document.Pages[0].Rotate = 90; // shown landscape
+ document.Save(path);
+ }
+
+ var (width, height, slides) = Read(await ConvertAsync(path));
+
+ // The turned first page makes landscape slides; the upright second page is fitted onto one, centred.
+ Assert.Equal((10693400, 7556500), (width, height));
+ Assert.True(slides[0].PixelWidth > slides[0].PixelHeight);
+ Assert.Equal((0, height), (slides[1].Y, slides[1].Height));
+ Assert.Equal((width - slides[1].Width) / 2, slides[1].X);
+ }
+
+ [Fact]
+ public async Task The_page_range_picks_the_slides_and_the_resolution_is_at_least_150_dpi()
+ {
+ var path = MakePdf(fx.NewFolder(), (A4Width, A4Height), (A4Width, A4Height), (A4Width, A4Height), (A4Width, A4Height));
+ var preset = new Preset { TargetFormat = "pptx", Pdf = { PageRange = "2-3", RenderDpi = 72 } };
+
+ var pptx = await ConvertAsync(path, preset);
+
+ ValidPackage(pptx);
+ var (_, _, slides) = Read(pptx);
+ Assert.Equal(["Page 2", "Page 3"], slides.Select(s => s.Name));
+ Assert.Contains("Text on page number 2 of the deck.", slides[0].Notes);
+ Assert.Contains("Text on page number 3 of the deck.", slides[1].Notes);
+ Assert.All(slides, s => Assert.InRange(s.PixelWidth, 1238, 1241)); // 72 dpi asked, 150 used
+ }
+
+ [Fact]
+ public async Task Filees_own_pptx_reader_sees_a_picture_on_each_slide()
+ {
+ var folder = fx.NewFolder();
+ var pptx = await ConvertAsync(MakePdf(folder, (960, 540), (960, 540)));
+
+ var document = PptxReader.Read(pptx, Path.Combine(folder, "media"));
+
+ var section = Assert.Single(document.Sections);
+ Assert.Equal(16.0 / 9, (double)section.Page!.Width / section.Page.Height, 3);
+ var pages = section.Blocks.OfType<HParagraph>().ToList();
+ Assert.Equal(2, pages.Count);
+ Assert.All(pages, page => Assert.Single(page.Inlines.OfType<HImage>()));
+ }
+
+ [Fact]
+ public async Task A_scan_without_text_has_no_notes()
+ {
+ var folder = fx.NewFolder();
+ var pdf = new PdfBuilder().NewPage();
+ pdf.Picture(PdfBuilder.Photo(folder, "scan.jpg", MagickFormat.Jpeg, 300, 400), 0, 0, A4Width, A4Height);
+ var path = pdf.Save(Path.Combine(folder, "scan.pdf"));
+
+ var pptx = await ConvertAsync(path);
+
+ ValidPackage(pptx);
+ Assert.Equal("", Assert.Single(Read(pptx).Slides).Notes);
+ using var zip = ZipFile.OpenRead(pptx);
+ Assert.DoesNotContain(zip.Entries, e => e.FullName.Contains("notes", StringComparison.OrdinalIgnoreCase));
+ }
+
+ [Fact]
+ public async Task Password_protected_pdf_fails_with_a_clear_message()
+ {
+ var folder = fx.NewFolder();
+ var path = MakePdf(folder, (A4Width, A4Height));
+ PdfBuilder.Protect(path, "1234");
+
+ var job = await RunAsync(path);
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("password", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);
+ Assert.Empty(Directory.GetFiles(folder, "*.pptx*"));
+ }
+
+ [Fact]
+ public async Task A_broken_pdf_fails_and_leaves_no_file()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "broken.pdf");
+ await File.WriteAllTextAsync(path, "%PDF-1.7\nthis is not really a PDF\n", TestContext.Current.CancellationToken);
+
+ var job = await RunAsync(path);
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Empty(Directory.GetFiles(folder, "*.pptx*"));
+ }
+
+ [Theory]
+ [InlineData(A4Width, A4Height, 7556500, 10693400)]
+ [InlineData(960, 540, 12192000, 6858000)]
+ [InlineData(10000, 5000, PictureDeckWriter.MaxSlideSide, PictureDeckWriter.MaxSlideSide / 2)] // larger than 56 in
+ [InlineData(36, 18, PictureDeckWriter.MinSlideSide * 2, PictureDeckWriter.MinSlideSide)] // smaller than 1 in
+ public void Slides_take_the_page_size_within_powerpoints_limits(double width, double height, long slideWidth, long slideHeight) =>
+ Assert.Equal((slideWidth, slideHeight), PictureDeckWriter.SlideSize(width, height));
+
+ [Fact]
+ public void Huge_pages_render_at_a_lower_resolution()
+ {
+ Assert.Equal(300, PdfSlidesConverter.PageDpi(A4Width, A4Height, 300));
+ // A0 (841 × 1189 mm) at 300 dpi would be 139 megapixels.
+ var dpi = PdfSlidesConverter.PageDpi(2384, 3370, 300);
+ Assert.InRange(dpi, 100, 299);
+ Assert.True(2384 / 72.0 * dpi * (3370 / 72.0 * dpi) <= PdfSlidesConverter.MaxPagePixels);
+ }
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Fact]
+ public void Picture_slides_come_from_a_pdf_only_and_leave_every_other_route_as_it_was()
+ {
+ var everyEngine = fx.Converters.Select(c => c.Id).ToArray();
+ var with = fx.Catalog.CreatePlanner(everyEngine);
+ var without = new ConverterCatalog(fx.Converters.Where(c => c is not PdfSlidesConverter)) { Priority = fx.Catalog.Priority }
+ .CreatePlanner(everyEngine);
+
+ Assert.Equal(["pdf-slides"], with.Plan("pdf", "pptx")!.Steps.Select(s => s.Converter.Id));
+
+ var formats = FormatRegistry.Known.Select(f => f.Id).ToList();
+ var checkedRoutes = 0;
+ foreach (var from in formats)
+ {
+ foreach (var to in formats.Where(t => t != from && (from, t) != ("pdf", "pptx")))
+ {
+ var route = with.Plan(from, to);
+ var before = without.Plan(from, to);
+ Assert.False(route?.Steps.Any(s => s.Converter is PdfSlidesConverter) ?? false,
+ $"{from} → {to} goes through picture slides: {string.Join(" → ", route?.Steps.Select(s => s.To) ?? [])}");
+ Assert.Equal(before is null, route is null);
+ if (before is null)
+ continue;
+ Assert.Equal(before.Cost, route!.Cost);
+ Assert.Equal(before.Steps.Select(s => (s.Converter.Id, s.To)), route.Steps.Select(s => (s.Converter.Id, s.To)));
+ checkedRoutes++;
+ }
+ }
+ Assert.True(checkedRoutes > 1000);
+
+ // Presentations keep their own routes to PDF and images (PPTX → PDF is not changed by a PDF → PPTX edge).
+ Assert.DoesNotContain(with.Plan("pptx", "pdf")!.Steps, s => s.Converter is PdfSlidesConverter);
+ }
+}