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 toolkit: watermark, page numbers and password for every PDF a preset writes

cre8ive-marketing43679c5b9567
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 3ba038b0..516a6736 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -686,6 +686,21 @@ PDFsharp and Magick.NET; nothing has to be installed.
- **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.
+## PDF watermark, page numbers and password
+
+A preset that writes PDF can finish every PDF it makes (`PdfOptions.Watermark`, `PageNumbers`, `Password`;
+`Pdf/PdfFinishing.cs`, PDFsharp only). `JobQueue` runs it (`IPdfFinisher`) on each PDF a file became, whichever engine
+wrote it (PDFsharp, rhwp, LibreOffice, Ghostscript …), and once on a merged PDF, so its pages are numbered through.
+
+- **Watermark**: the text in light grey (22 % opacity), bold, along the page's diagonal over the content, at 70 % of
+ the diagonal and at most a quarter of the short side high.
+- **Page numbers**: "3 / 10", 9 pt dark grey, centred 10 mm above the bottom edge.
+- Text is drawn as glyph outlines (`Vector/GlyphOutlines.cs`, HarfBuzz shaping, shared with SVG text in PDFs). Any
+ script works with a font the PC has for it (Skia's font fallback, else Arial or the default face), and no font is
+ embedded, so the PDF grows by a few kilobytes. The text can't be selected or searched.
+- **Password**: opens the PDF (user and owner password are the same), AES-256 (`SetEncryptionToV5`). It is saved with
+ the preset in the settings file. A password makes a PDF/A no longer conform, since PDF/A forbids encryption.
+
## 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/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 7ee866f4..0685c8e6 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -509,6 +509,11 @@
"presets.pdf_ghostscript": "تجربة Ghostscript أيضًا (عند تثبيته)",
"presets.pdf_ghostscript_hint": "غالبًا ما يُنتج حجمًا أصغر، لكنه يعيد كتابة الملف بالكامل.\nتُحفَظ النتيجة الأصغر.",
"presets.pdf_keep_metadata": "الاحتفاظ بالبيانات الوصفية للصفحات والصور (XMP)",
+ "presets.watermark": "علامة مائية",
+ "presets.watermark_hint": "مثلًا: مسودة",
+ "presets.pdf_password": "كلمة مرور الفتح",
+ "presets.pdf_password_hint": "اتركه فارغًا بلا كلمة مرور. تُحفظ مع الإعداد المسبق، فاستخدم كلمة مرور لهذا النوع من الملفات فقط.",
+ "presets.page_numbers": "أرقام الصفحات (1 / 5 في الأسفل)",
"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/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index d6024c30..262c91de 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -524,6 +524,11 @@
"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.watermark": "Watermark",
+ "presets.watermark_hint": "e.g. DRAFT",
+ "presets.pdf_password": "Password to open",
+ "presets.pdf_password_hint": "Empty for none. It is saved with the preset, so use one only for this kind of file.",
+ "presets.page_numbers": "Page numbers (1 / 5 at the bottom)",
"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/es.json b/src/Filee.App/Assets/i18n/es.json
index 89007a3e..549716b1 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -509,6 +509,11 @@
"presets.pdf_ghostscript": "Probar también con Ghostscript (si está instalado)",
"presets.pdf_ghostscript_hint": "A menudo es más pequeño, pero reescribe todo el archivo.\nSe conserva el resultado más pequeño.",
"presets.pdf_keep_metadata": "Conservar metadatos de página e imagen (XMP)",
+ "presets.watermark": "Marca de agua",
+ "presets.watermark_hint": "p. ej., BORRADOR",
+ "presets.pdf_password": "Contraseña para abrir",
+ "presets.pdf_password_hint": "Vacío para ninguna. Se guarda con el ajuste preestablecido: úsala solo para este tipo de archivo.",
+ "presets.page_numbers": "Números de página (1 / 5 abajo)",
"presets.combine_pages_hint": "Pone todas las páginas una debajo de otra en una sola imagen.\nLos resultados muy largos se escalan al límite del formato (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Apilar las páginas en una imagen alta (cuando se convierte un PDF)",
"presets.trim_page_margins": "Recortar el espacio en blanco de arriba y abajo de cada página",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 32197851..c6612f46 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "Essayer aussi Ghostscript (s'il est installé)",
"presets.pdf_ghostscript_hint": "Souvent plus léger, mais il réécrit tout le fichier.\nLe résultat le plus léger est conservé.",
"presets.pdf_keep_metadata": "Conserver les métadonnées des pages et des images (XMP)",
+ "presets.watermark": "Filigrane",
+ "presets.watermark_hint": "p. ex. BROUILLON",
+ "presets.pdf_password": "Mot de passe d'ouverture",
+ "presets.pdf_password_hint": "Vide pour aucun. Il est enregistré avec le préréglage : utilisez-en un réservé à ce type de fichier.",
+ "presets.page_numbers": "Numéros de page (1 / 5 en bas)",
"presets.combine_pages_hint": "Place toutes les pages les unes sous les autres dans une seule image.\nLes résultats très longs sont réduits à la limite du format (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Empiler les pages en une seule image haute (lors de la conversion d'un PDF)",
"presets.trim_page_margins": "Supprimer l'espace vide au-dessus et au-dessous de chaque page",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index dde78607..47712fff 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -509,6 +509,11 @@
"presets.pdf_ghostscript": "Ghostscript भी आज़माएँ (इंस्टॉल होने पर)",
"presets.pdf_ghostscript_hint": "अक्सर और छोटा होता है, लेकिन पूरी फ़ाइल को दोबारा लिखता है।\nसबसे छोटा नतीजा रखा जाता है।",
"presets.pdf_keep_metadata": "पेज और तस्वीर का मेटाडेटा (XMP) रखें",
+ "presets.watermark": "वॉटरमार्क",
+ "presets.watermark_hint": "जैसे: ड्राफ्ट",
+ "presets.pdf_password": "खोलने का पासवर्ड",
+ "presets.pdf_password_hint": "खाली छोड़ें तो कोई पासवर्ड नहीं। यह प्रीसेट के साथ सेव होता है, इसलिए सिर्फ़ इस तरह की फ़ाइलों का पासवर्ड रखें।",
+ "presets.page_numbers": "पेज नंबर (नीचे 1 / 5)",
"presets.combine_pages_hint": "सभी पेजों को एक के नीचे एक रखकर एक इमेज बनाता है।\nबहुत लंबे नतीजे फ़ॉर्मैट की सीमा तक स्केल किए जाते हैं (JPG 65,500 px, WebP 16,383 px)।",
"presets.combine_pages": "पेजों को एक लंबी इमेज में जोड़ें (जब PDF कन्वर्ट हो)",
"presets.trim_page_margins": "हर पेज के ऊपर और नीचे की खाली जगह काटें",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index afc5f5d3..66ad21f8 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -509,6 +509,11 @@
"presets.pdf_ghostscript": "Ghostscriptも試す(インストール済みの場合)",
"presets.pdf_ghostscript_hint": "さらに小さくできることがありますが、ファイル全体を書き換えます。\n最も小さい結果を保持します。",
"presets.pdf_keep_metadata": "ページと画像のメタデータ(XMP)を保持",
+ "presets.watermark": "透かし",
+ "presets.watermark_hint": "例:下書き",
+ "presets.pdf_password": "開くときのパスワード",
+ "presets.pdf_password_hint": "空欄なら設定しません。プリセットと一緒に保存されるので、この用途専用のパスワードにしてください。",
+ "presets.page_numbers": "ページ番号(下部に 1 / 5)",
"presets.combine_pages_hint": "すべてのページを縦に並べて1枚の画像にします。\n長すぎる場合は形式の上限に合わせて縮小されます(JPG:65,500 px、WebP:16,383 px)。",
"presets.combine_pages": "ページを縦に並べて1枚の画像にする(PDFを変換する場合)",
"presets.trim_page_margins": "各ページの上下の余白を切り取る",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 115bfc7e..6d34e364 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "Ghostscript로도 해 보기 (설치된 경우)",
"presets.pdf_ghostscript_hint": "더 작아질 때가 많지만 파일 전체를 다시 써요.\n가장 작은 결과를 남겨요.",
"presets.pdf_keep_metadata": "페이지·이미지 메타데이터(XMP) 유지",
+ "presets.watermark": "워터마크",
+ "presets.watermark_hint": "예: 초안",
+ "presets.pdf_password": "열기 암호",
+ "presets.pdf_password_hint": "비워 두면 암호를 걸지 않습니다. 프리셋과 함께 저장되므로 이 용도로만 쓰는 암호를 넣으세요.",
+ "presets.page_numbers": "페이지 번호 (아래쪽에 1 / 5)",
"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/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 2e2da36b..e992ccc8 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "Spróbuj też Ghostscript (jeśli jest zainstalowany)",
"presets.pdf_ghostscript_hint": "Często daje mniejszy plik, ale zapisuje cały plik od nowa.\nZostaje najmniejszy wynik.",
"presets.pdf_keep_metadata": "Zachowaj metadane stron i obrazów (XMP)",
+ "presets.watermark": "Znak wodny",
+ "presets.watermark_hint": "np. SZKIC",
+ "presets.pdf_password": "Hasło do otwarcia",
+ "presets.pdf_password_hint": "Puste oznacza brak hasła. Zapisuje się razem z ustawieniem, więc użyj hasła tylko do tego rodzaju plików.",
+ "presets.page_numbers": "Numery stron (1 / 5 na dole)",
"presets.combine_pages_hint": "Układa wszystkie strony jedna pod drugą w jednym obrazie.\nBardzo długie wyniki są skalowane do limitu formatu (JPG 65 500 px, WebP 16 383 px).",
"presets.combine_pages": "Złóż strony w jeden wysoki obraz (przy konwersji PDF)",
"presets.trim_page_margins": "Wytnij puste miejsce nad i pod każdą stroną",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 0b7cd7cd..934f829b 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "Tentar também o Ghostscript (quando instalado)",
"presets.pdf_ghostscript_hint": "Muitas vezes menor, mas reescreve o arquivo inteiro.\nO menor resultado é mantido.",
"presets.pdf_keep_metadata": "Manter metadados de página e imagem (XMP)",
+ "presets.watermark": "Marca d'água",
+ "presets.watermark_hint": "ex.: RASCUNHO",
+ "presets.pdf_password": "Senha para abrir",
+ "presets.pdf_password_hint": "Vazio para nenhuma. Ela é salva com a predefinição, então use uma só para esse tipo de arquivo.",
+ "presets.page_numbers": "Números de página (1 / 5 embaixo)",
"presets.combine_pages_hint": "Coloca todas as páginas uma embaixo da outra numa única imagem.\nResultados muito longos são reduzidos ao limite do formato (JPG 65.500 px, WebP 16.383 px).",
"presets.combine_pages": "Empilhar as páginas numa imagem alta (quando um PDF é convertido)",
"presets.trim_page_margins": "Cortar o espaço em branco acima e abaixo de cada página",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 3eb526c7..49b5413f 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "Попробовать также Ghostscript (если установлен)",
"presets.pdf_ghostscript_hint": "Часто получается меньше, но он перезаписывает весь файл.\nОстаётся самый маленький результат.",
"presets.pdf_keep_metadata": "Сохранять метаданные страниц и картинок (XMP)",
+ "presets.watermark": "Водяной знак",
+ "presets.watermark_hint": "например, ЧЕРНОВИК",
+ "presets.pdf_password": "Пароль для открытия",
+ "presets.pdf_password_hint": "Пусто — без пароля. Он сохраняется вместе с пресетом, поэтому используйте отдельный пароль только для таких файлов.",
+ "presets.page_numbers": "Номера страниц (1 / 5 внизу)",
"presets.combine_pages_hint": "Ставит все страницы одну под другой в одной картинке.\nОчень длинный результат уменьшается до предела формата (JPG 65 500 px, WebP 16 383 px).",
"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 6247a2b0..7bc8b8d7 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "也试试 Ghostscript(已安装时)",
"presets.pdf_ghostscript_hint": "通常更小,但会重写整个文件。\n保留最小的结果。",
"presets.pdf_keep_metadata": "保留页面和图片元数据 (XMP)",
+ "presets.watermark": "水印",
+ "presets.watermark_hint": "例如:草稿",
+ "presets.pdf_password": "打开密码",
+ "presets.pdf_password_hint": "留空则不设密码。密码会随预设一起保存,请只用于这类文件。",
+ "presets.page_numbers": "页码(底部显示 1 / 5)",
"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/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index d1a197a1..17a37370 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -524,6 +524,11 @@
"presets.pdf_ghostscript": "也試試 Ghostscript(已安裝時)",
"presets.pdf_ghostscript_hint": "通常更小,但會重寫整個檔案。\n保留最小的結果。",
"presets.pdf_keep_metadata": "保留頁面和圖片中繼資料 (XMP)",
+ "presets.watermark": "浮水印",
+ "presets.watermark_hint": "例如:草稿",
+ "presets.pdf_password": "開啟密碼",
+ "presets.pdf_password_hint": "留空則不設密碼。密碼會隨預設一起儲存,請只用於這類檔案。",
+ "presets.page_numbers": "頁碼(底部顯示 1 / 5)",
"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/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index d76f638b..062d2ad6 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -105,6 +105,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_pageSize = PageSizes.First(p => p.Value == _edit.Pdf.PageSize);
_compressionLevel = CompressionLevels.FirstOrDefault(c => c.Value == _edit.Pdf.Compression) ?? CompressionLevels[0];
_compressWithGhostscript = _edit.Pdf.CompressWithGhostscript;
+ _watermark = _edit.Pdf.Watermark;
+ _pageNumbers = _edit.Pdf.PageNumbers;
+ _pdfPassword = _edit.Pdf.Password;
_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);
@@ -385,6 +388,11 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private bool _compressWithGhostscript;
+ /// <summary>A PDF target's finishing: watermark text, page numbers, a password to open it (PdfOptions).</summary>
+ [ObservableProperty] private string _watermark;
+ [ObservableProperty] private bool _pageNumbers;
+ [ObservableProperty] private string _pdfPassword;
+
/// <summary>PDF → image: one tall image of all pages.</summary>
[ObservableProperty] private bool _combinePages;
[ObservableProperty] private bool _trimPageMargins;
@@ -595,6 +603,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject
pdf.SplitTallImage = SplitTallImage;
pdf.Compression = CompressionLevel.Value;
pdf.CompressWithGhostscript = CompressWithGhostscript;
+ // Only for a PDF target, where they are shown: a password left behind by it must not lock nothing.
+ pdf.Watermark = ShowPdfBuild ? Watermark.Trim() : "";
+ pdf.PageNumbers = ShowPdfBuild && PageNumbers;
+ pdf.Password = ShowPdfBuild ? PdfPassword : "";
_original.Document.PdfA = PdfA;
// Only where the option is shown, as with SaveEveryFrame below.
_original.Document.LeaveOutPictures = ShowLeaveOutPictures && LeaveOutPictures;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 8c81df87..7f885ec4 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -358,6 +358,21 @@
</StackPanel>
</Grid>
<CheckBox Content="{DynamicResource presets.pdfa}" IsChecked="{Binding PdfA}" IsVisible="{Binding ShowDocument}" />
+ <!-- Finishing of every PDF the preset writes: watermark, page numbers, password -->
+ <StackPanel Spacing="10" IsVisible="{Binding ShowPdfBuild}">
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.watermark}" />
+ <TextBox Text="{Binding Watermark}" PlaceholderText="{DynamicResource presets.watermark_hint}" MaxLength="60" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource presets.pdf_password}" />
+ <TextBox Text="{Binding PdfPassword}" PasswordChar="•" Classes="revealPasswordButton" MaxLength="64" />
+ </StackPanel>
+ </Grid>
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource presets.pdf_password_hint}" />
+ <CheckBox Content="{DynamicResource presets.page_numbers}" IsChecked="{Binding PageNumbers}" />
+ </StackPanel>
</StackPanel>
</Border>
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index 3a84b9d8..5d8ad75e 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -187,6 +187,17 @@ public interface IPdfMerger
Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken);
}
+/// <summary>
+/// Adds a watermark and page numbers to a finished PDF and locks it with a password
+/// (<see cref="Presets.PdfOptions.FinishesPdf"/>). Implemented by the PDF engine; <see cref="JobQueue"/> runs it on
+/// every PDF a job writes, whichever engine made it, and on a merged PDF once, after merging.
+/// </summary>
+public interface IPdfFinisher
+{
+ /// <summary>Rewrites <paramref name="path"/> in place.</summary>
+ Task FinishAsync(string path, Presets.PdfOptions options, CancellationToken cancellationToken);
+}
+
/// <summary>
/// Writes TIFF pages (and every page of multi-page TIFFs) into one multi-page TIFF, in order. Implemented by the
/// ImageMagick engine; <see cref="JobQueue"/> uses it when a preset sets <see cref="Presets.ImageOptions.MultiPageTiff"/>.
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 9cf06228..2151ae89 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -226,6 +226,15 @@ public sealed class JobQueue : IAsyncDisposable
}
/// <summary>Converts every file to PDF in the work directory, then merges them into one output.</summary>
+ /// <summary>Applies the preset's PDF finishing (<see cref="PdfOptions.FinishesPdf"/>) to the PDFs among <paramref name="outputs"/>.</summary>
+ private async Task FinishPdfsAsync(Preset preset, IReadOnlyList<string> outputs, CancellationToken ct)
+ {
+ if (!preset.Pdf.FinishesPdf || _catalog.All.OfType<IPdfFinisher>().FirstOrDefault() is not { } finisher)
+ return;
+ foreach (var pdf in outputs.Where(o => FormatRegistry.Detect(o)?.Id == "pdf"))
+ await finisher.FinishAsync(pdf, preset.Pdf, ct);
+ }
+
private async Task RunMergedAsync(ConversionJob job, RoutePlanner planner, string workDir)
{
var parts = new string?[job.Files.Count];
@@ -266,6 +275,8 @@ public sealed class JobQueue : IAsyncDisposable
try
{
await _pdfMerger!.MergeAsync(inputs, output, job.CancellationToken);
+ // Once for the merged PDF, so its pages are numbered through.
+ await FinishPdfsAsync(job.Preset, [output], job.CancellationToken);
}
catch
{
@@ -579,6 +590,10 @@ public sealed class JobQueue : IAsyncDisposable
inputs = outputs;
}
+ // Watermark, page numbers, password: on every PDF this file became, from whichever engine.
+ if (finalOutput && job.Preset.TargetFormat == "pdf")
+ await FinishPdfsAsync(job.Preset, inputs, ct);
+
if (zipResult && inputs.Count > 0)
inputs = PackZip(job, file, index, inputs, ct);
// One output, and nothing else handed out for it (a Markdown file's picture folder goes with it).
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index ed631510..9c1385fa 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -409,6 +409,22 @@ public sealed class PdfOptions
/// </summary>
public bool CompressWithGhostscript { get; set; }
+ /// <summary>Text written large and faint across every page of a PDF ("DRAFT", "CONFIDENTIAL"); empty for none.</summary>
+ public string Watermark { get; set; } = "";
+
+ /// <summary>"1 / 5" at the bottom of every page of a PDF.</summary>
+ public bool PageNumbers { get; set; }
+
+ /// <summary>
+ /// A password the PDF opens with (AES-256); empty for none. Saved with the preset in the settings file, like the
+ /// rest of it.
+ /// </summary>
+ public string Password { get; set; } = "";
+
+ /// <summary>A PDF this preset writes gets a watermark, page numbers or a password (<see cref="Conversion.IPdfFinisher"/>).</summary>
+ [JsonIgnore]
+ public bool FinishesPdf => !string.IsNullOrWhiteSpace(Watermark) || PageNumbers || Password.Length > 0;
+
public PdfOptions Clone() => (PdfOptions)MemberwiseClone();
}
diff --git a/src/Filee.Engines/Pdf/PdfFinishing.cs b/src/Filee.Engines/Pdf/PdfFinishing.cs
new file mode 100644
index 00000000..c7308fdc
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfFinishing.cs
@@ -0,0 +1,131 @@
+// The last touch on a PDF a preset writes (PdfOptions.FinishesPdf): a watermark across every page, page numbers at
+// the bottom, and a password it opens with. Text is drawn as glyph outlines (GlyphOutlines, HarfBuzz), so any
+// language works with the fonts on the PC and no font is embedded; the password encrypts with AES-256.
+// Runs after whichever engine made the PDF (JobQueue), once for a merged PDF.
+
+using Filee.Core.Presets;
+using Filee.Engines.Vector;
+using PdfSharp.Drawing;
+using PdfSharp.Pdf;
+using SkiaSharp;
+
+namespace Filee.Engines.Pdf;
+
+internal static class PdfFinishing
+{
+ private const double PointsPerMm = 72 / 25.4;
+
+ /// <summary>Rewrites <paramref name="path"/> with the watermark, page numbers and password <paramref name="options"/> ask for.</summary>
+ public static void Finish(string path, PdfOptions options, CancellationToken ct)
+ {
+ using (var document = PdfSharpConverter.OpenForChanges(path))
+ using (var glyphs = new GlyphOutlines())
+ {
+ var watermark = options.Watermark.Trim();
+ for (var i = 0; i < document.PageCount; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ var page = document.Pages[i];
+ using var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
+ if (watermark.Length > 0)
+ DrawWatermark(graphics, glyphs, watermark, page.Width.Point, page.Height.Point);
+ if (options.PageNumbers)
+ DrawPageNumber(graphics, glyphs, $"{i + 1} / {document.PageCount}", page.Width.Point, page.Height.Point);
+ }
+ if (options.Password.Length > 0)
+ {
+ document.SecuritySettings.UserPassword = options.Password;
+ document.SecuritySettings.OwnerPassword = options.Password;
+ document.SecurityHandler.SetEncryptionToV5();
+ }
+ var finished = path + ".finished";
+ document.Save(finished);
+ File.Move(finished, path, overwrite: true);
+ }
+ }
+
+ /// <summary>Large, faint grey text along the page's diagonal, over the content.</summary>
+ private static void DrawWatermark(XGraphics graphics, GlyphOutlines glyphs, string text, double width, double height)
+ {
+ using var outline = Outline(glyphs, text, 100, bold: true);
+ if (outline.IsEmpty)
+ return;
+ var bounds = outline.TightBounds;
+ var diagonal = Math.Sqrt(width * width + height * height);
+ var scale = 0.7 * diagonal / bounds.Width;
+ // Short text isn't blown up to cover the page: at most 1/4 of the short side high.
+ scale = Math.Min(scale, Math.Min(width, height) / 4 / bounds.Height);
+ var state = graphics.Save();
+ graphics.TranslateTransform(width / 2, height / 2);
+ graphics.RotateTransform(-Math.Atan2(height, width) * 180 / Math.PI);
+ graphics.ScaleTransform(scale);
+ graphics.TranslateTransform(-bounds.MidX, -bounds.MidY);
+ graphics.DrawPath(new XSolidBrush(XColor.FromArgb(56, 128, 128, 128)), ToXPath(outline));
+ graphics.Restore(state);
+ }
+
+ /// <summary>"3 / 10" centred 10 mm above the bottom edge, 9 pt dark grey.</summary>
+ private static void DrawPageNumber(XGraphics graphics, GlyphOutlines glyphs, string text, double width, double height)
+ {
+ using var outline = Outline(glyphs, text, 9, bold: false);
+ if (outline.IsEmpty)
+ return;
+ var bounds = outline.TightBounds;
+ var state = graphics.Save();
+ graphics.TranslateTransform(width / 2 - bounds.MidX, height - 10 * PointsPerMm);
+ graphics.DrawPath(new XSolidBrush(XColor.FromArgb(96, 96, 96)), ToXPath(outline));
+ graphics.Restore(state);
+ }
+
+ /// <summary>
+ /// The text's glyph outlines at <paramref name="size"/> points, baseline at y = 0 (y down). The font is one the PC
+ /// has for the text's first non-Latin character, else Arial or the system's default face.
+ /// </summary>
+ internal static SKPath Outline(GlyphOutlines glyphs, string text, float size, bool bold)
+ {
+ var style = bold ? SKFontStyle.Bold : SKFontStyle.Normal;
+ var other = text.EnumerateRunes().FirstOrDefault(r => r.Value > 0x24F);
+ using var typeface = (other.Value > 0 ? SKFontManager.Default.MatchCharacter(null, style, null, other.Value) : null)
+ ?? SKFontManager.Default.MatchFamily("Arial", style)
+ ?? SKTypeface.CreateDefault();
+ using var font = new SKFont(typeface, size);
+ var path = new SKPath { FillType = SKPathFillType.Winding };
+ glyphs.AppendShaped(path, text, font, 0, 0, SKTextAlign.Left);
+ return path;
+ }
+
+ /// <summary>A Skia path as a PDFsharp path; quadratic curves become cubic ones.</summary>
+ internal static XGraphicsPath ToXPath(SKPath path)
+ {
+ var result = new XGraphicsPath { FillMode = XFillMode.Winding };
+ using var iterator = path.CreateRawIterator();
+ var points = new SKPoint[4];
+ SKPathVerb verb;
+ while ((verb = iterator.Next(points)) != SKPathVerb.Done)
+ {
+ switch (verb)
+ {
+ case SKPathVerb.Move:
+ result.StartFigure();
+ break;
+ case SKPathVerb.Line:
+ result.AddLine(X(points[0]), X(points[1]));
+ break;
+ case SKPathVerb.Quad or SKPathVerb.Conic:
+ var (p0, p1, p2) = (points[0], points[1], points[2]);
+ result.AddBezier(X(p0), X(p0 + Third(p1 - p0)), X(p2 + Third(p1 - p2)), X(p2));
+ break;
+ case SKPathVerb.Cubic:
+ result.AddBezier(X(points[0]), X(points[1]), X(points[2]), X(points[3]));
+ break;
+ case SKPathVerb.Close:
+ result.CloseFigure();
+ break;
+ }
+ }
+ return result;
+
+ static XPoint X(SKPoint p) => new(p.X, p.Y);
+ static SKPoint Third(SKPoint v) => new(v.X * 2 / 3, v.Y * 2 / 3);
+ }
+}
diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
index 4f64ac75..bc36c550 100644
--- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs
+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
@@ -1,5 +1,6 @@
// 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).
+// compression itself is in PdfCompressor, with Ghostscript as an optional second try). It also finishes every PDF a
+// job writes with a watermark, page numbers or a password (PdfFinishing).
using Filee.Core.Conversion;
using Filee.Core.Presets;
@@ -14,7 +15,7 @@ using PdfSharp.Pdf.IO;
namespace Filee.Engines.Pdf;
/// <summary>Image → PDF, PDF → PDF (split / page range / compression) and PDF merging.</summary>
-public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransformer
+public sealed class PdfSharpConverter : IConverter, IPdfMerger, IPdfFinisher, IImageTransformer
{
private const double PointsPerInch = 72.0;
private const double MillimetresPerInch = 25.4;
@@ -39,6 +40,10 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
: step.Preset.Pdf.Compression == PdfCompression.None ? Task.Run(() => SplitOrExtract(step, progress, cancellationToken), cancellationToken)
: Task.Run(() => CompressAsync(step, progress, cancellationToken), cancellationToken);
+ /// <summary>Watermark, page numbers and password (PdfFinishing).</summary>
+ public Task FinishAsync(string path, PdfOptions options, CancellationToken cancellationToken) =>
+ Task.Run(() => PdfFinishing.Finish(path, options, cancellationToken), cancellationToken);
+
public Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken) =>
Task.Run(() =>
{
@@ -254,7 +259,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
/// 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)
+ internal static PdfDocument OpenForChanges(string path)
{
try
{
diff --git a/src/Filee.Engines/Vector/GlyphOutlines.cs b/src/Filee.Engines/Vector/GlyphOutlines.cs
new file mode 100644
index 00000000..eb0af013
--- /dev/null
+++ b/src/Filee.Engines/Vector/GlyphOutlines.cs
@@ -0,0 +1,119 @@
+// Text as glyph outlines: shaped with HarfBuzz the way Svg.Skia does it (adapted from SkiaModel.TextShaping.cs,
+// Svg.Skia, MIT), so Arabic joins and Indic syllables come out right, and drawn as paths, so no font is embedded.
+// Used for SVG text in PDFs (OutlinedTextPlayback) and for PDF watermarks and page numbers (PdfFinishing).
+
+using System.Runtime.InteropServices;
+using HarfBuzzSharp;
+using Buffer = HarfBuzzSharp.Buffer;
+using SKFont = SkiaSharp.SKFont;
+using SKPath = SkiaSharp.SKPath;
+using SKTextAlign = SkiaSharp.SKTextAlign;
+using SKTypeface = SkiaSharp.SKTypeface;
+
+namespace Filee.Engines.Vector;
+
+/// <summary>Shapes text and appends its glyph outlines to a path; HarfBuzz fonts are cached per typeface.</summary>
+internal sealed class GlyphOutlines : IDisposable
+{
+ /// <summary>HarfBuzz works in integer units: positions are computed at this scale and divided back.</summary>
+ private const int HarfBuzzScale = 512;
+
+ private readonly Dictionary<string, Font?> _shapers = new(StringComparer.Ordinal);
+
+ /// <summary>Shapes <paramref name="text"/> and appends its glyph outlines, aligned at (<paramref name="x"/>, <paramref name="y"/>).</summary>
+ public bool AppendShaped(SKPath path, string text, SKFont font, float x, float y, SKTextAlign align)
+ {
+ if (string.IsNullOrEmpty(text))
+ return true;
+ var shaper = ShaperFor(font.Typeface);
+ if (shaper is null)
+ return false;
+
+ using var buffer = new Buffer();
+ buffer.ClusterLevel = ClusterLevel.Characters;
+ buffer.AddUtf16(text);
+ buffer.GuessSegmentProperties();
+ shaper.Shape(buffer);
+
+ var infos = buffer.GlyphInfos;
+ var positions = buffer.GlyphPositions;
+ var scaleY = font.Size / HarfBuzzScale;
+ var scaleX = scaleY * font.ScaleX;
+ var width = 0f;
+ foreach (var position in positions)
+ width += position.XAdvance * scaleX;
+ var penX = x - align switch
+ {
+ SKTextAlign.Center => width / 2,
+ SKTextAlign.Right => width,
+ _ => 0f,
+ };
+ var penY = y;
+ for (var i = 0; i < infos.Length; i++)
+ {
+ AppendGlyph(path, font, (ushort)infos[i].Codepoint, penX + positions[i].XOffset * scaleX, penY - positions[i].YOffset * scaleY);
+ penX += positions[i].XAdvance * scaleX;
+ penY -= positions[i].YAdvance * scaleY;
+ }
+ return true;
+ }
+
+ public static void AppendGlyph(SKPath path, SKFont font, ushort glyph, float x, float y)
+ {
+ using var outline = font.GetGlyphPath(glyph);
+ if (outline is { IsEmpty: false })
+ path.AddPath(outline, x, y);
+ }
+
+ /// <summary>A HarfBuzz font for the typeface (cached), or null when its font data can't be read.</summary>
+ private Font? ShaperFor(SKTypeface typeface)
+ {
+ var key = $"{typeface.FamilyName}|{typeface.FontWeight}|{typeface.FontWidth}|{typeface.FontSlant}";
+ if (_shapers.TryGetValue(key, out var cached))
+ return cached;
+
+ Font? font = null;
+ var asset = typeface.OpenStream(out var index);
+ if (asset is not null)
+ {
+ using var blob = ToBlob(asset);
+ using var face = new Face(blob, index) { Index = index, UnitsPerEm = typeface.UnitsPerEm };
+ font = new Font(face);
+ font.SetScale(HarfBuzzScale, HarfBuzzScale);
+ font.SetFunctionsOpenType();
+ }
+ _shapers[key] = font;
+ return font;
+ }
+
+ /// <summary>Wraps Skia's font data for HarfBuzz without copying when Skia has it in memory.</summary>
+ private static Blob ToBlob(SkiaSharp.SKStreamAsset asset)
+ {
+ var size = asset.Length;
+ var memory = asset.GetMemoryBase();
+ Blob blob;
+ if (memory != IntPtr.Zero)
+ {
+ blob = new Blob(memory, size, MemoryMode.ReadOnly, asset.Dispose);
+ }
+ else
+ {
+ var copy = Marshal.AllocCoTaskMem(size);
+ asset.Read(copy, size);
+ blob = new Blob(copy, size, MemoryMode.ReadOnly, () =>
+ {
+ Marshal.FreeCoTaskMem(copy);
+ asset.Dispose();
+ });
+ }
+ blob.MakeImmutable();
+ return blob;
+ }
+
+ public void Dispose()
+ {
+ foreach (var font in _shapers.Values)
+ font?.Dispose();
+ _shapers.Clear();
+ }
+}
diff --git a/src/Filee.Engines/Vector/OutlinedTextPlayback.cs b/src/Filee.Engines/Vector/OutlinedTextPlayback.cs
index ff380c8f..a8c14a5c 100644
--- a/src/Filee.Engines/Vector/OutlinedTextPlayback.cs
+++ b/src/Filee.Engines/Vector/OutlinedTextPlayback.cs
@@ -1,17 +1,13 @@
// Draws an Svg.Skia drawing with its text converted to glyph outlines, for PDF output. SkiaSharp's PDF backend is
// built without a font subsetter and embeds every font file whole: one line of Korean text adds the 13 MB Malgun
// Gothic font to the PDF. Outlines keep the text's exact shape at a few kilobytes (it is no longer selectable).
-// Text is shaped with HarfBuzz the way Svg.Skia does it (adapted from SkiaModel.TextShaping.cs, Svg.Skia, MIT).
+// Text is shaped with HarfBuzz (GlyphOutlines).
-using System.Runtime.InteropServices;
-using HarfBuzzSharp;
using ShimSkiaSharp;
using Svg.Skia;
-using Buffer = HarfBuzzSharp.Buffer;
using SKCanvas = SkiaSharp.SKCanvas;
using SKFont = SkiaSharp.SKFont;
using SKPath = SkiaSharp.SKPath;
-using SKPoint = SkiaSharp.SKPoint;
using SKTextAlign = SkiaSharp.SKTextAlign;
using SKTypeface = SkiaSharp.SKTypeface;
@@ -20,10 +16,7 @@ namespace Filee.Engines.Vector;
/// <summary>Plays back an Svg.Skia picture model, drawing text commands as paths.</summary>
internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
{
- /// <summary>HarfBuzz works in integer units: positions are computed at this scale and divided back.</summary>
- private const int HarfBuzzScale = 512;
-
- private readonly Dictionary<string, Font?> _shapers = new(StringComparer.Ordinal);
+ private readonly GlyphOutlines _glyphs = new();
/// <summary>Draws every command of <paramref name="picture"/> onto <paramref name="canvas"/>.</summary>
public void Draw(ShimSkiaSharp.SKPicture picture, SKCanvas canvas)
@@ -90,7 +83,7 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
return true;
using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint!);
var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint!.TextAlign);
- return font?.Typeface is not null && AppendShaped(path, command.Text, font, command.X, command.Y, align);
+ return font?.Typeface is not null && _glyphs.AppendShaped(path, command.Text, font, command.X, command.Y, align);
}
private bool OutlineTextBlob(DrawTextBlobCanvasCommand command, SKPath path)
@@ -106,7 +99,7 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
if (glyphs.Length != points.Length)
return false;
for (var i = 0; i < glyphs.Length; i++)
- AppendGlyph(path, font, glyphs[i], command.X + points[i].X, command.Y + points[i].Y);
+ GlyphOutlines.AppendGlyph(path, font, glyphs[i], command.X + points[i].X, command.Y + points[i].Y);
return true;
}
@@ -121,7 +114,7 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
foreach (var fragment in command.Fragments)
{
using var part = new SKPath();
- if (!AppendShaped(part, fragment.Text, font, fragment.Point.X, fragment.Point.Y, align))
+ if (!_glyphs.AppendShaped(part, fragment.Text, font, fragment.Point.X, fragment.Point.Y, align))
continue;
// Per-character rotation (SVG "rotate") and horizontal scaling (textLength), as Svg.Skia applies them.
var transform = SkiaSharp.SKMatrix.Identity;
@@ -135,100 +128,5 @@ internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable
return true;
}
- /// <summary>Shapes <paramref name="text"/> and appends its glyph outlines, aligned at (<paramref name="x"/>, <paramref name="y"/>).</summary>
- private bool AppendShaped(SKPath path, string text, SKFont font, float x, float y, SKTextAlign align)
- {
- if (string.IsNullOrEmpty(text))
- return true;
- var shaper = ShaperFor(font.Typeface);
- if (shaper is null)
- return false;
-
- using var buffer = new Buffer();
- buffer.ClusterLevel = ClusterLevel.Characters;
- buffer.AddUtf16(text);
- buffer.GuessSegmentProperties();
- shaper.Shape(buffer);
-
- var infos = buffer.GlyphInfos;
- var positions = buffer.GlyphPositions;
- var scaleY = font.Size / HarfBuzzScale;
- var scaleX = scaleY * font.ScaleX;
- var width = 0f;
- foreach (var position in positions)
- width += position.XAdvance * scaleX;
- var penX = x - align switch
- {
- SKTextAlign.Center => width / 2,
- SKTextAlign.Right => width,
- _ => 0f,
- };
- var penY = y;
- for (var i = 0; i < infos.Length; i++)
- {
- AppendGlyph(path, font, (ushort)infos[i].Codepoint, penX + positions[i].XOffset * scaleX, penY - positions[i].YOffset * scaleY);
- penX += positions[i].XAdvance * scaleX;
- penY -= positions[i].YAdvance * scaleY;
- }
- return true;
- }
-
- private static void AppendGlyph(SKPath path, SKFont font, ushort glyph, float x, float y)
- {
- using var outline = font.GetGlyphPath(glyph);
- if (outline is { IsEmpty: false })
- path.AddPath(outline, x, y);
- }
-
- /// <summary>A HarfBuzz font for the typeface (cached), or null when its font data can't be read.</summary>
- private Font? ShaperFor(SKTypeface typeface)
- {
- var key = $"{typeface.FamilyName}|{typeface.FontWeight}|{typeface.FontWidth}|{typeface.FontSlant}";
- if (_shapers.TryGetValue(key, out var cached))
- return cached;
-
- Font? font = null;
- var asset = typeface.OpenStream(out var index);
- if (asset is not null)
- {
- using var blob = ToBlob(asset);
- using var face = new Face(blob, index) { Index = index, UnitsPerEm = typeface.UnitsPerEm };
- font = new Font(face);
- font.SetScale(HarfBuzzScale, HarfBuzzScale);
- font.SetFunctionsOpenType();
- }
- _shapers[key] = font;
- return font;
- }
-
- /// <summary>Wraps Skia's font data for HarfBuzz without copying when Skia has it in memory.</summary>
- private static Blob ToBlob(SkiaSharp.SKStreamAsset asset)
- {
- var size = asset.Length;
- var memory = asset.GetMemoryBase();
- Blob blob;
- if (memory != IntPtr.Zero)
- {
- blob = new Blob(memory, size, MemoryMode.ReadOnly, asset.Dispose);
- }
- else
- {
- var copy = Marshal.AllocCoTaskMem(size);
- asset.Read(copy, size);
- blob = new Blob(copy, size, MemoryMode.ReadOnly, () =>
- {
- Marshal.FreeCoTaskMem(copy);
- asset.Dispose();
- });
- }
- blob.MakeImmutable();
- return blob;
- }
-
- public void Dispose()
- {
- foreach (var font in _shapers.Values)
- font?.Dispose();
- _shapers.Clear();
- }
+ public void Dispose() => _glyphs.Dispose();
}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index a5f09e05..e32b5aa0 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1116,6 +1116,37 @@ public class RenderTests
Assert.False(preset.Output.SubfolderOnlyForSeveralFiles);
}
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ public void Preset_editor_shows_and_saves_watermark_page_numbers_and_password(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();
+ var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "merge-pdf");
+ var vm = new PresetEditorViewModel(preset, loc);
+ Assert.True(vm.ShowPdfBuild);
+ vm.Watermark = " DRAFT ";
+ vm.PageNumbers = true;
+ vm.PdfPassword = "1234";
+
+ var window = new PresetEditorWindow { DataContext = vm, Height = 1400 };
+ window.Show();
+ Pump();
+ Save(window, $"preset-pdf-finishing-{language}.png");
+ window.Close();
+
+ Assert.True(vm.Apply());
+ Assert.Equal(("DRAFT", true, "1234"), (preset.Pdf.Watermark, preset.Pdf.PageNumbers, preset.Pdf.Password));
+ Assert.True(preset.Pdf.FinishesPdf);
+
+ // Not for other targets: nothing is kept behind them.
+ vm = new PresetEditorViewModel(preset, loc);
+ vm.Target = vm.Targets.Single(t => t.Value == "png");
+ Assert.True(vm.Apply());
+ Assert.False(preset.Pdf.FinishesPdf);
+ }
+
[AvaloniaFact]
public void Preset_editor_keeps_rotation_visible_for_pdf_and_drops_it_for_targets_that_cannot_turn()
{
diff --git a/tests/Filee.Core.Tests/PdfFinishingQueueTests.cs b/tests/Filee.Core.Tests/PdfFinishingQueueTests.cs
new file mode 100644
index 00000000..1bc2283e
--- /dev/null
+++ b/tests/Filee.Core.Tests/PdfFinishingQueueTests.cs
@@ -0,0 +1,77 @@
+// Watermark, page numbers and password are applied by JobQueue to every PDF a job writes, whichever engine made it,
+// and once to a merged PDF.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+
+namespace Filee.Core.Tests;
+
+public class PdfFinishingQueueTests
+{
+ /// <summary>Converts like <see cref="FakeConverter"/> and records the PDFs it was asked to finish.</summary>
+ private sealed class FakeFinisher(params ConversionEdge[] edges) : IConverter, IPdfFinisher
+ {
+ private readonly FakeConverter _writer = new("pdfsharp", edges);
+
+ public List<string> Finished { get; } = [];
+ public string Id => "pdfsharp";
+ public string DisplayName => "PDFsharp";
+ public IReadOnlyList<ConversionEdge> Edges => edges;
+ public int MaxParallelism => 0;
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ _writer.ConvertAsync(step, progress, cancellationToken);
+
+ public Task FinishAsync(string path, PdfOptions options, CancellationToken cancellationToken)
+ {
+ lock (Finished)
+ Finished.Add(Path.GetFileName(path));
+ return Task.CompletedTask;
+ }
+ }
+
+ [Fact]
+ public async Task Every_pdf_of_a_job_is_finished_whichever_engine_wrote_it()
+ {
+ using var dir = new TempDir();
+ var finisher = new FakeFinisher(new ConversionEdge("jpg", "pdf"));
+ var office = new FakeConverter("rhwp", new ConversionEdge("docx", "pdf"));
+ await using var queue = new JobQueue(new ConverterCatalog([finisher, office]));
+
+ var job = new ConversionJob([dir.File("scan.jpg"), dir.File("report.docx")],
+ new Preset { TargetFormat = "pdf", Pdf = { PageNumbers = true } }, "Test");
+ await queue.RunAsync(job);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(["report.pdf", "scan.pdf"], finisher.Finished.Order());
+ }
+
+ [Fact]
+ public async Task Nothing_is_finished_without_the_options_or_for_other_targets()
+ {
+ using var dir = new TempDir();
+ var finisher = new FakeFinisher(new ConversionEdge("jpg", "pdf"), new ConversionEdge("jpg", "png"));
+ await using var queue = new JobQueue(new ConverterCatalog([finisher]));
+
+ await queue.RunAsync(new ConversionJob([dir.File("a.jpg")], new Preset { TargetFormat = "pdf" }, "Test"));
+ await queue.RunAsync(new ConversionJob([dir.File("b.jpg")], new Preset { TargetFormat = "png", Pdf = { Watermark = "DRAFT" } }, "Test"));
+
+ Assert.Empty(finisher.Finished);
+ }
+
+ [Fact]
+ public async Task A_merged_pdf_is_finished_once_so_its_pages_are_numbered_through()
+ {
+ using var dir = new TempDir();
+ var finisher = new FakeFinisher(new ConversionEdge("jpg", "pdf"));
+ await using var queue = new JobQueue(new ConverterCatalog([finisher]), new FakeMerger());
+
+ var job = new ConversionJob([dir.File("1.jpg"), dir.File("2.jpg")],
+ new Preset { TargetFormat = "pdf", Pdf = { MergeIntoSingle = true, PageNumbers = true, Watermark = "DRAFT" } }, "Test");
+ await queue.RunAsync(job);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal([Path.GetFileName(job.Outputs.Single())], finisher.Finished);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/PdfFinishingTests.cs b/tests/Filee.Engines.Tests/PdfFinishingTests.cs
new file mode 100644
index 00000000..35e9580f
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PdfFinishingTests.cs
@@ -0,0 +1,86 @@
+// Watermark, page numbers and password on real PDFs (PdfFinishing): the stamps are drawn where they belong, any
+// language has outlines, and a locked PDF opens only with its password.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Pdf;
+using Filee.Engines.Vector;
+using PDFtoImage;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.IO;
+using SkiaSharp;
+
+#pragma warning disable CA1416
+
+namespace Filee.Engines.Tests;
+
+public class PdfFinishingTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ /// <summary>A PDF of blank A4 pages.</summary>
+ private static string BlankPdf(string folder, int pages)
+ {
+ var path = Path.Combine(folder, "blank.pdf");
+ using var document = new PdfDocument();
+ for (var i = 0; i < pages; i++)
+ document.AddPage();
+ document.Save(path);
+ return path;
+ }
+
+ /// <summary>Pixels of a rendered page that aren't white, in a box given as fractions of the page.</summary>
+ private static int Marked(string pdf, int page, double left, double top, double right, double bottom, string? password = null)
+ {
+ using var bitmap = Conversion.ToImage(File.ReadAllBytes(pdf), page, password, new RenderOptions(Dpi: 50, BackgroundColor: SKColors.White));
+ var count = 0;
+ for (var y = (int)(top * bitmap.Height); y < (int)(bottom * bitmap.Height); y++)
+ for (var x = (int)(left * bitmap.Width); x < (int)(right * bitmap.Width); x++)
+ if (bitmap.GetPixel(x, y).Red < 245)
+ count++;
+ return count;
+ }
+
+ [Fact]
+ public async Task A_watermark_and_page_numbers_are_drawn_on_every_page()
+ {
+ var pdf = BlankPdf(fx.NewFolder(), 2);
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "pdf", Pdf = { Watermark = "CONFIDENTIAL", PageNumbers = true } });
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var output = job.Outputs.Single();
+ for (var page = 0; page < 2; page++)
+ {
+ Assert.True(Marked(output, page, 0.3, 0.4, 0.7, 0.6) > 50, "the watermark crosses the middle");
+ Assert.True(Marked(output, page, 0.4, 0.9, 0.6, 0.99) > 5, "the page number sits at the bottom");
+ Assert.Equal(0, Marked(output, page, 0, 0, 0.1, 0.1)); // the corners stay clean
+ }
+ Assert.Equal(0, Marked(pdf, 0, 0, 0, 1, 1)); // the source is untouched
+ }
+
+ [Fact]
+ public async Task A_password_locks_the_pdf()
+ {
+ var pdf = BlankPdf(fx.NewFolder(), 1);
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "pdf", Pdf = { Password = "filee-1234" } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ var output = job.Outputs.Single();
+ Assert.ThrowsAny<Exception>(() => PdfReader.Open(output, PdfDocumentOpenMode.Import).Dispose());
+ using var opened = PdfReader.Open(output, "filee-1234", PdfDocumentOpenMode.Import);
+ Assert.Equal(1, opened.PageCount);
+ Assert.Contains("/AESV3", await File.ReadAllTextAsync(output, System.Text.Encoding.Latin1, TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public void Text_in_other_scripts_has_outlines()
+ {
+ using var glyphs = new GlyphOutlines();
+ foreach (var text in new[] { "DRAFT", "기밀", "機密", "Черновик" })
+ {
+ using var outline = PdfFinishing.Outline(glyphs, text, 40, bold: true);
+ Assert.SkipWhen(outline.IsEmpty && text != "DRAFT", $"no font for {text} on this machine");
+ Assert.False(outline.IsEmpty, text);
+ }
+ }
+}