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.

Preserve PDF structure in page tools

Perrichenob0f9c92eed8f
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4a7c9e40..ae673905 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -121,11 +121,19 @@ the drag donut shows files and flips on `FlipKeyPressed` / `FlipWheelTurned`: th
can't hold an event back; Explorer and Finder ignore Tab during a drag) and reports one flip per key press.
The editor's Front / Back switch (`ToolbarPageViewModel.EditingBack`) edits either list with the same drag and drop.
-## Crop overlay
+A group is one slice that opens up to six non-group actions. Its members may be conversions or interactive tools
+(for example the PDF Edit group contains Crop and the page editor); groups cannot contain another group. The group
+editor offers both kinds, and `UserDataStore.EnsureConsistency` removes missing, duplicate, nested or excess members
+without excluding tools.
-The Crop tool (`tool-crop`) opens `Views/CropOverlayWindow` instead of running a job: the files one after another,
+## Crop overlay and PDF page editor
+
+The image Crop tool (`tool-crop`) and PDF Crop (`tool-pdf-crop`) open `Views/CropOverlayWindow` instead of running a job:
+the files one after another,
each cropped by hand and saved by `CropService` (the preset's output rule, the source's quality kept, animated or
-multi-frame pictures refused, the EXIF thumbnail dropped), one history entry for the run.
+multi-frame pictures refused, the EXIF thumbnail dropped), one history entry for the run. A PDF preview is rendered
+with PDFium and the chosen rectangle changes every page's crop box in a copied document opened in modify mode, so
+text, vectors, outlines, forms, page labels and document information remain PDF objects and stay attached.
- `CropOverlayViewModel` walks the queue (Enter saves and opens the next file, Skip, Esc closes), keeps a
`CropQueueItem` per file for the strip of thumbnails (waiting, current, done, skipped, failed; a thumbnail is a
@@ -146,6 +154,11 @@ multi-frame pictures refused, the EXIF thumbnail dropped), one history entry for
- `Controls/CropMath` holds the arithmetic (ratios and their portrait forms, nudging by whole pixels, the frame in
pixels, where the size chip goes, where the dial opens) and is unit tested.
+`tool-pdf-pages` opens `Views/PdfPageEditorWindow`: it previews, reorders, rotates, deletes, adds and extracts pages.
+Each source PDF's bytes and page sizes are cached once after the window has appeared; thumbnails and the large preview
+render off the UI thread. A whole-document edit keeps the original catalogue and changes `/Rotate` in modify mode.
+Only an actual reorder, deletion, addition or extraction builds a new PDF from selected page objects.
+
## Settings and data
`UserDataStore` owns `settings.json`, `presets.json`, `profiles.json` and `history.json`
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 3ba038b0..41255828 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -9,7 +9,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Windows Imaging Component | part of Windows (Windows only) | **JPEG XR** (JXR, WDP, HDP; HDR screenshots of Windows) → the images ImageMagick writes, and PDF, ICNS, HEIC and SVG through PNG; HDR tone-mapped to SDR |
| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI → PDF |
| ICNS | built in | images → ICNS (16–1024 px), ICNS → images |
-| PDFsharp | built in (library) | images → PDF, merge, split, page ranges, **compression** (smaller PDFs, see below) |
+| PDFsharp | built in (library) | images → PDF, merge, split, page ranges, page organising, lossless rotate and crop-box edits, **compression** (smaller PDFs, see below) |
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML (pictures in a `<name>_files` folder next to the Markdown, embedded in the HTML) |
| Text & Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT**; **TXT, LOG, PY, PAC, BAT, COMMAND → UTF-8 TXT**, preserving source text without running scripts (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 83332f2f..7ce2605a 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -207,7 +207,7 @@
"preset.pdf_add.short": "إضافة",
"preset.pdf_extract": "استخراج صفحة",
"preset.pdf_extract.short": "استخراج",
- "preset.split_pdf.short": "استخراج",
+ "preset.split_pdf.short": "تقسيم",
"pdf_editor.title": "تحرير صفحات PDF",
"pdf_editor.hint": "أعد ترتيب الصفحات أو أدرها أو احذفها. أضف صفحات من PDF آخر أو استخرج الصفحة المحددة.",
"pdf_editor.add": "إضافة PDF",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 0dcbdefd..b4ab4523 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "Add",
"preset.pdf_extract": "Extract page",
"preset.pdf_extract.short": "Extract",
- "preset.split_pdf.short": "Extract",
+ "preset.split_pdf.short": "Split",
"pdf_editor.title": "Edit PDF pages",
"pdf_editor.hint": "Reorder, rotate or delete pages. Add pages from another PDF, or extract the selected page as its own file.",
"pdf_editor.add": "Add PDF",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 4f790ae7..97a2b9c7 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -207,7 +207,7 @@
"preset.pdf_add.short": "Añadir",
"preset.pdf_extract": "Extraer página",
"preset.pdf_extract.short": "Extraer",
- "preset.split_pdf.short": "Extraer",
+ "preset.split_pdf.short": "Dividir",
"pdf_editor.title": "Editar páginas PDF",
"pdf_editor.hint": "Reordena, gira o elimina páginas. Añade páginas de otro PDF o extrae la seleccionada como archivo independiente.",
"pdf_editor.add": "Añadir PDF",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index a99e378e..fbcbe97f 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "Ajouter",
"preset.pdf_extract": "Extraire la page",
"preset.pdf_extract.short": "Extraire",
- "preset.split_pdf.short": "Extraire",
+ "preset.split_pdf.short": "Scinder",
"pdf_editor.title": "Modifier les pages PDF",
"pdf_editor.hint": "Réorganisez, faites pivoter ou supprimez des pages. Ajoutez des pages d’un autre PDF ou extrayez la page sélectionnée.",
"pdf_editor.add": "Ajouter un PDF",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index f82d920d..dd19a4c7 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -207,7 +207,7 @@
"preset.pdf_add.short": "जोड़ें",
"preset.pdf_extract": "पृष्ठ निकालें",
"preset.pdf_extract.short": "निकालें",
- "preset.split_pdf.short": "निकालें",
+ "preset.split_pdf.short": "विभाजित करें",
"pdf_editor.title": "PDF पृष्ठ संपादित करें",
"pdf_editor.hint": "पृष्ठों का क्रम बदलें, घुमाएँ या हटाएँ। दूसरे PDF से पृष्ठ जोड़ें या चुना हुआ पृष्ठ निकालें।",
"pdf_editor.add": "PDF जोड़ें",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index c9787978..7b25ff1f 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -207,7 +207,7 @@
"preset.pdf_add.short": "追加",
"preset.pdf_extract": "ページを抽出",
"preset.pdf_extract.short": "抽出",
- "preset.split_pdf.short": "抽出",
+ "preset.split_pdf.short": "分割",
"pdf_editor.title": "PDF ページを編集",
"pdf_editor.hint": "ページの並べ替え、回転、削除ができます。別の PDF から追加するか、選択したページを抽出できます。",
"pdf_editor.add": "PDF を追加",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 4753c693..e3e89085 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -217,9 +217,9 @@
"preset.pdf_add.short": "추가",
"preset.pdf_extract": "페이지 추출",
"preset.pdf_extract.short": "추출",
- "preset.split_pdf.short": "추출",
+ "preset.split_pdf.short": "분할",
"pdf_editor.title": "PDF 페이지 편집",
- "pdf_editor.hint": "페이지 순서를 바꾸거나 회전·삭제하세요. 다른 PDF에서 페이지를 추가하거나 선택한 페이지를 추출할 수 있습니다.",
+ "pdf_editor.hint": "페이지 순서를 바꾸거나 회전·삭제하세요. 다른 PDF에서 페이지를 추가하거나 선택한 페이지를 추출할 수 있어요.",
"pdf_editor.add": "PDF 추가",
"pdf_editor.delete": "삭제",
"pdf_editor.page": "{0}페이지",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 31d4bd6f..fc01bc24 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "Dodaj",
"preset.pdf_extract": "Wyodrębnij stronę",
"preset.pdf_extract.short": "Wyodrębnij",
- "preset.split_pdf.short": "Wyodrębnij",
+ "preset.split_pdf.short": "Podziel",
"pdf_editor.title": "Edytuj strony PDF",
"pdf_editor.hint": "Zmieniaj kolejność, obracaj lub usuwaj strony. Dodaj strony z innego PDF albo wyodrębnij wybraną stronę.",
"pdf_editor.add": "Dodaj PDF",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 577b6eda..c665cbc4 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "Adicionar",
"preset.pdf_extract": "Extrair página",
"preset.pdf_extract.short": "Extrair",
- "preset.split_pdf.short": "Extrair",
+ "preset.split_pdf.short": "Dividir",
"pdf_editor.title": "Editar páginas do PDF",
"pdf_editor.hint": "Reordene, gire ou exclua páginas. Adicione páginas de outro PDF ou extraia a página selecionada.",
"pdf_editor.add": "Adicionar PDF",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 0d2581dd..2f214d63 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "Добавить",
"preset.pdf_extract": "Извлечь страницу",
"preset.pdf_extract.short": "Извлечь",
- "preset.split_pdf.short": "Извлечь",
+ "preset.split_pdf.short": "Разделить",
"pdf_editor.title": "Изменение страниц PDF",
"pdf_editor.hint": "Меняйте порядок, поворачивайте и удаляйте страницы. Добавляйте их из другого PDF или извлекайте выбранную страницу.",
"pdf_editor.add": "Добавить PDF",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index a00764d1..fbf0733b 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "添加",
"preset.pdf_extract": "提取页面",
"preset.pdf_extract.short": "提取",
- "preset.split_pdf.short": "提取",
+ "preset.split_pdf.short": "拆分",
"pdf_editor.title": "编辑 PDF 页面",
"pdf_editor.hint": "可重新排序、旋转或删除页面,也可从其他 PDF 添加页面或提取所选页面。",
"pdf_editor.add": "添加 PDF",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 82392e53..358430f6 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -217,7 +217,7 @@
"preset.pdf_add.short": "新增",
"preset.pdf_extract": "擷取頁面",
"preset.pdf_extract.short": "擷取",
- "preset.split_pdf.short": "擷取",
+ "preset.split_pdf.short": "拆分",
"pdf_editor.title": "編輯 PDF 頁面",
"pdf_editor.hint": "可重新排序、旋轉或刪除頁面,也可從其他 PDF 新增頁面或擷取所選頁面。",
"pdf_editor.add": "新增 PDF",
diff --git a/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs b/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs
index 8ce4d8eb..40a7ad46 100644
--- a/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PdfPageEditorViewModel.cs
@@ -17,9 +17,10 @@ using Microsoft.Extensions.Logging;
namespace Filee.App.ViewModels;
-public sealed partial class PdfPageItem(string path, int pageIndex, ILocalizer loc) : ObservableObject, IDisposable
+public sealed partial class PdfPageItem(PdfPreviewSource previewSource, int pageIndex, ILocalizer loc) : ObservableObject, IDisposable
{
- public string Path { get; } = path;
+ public PdfPreviewSource PreviewSource { get; } = previewSource;
+ public string Path => PreviewSource.Path;
public int PageIndex { get; } = pageIndex;
public int PageNumber => PageIndex + 1;
public string PageText => loc.Format("pdf_editor.page", PageIndex + 1);
@@ -72,7 +73,10 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
private readonly UserDataStore _store;
private readonly ILogger? _log;
private readonly string _primarySource;
+ private readonly IReadOnlyList<string> _initialFiles;
+ private readonly Dictionary<string, PdfPreviewSource> _previewSources = new(FileSystemPaths.Comparer);
private readonly SemaphoreSlim _thumbnailGate = new(1, 1);
+ private Task? _initialLoad;
private int _previewRequest;
private bool _closed;
@@ -84,8 +88,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
_store = store;
_log = log;
_primarySource = files.First();
- AddFiles(files);
- SelectedPage = Pages.FirstOrDefault();
+ _initialFiles = files;
}
public ObservableCollection<PdfPageItem> Pages { get; } = [];
@@ -126,8 +129,12 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
partial void OnSelectedPageChanged(PdfPageItem? value) => _ = LoadSelectedPreviewAsync(value);
- /// <summary>Renders the page strip after the window is visible; PDF parsing never blocks its first frame.</summary>
- public Task LoadThumbnailsAsync() => LoadThumbnailsAsync(Pages.ToList());
+ /// <summary>Opens the PDFs and renders the page strip after the window is visible.</summary>
+ public async Task LoadThumbnailsAsync()
+ {
+ await EnsureInitialFilesAsync();
+ await LoadThumbnailsAsync(Pages.ToList());
+ }
private async Task LoadThumbnailsAsync(IReadOnlyList<PdfPageItem> items)
{
@@ -141,7 +148,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
item.IsThumbnailLoading = true;
try
{
- var preview = await Task.Run(() => PdfPageTools.Preview(item.Path, item.PageIndex, 260));
+ var preview = await Task.Run(() => item.PreviewSource.Preview(item.PageIndex, 260));
if (!_closed && Pages.Contains(item))
item.SetThumbnail(preview.Png);
}
@@ -171,7 +178,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
return;
try
{
- var preview = await Task.Run(() => PdfPageTools.Preview(item.Path, item.PageIndex, 1400));
+ var preview = await Task.Run(() => item.PreviewSource.Preview(item.PageIndex, 1400));
using var stream = new MemoryStream(preview.Png);
var bitmap = new Bitmap(stream);
if (_closed || request != _previewRequest || !ReferenceEquals(item, SelectedPage))
@@ -196,20 +203,33 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
public async Task AddFilesAsync(IReadOnlyList<string> paths)
{
- if (paths.Count == 0 || IsBusy)
+ await EnsureInitialFilesAsync();
+ if (paths.Count == 0 || IsBusy || _closed)
return;
+ var added = await AddFilesCoreAsync(paths);
+ _ = LoadThumbnailsAsync(added);
+ }
+
+ private Task EnsureInitialFilesAsync() => _initialLoad ??= AddFilesCoreAsync(_initialFiles);
+
+ private async Task<IReadOnlyList<PdfPageItem>> AddFilesCoreAsync(IReadOnlyList<string> paths)
+ {
+ if (paths.Count == 0 || _closed)
+ return [];
IsBusy = true;
Status = _loc["pdf_editor.loading"];
var added = new List<PdfPageItem>();
try
{
- var counts = await Task.Run(() => paths.Select(path =>
+ var missing = paths.Distinct(FileSystemPaths.Comparer)
+ .Where(path => !_previewSources.ContainsKey(path)).ToList();
+ var opened = await Task.Run(() => missing.Select(path =>
{
- try { return (Path: path, Count: PdfPageTools.PageCount(path), Error: (Exception?)null); }
- catch (Exception ex) when (ex is not OutOfMemoryException) { return (Path: path, Count: 0, Error: ex); }
+ try { return (Path: path, Source: PdfPreviewSource.Open(path), Error: (Exception?)null); }
+ catch (Exception ex) when (ex is not OutOfMemoryException) { return (Path: path, Source: (PdfPreviewSource?)null, Error: ex); }
}).ToList());
var failed = false;
- foreach (var (path, count, error) in counts)
+ foreach (var (path, source, error) in opened)
{
if (error is not null)
{
@@ -217,9 +237,15 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
_log?.LogError(error, "Could not add {Path} to the PDF editor", path);
continue;
}
- for (var page = 0; page < count; page++)
+ _previewSources[path] = source!;
+ }
+ foreach (var path in paths)
+ {
+ if (!_previewSources.TryGetValue(path, out var source))
+ continue;
+ for (var page = 0; page < source.PageCount; page++)
{
- var item = new PdfPageItem(path, page, _loc);
+ var item = new PdfPageItem(source, page, _loc);
Pages.Add(item);
added.Add(item);
}
@@ -237,25 +263,7 @@ public sealed partial class PdfPageEditorViewModel : ObservableObject, IDisposab
{
IsBusy = false;
}
- _ = LoadThumbnailsAsync(added);
- }
-
- private void AddFiles(IEnumerable<string> paths)
- {
- foreach (var path in paths)
- {
- try
- {
- for (var page = 0; page < PdfPageTools.PageCount(path); page++)
- Pages.Add(new PdfPageItem(path, page, _loc));
- }
- catch (Exception ex) when (ex is not OutOfMemoryException)
- {
- _log?.LogError(ex, "Could not open {Path} in the PDF editor", path);
- Status = _loc["error.conversion_failed"];
- }
- }
- NotifyCollectionChanged();
+ return added;
}
private bool CanMoveUp() => !IsBusy && SelectedPage is not null && Pages.IndexOf(SelectedPage) > 0;
diff --git a/src/Filee.Engines/Pdf/PdfPageTools.cs b/src/Filee.Engines/Pdf/PdfPageTools.cs
index f6eebffc..1719723a 100644
--- a/src/Filee.Engines/Pdf/PdfPageTools.cs
+++ b/src/Filee.Engines/Pdf/PdfPageTools.cs
@@ -15,6 +15,63 @@ namespace Filee.Engines.Pdf;
public sealed record PdfPagePreview(byte[] Png, int Width, int Height);
+/// <summary>
+/// One cached PDF snapshot for previews. The bytes and page geometry are read once, so an editor with hundreds of
+/// pages does not reopen and inspect the whole file for every thumbnail.
+/// </summary>
+public sealed class PdfPreviewSource
+{
+ private readonly byte[] _pdf;
+ private readonly IReadOnlyList<(double Width, double Height)> _sizes;
+
+ private PdfPreviewSource(string path, byte[] pdf, IReadOnlyList<(double Width, double Height)> sizes)
+ {
+ Path = path;
+ _pdf = pdf;
+ _sizes = sizes;
+ }
+
+ public string Path { get; }
+ public int PageCount => _sizes.Count;
+
+ public static PdfPreviewSource Open(string path)
+ {
+ var pdf = File.ReadAllBytes(path);
+ try
+ {
+ var sizes = Conversion.GetPageSizes(pdf, null)
+ .Select(size => ((double)size.Width, (double)size.Height))
+ .ToList();
+ return new PdfPreviewSource(path, pdf, sizes);
+ }
+ catch (PdfPasswordProtectedException)
+ {
+ throw PdfDocumentReader.PasswordProtected();
+ }
+ }
+
+ /// <summary>Renders one page, bounded so a poster-sized page cannot make an enormous bitmap.</summary>
+ public PdfPagePreview Preview(int pageIndex = 0, int maxDimension = 2560)
+ {
+ if (pageIndex < 0 || pageIndex >= _sizes.Count)
+ throw new ArgumentOutOfRangeException(nameof(pageIndex));
+ var size = _sizes[pageIndex];
+ var longest = Math.Max(size.Width, size.Height);
+ var dpi = longest <= 0 ? 96 : Math.Clamp((int)Math.Floor(maxDimension * 72 / longest), 36, 150);
+ var options = new RenderOptions(Dpi: dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White);
+ try
+ {
+ using var bitmap = Conversion.ToImages(_pdf, [pageIndex], null, options).Single();
+ using var encoded = bitmap.Encode(SKEncodedImageFormat.Png, 100);
+ return new PdfPagePreview(encoded.ToArray(), bitmap.Width, bitmap.Height);
+ }
+ catch (PdfPasswordProtectedException)
+ {
+ throw PdfDocumentReader.PasswordProtected();
+ }
+ }
+}
+
/// <summary>One page in an edited document. <see cref="Rotation"/> is an additional clockwise turn in degrees.</summary>
public sealed record PdfPageReference(string Path, int PageIndex, int Rotation = 0);
@@ -32,6 +89,31 @@ public static class PdfPageTools
{
if (pages.Count == 0)
throw new InvalidOperationException("A PDF must contain at least one page.");
+
+ // Keeping every page of one document in its original order only changes /Rotate. Modify a copy so outlines,
+ // AcroForm fields, page labels and document information are not discarded by a page-by-page rebuild.
+ var originalPath = pages[0].Path;
+ if (pages.All(page => FileSystemPaths.Comparer.Equals(page.Path, originalPath))
+ && pages.Select(page => page.PageIndex).SequenceEqual(Enumerable.Range(0, pages.Count)))
+ {
+ bool keepsEveryPage;
+ using (var source = PdfSharpConverter.Open(originalPath, PdfDocumentOpenMode.Import))
+ keepsEveryPage = source.PageCount == pages.Count;
+ if (keepsEveryPage)
+ {
+ ModifyCopy(originalPath, outputPath, document =>
+ {
+ for (var index = 0; index < pages.Count; index++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (pages[index].Rotation != 0)
+ document.Pages[index].Rotate = NormaliseRotation(document.Pages[index].Rotate + pages[index].Rotation);
+ }
+ });
+ return;
+ }
+ }
+
var sources = new Dictionary<string, PdfDocument>(FileSystemPaths.Comparer);
try
{
@@ -48,7 +130,7 @@ public static class PdfPageTools
throw new InvalidDataException($"Page {item.PageIndex + 1} no longer exists in {Path.GetFileName(item.Path)}.");
var page = output.AddPage(source.Pages[item.PageIndex]);
if (item.Rotation != 0)
- page.Rotate = ((page.Rotate + item.Rotation) % 360 + 360) % 360;
+ page.Rotate = NormaliseRotation(page.Rotate + item.Rotation);
}
output.Save(outputPath);
}
@@ -62,24 +144,7 @@ public static class PdfPageTools
/// <summary>Renders one page for the crop UI, bounded so a poster-sized page cannot make an enormous bitmap.</summary>
public static PdfPagePreview Preview(string path, int pageIndex = 0, int maxDimension = 2560)
{
- var pdf = File.ReadAllBytes(path);
- try
- {
- var sizes = Conversion.GetPageSizes(pdf, null);
- if (pageIndex < 0 || pageIndex >= sizes.Count)
- throw new ArgumentOutOfRangeException(nameof(pageIndex));
- var size = sizes[pageIndex];
- var longest = Math.Max(size.Width, size.Height);
- var dpi = longest <= 0 ? 96 : Math.Clamp((int)Math.Floor(maxDimension * 72 / longest), 36, 150);
- var options = new RenderOptions(Dpi: dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White);
- using var bitmap = Conversion.ToImages(pdf, [pageIndex], null, options).Single();
- using var encoded = bitmap.Encode(SKEncodedImageFormat.Png, 100);
- return new PdfPagePreview(encoded.ToArray(), bitmap.Width, bitmap.Height);
- }
- catch (PdfPasswordProtectedException)
- {
- throw PdfDocumentReader.PasswordProtected();
- }
+ return PdfPreviewSource.Open(path).Preview(pageIndex, maxDimension);
}
/// <summary>
@@ -90,21 +155,43 @@ public static class PdfPageTools
CancellationToken cancellationToken = default)
{
(x, y, width, height) = Clamp(x, y, width, height);
- using var source = PdfSharpConverter.Open(inputPath, PdfDocumentOpenMode.Import);
- using var output = new PdfDocument();
- foreach (var sourcePage in source.Pages)
+ ModifyCopy(inputPath, outputPath, document =>
{
- cancellationToken.ThrowIfCancellationRequested();
- var page = output.AddPage(sourcePage);
- var box = page.EffectiveCropBoxReadOnly;
- var (left, bottom, right, top) = MapFromDisplayed(page.Rotate, x, y, width, height);
- page.CropBox = new PdfRectangle(
- new XPoint(box.X1 + left * box.Width, box.Y1 + bottom * box.Height),
- new XPoint(box.X1 + right * box.Width, box.Y1 + top * box.Height));
- }
- output.Save(outputPath);
+ foreach (var page in document.Pages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var box = page.EffectiveCropBoxReadOnly;
+ var (left, bottom, right, top) = MapFromDisplayed(page.Rotate, x, y, width, height);
+ page.CropBox = new PdfRectangle(
+ new XPoint(box.X1 + left * box.Width, box.Y1 + bottom * box.Height),
+ new XPoint(box.X1 + right * box.Width, box.Y1 + top * box.Height));
+ }
+ });
}
+ /// <summary>Turns every page while preserving the document catalogue, forms, labels, outlines and information.</summary>
+ internal static void RotateAll(string inputPath, string outputPath, int degrees,
+ CancellationToken cancellationToken = default) =>
+ ModifyCopy(inputPath, outputPath, document =>
+ {
+ foreach (var page in document.Pages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ page.Rotate = NormaliseRotation(page.Rotate + degrees);
+ }
+ });
+
+ private static void ModifyCopy(string inputPath, string outputPath, Action<PdfDocument> change)
+ {
+ if (!FileSystemPaths.Comparer.Equals(Path.GetFullPath(inputPath), Path.GetFullPath(outputPath)))
+ File.Copy(inputPath, outputPath, overwrite: true);
+ using var document = PdfSharpConverter.Open(outputPath, PdfDocumentOpenMode.Modify);
+ change(document);
+ document.Save(outputPath);
+ }
+
+ private static int NormaliseRotation(int rotation) => ((rotation % 360) + 360) % 360;
+
private static (double X, double Y, double Width, double Height) Clamp(double x, double y, double width, double height)
{
x = Math.Clamp(x, 0, 1);
diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
index c7673867..811a368a 100644
--- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs
+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
@@ -105,7 +105,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
return [path];
}
- /// <summary>PDF → PDF: split into single pages, or extract the configured page range.</summary>
+ /// <summary>PDF → PDF: split into single pages, extract a range, or rotate the complete document in place.</summary>
private static IReadOnlyList<string> SplitOrExtract(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
{
using var source = Open(step.InputPath, PdfDocumentOpenMode.Import);
@@ -129,6 +129,21 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
return written;
}
+ if (pages.SequenceEqual(Enumerable.Range(0, source.PageCount)))
+ {
+ var complete = step.Output.Allocate("pdf");
+ if (complete is null)
+ return [];
+ ct.ThrowIfCancellationRequested();
+ var degrees = RotationDegrees(step.Preset.Pdf.Rotation);
+ if (degrees == 0)
+ File.Copy(step.InputPath, complete, overwrite: true);
+ else
+ PdfPageTools.RotateAll(step.InputPath, complete, degrees, ct);
+ progress?.Report(1);
+ return [complete];
+ }
+
using var extract = new PdfDocument();
foreach (var index in pages)
Rotate(extract.AddPage(source.Pages[index]), step.Preset.Pdf.Rotation);
@@ -141,16 +156,19 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
private static void Rotate(PdfPage page, PdfRotation rotation)
{
- var degrees = rotation switch
+ var degrees = RotationDegrees(rotation);
+ if (degrees != 0)
+ page.Rotate = ((page.Rotate + degrees) % 360 + 360) % 360;
+ }
+
+ private static int RotationDegrees(PdfRotation rotation) =>
+ rotation switch
{
PdfRotation.Left90 => -90,
PdfRotation.Right90 => 90,
PdfRotation.Rotate180 => 180,
_ => 0,
};
- if (degrees != 0)
- page.Rotate = ((page.Rotate + degrees) % 360 + 360) % 360;
- }
/// <summary>
/// PDF → a smaller PDF (<see cref="PdfOptions.Compression"/>), also with a page range or one file per page: the whole
@@ -181,10 +199,18 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
parts.Add((path, $"_p{index + 1}"));
}
}
- else if (options.Rotation == PdfRotation.None
- && pages.SequenceEqual(Enumerable.Range(0, source.PageCount)))
+ else if (pages.SequenceEqual(Enumerable.Range(0, source.PageCount)))
{
- parts.Add((step.InputPath, null));
+ if (options.Rotation == PdfRotation.None)
+ {
+ parts.Add((step.InputPath, null));
+ }
+ else
+ {
+ var path = Path.Combine(scratch, "rotated.pdf");
+ PdfPageTools.RotateAll(step.InputPath, path, RotationDegrees(options.Rotation), ct);
+ parts.Add((path, null));
+ }
}
else
{
diff --git a/tests/Filee.App.Tests/PdfPageEditorTests.cs b/tests/Filee.App.Tests/PdfPageEditorTests.cs
index c83af14e..3931a8fb 100644
--- a/tests/Filee.App.Tests/PdfPageEditorTests.cs
+++ b/tests/Filee.App.Tests/PdfPageEditorTests.cs
@@ -52,6 +52,8 @@ public class PdfPageEditorTests
preset.Output.CustomFolder = folder;
using var vm = new PdfPageEditorViewModel([first], preset, AppHost.Get<ILocalizer>(), store);
+ Assert.Empty(vm.Pages); // The constructor does not parse the PDF on the UI thread.
+ await vm.LoadThumbnailsAsync();
await vm.AddFilesAsync([added]);
vm.SelectedPage = vm.Pages[2];
vm.MoveUpCommand.Execute(null);
@@ -91,12 +93,12 @@ public class PdfPageEditorTests
{
SelectedPage = null,
};
- vm.SelectedPage = vm.Pages[1];
- vm.RotateRightCommand.Execute(null);
var window = new PdfPageEditorWindow { DataContext = vm };
window.Show();
await vm.LoadThumbnailsAsync();
+ vm.SelectedPage = vm.Pages[1];
+ vm.RotateRightCommand.Execute(null);
for (var i = 0; i < 100 && !vm.HasSelectedPreview; i++)
{
RenderTests.Pump();
diff --git a/tests/Filee.Engines.Tests/PdfPageToolsTests.cs b/tests/Filee.Engines.Tests/PdfPageToolsTests.cs
index a454c41e..45803850 100644
--- a/tests/Filee.Engines.Tests/PdfPageToolsTests.cs
+++ b/tests/Filee.Engines.Tests/PdfPageToolsTests.cs
@@ -23,6 +23,54 @@ public class PdfPageToolsTests(EngineFixture fx) : IClassFixture<EngineFixture>
return path;
}
+ private static string MakeStructuredPdf(string folder, string name)
+ {
+ var path = Path.Combine(folder, name);
+ using var document = new PdfDocument();
+ var first = document.AddPage();
+ document.AddPage();
+ document.Info.Title = "Preserve this title";
+ document.Info.Author = "Filee tests";
+ document.Outlines.Add("First page", first);
+ var field = new PdfDictionary(document);
+ field.Elements.SetName("/FT", "/Tx");
+ field.Elements.SetString("/T", "Customer");
+ field.Elements.SetString("/V", "Alice");
+ document.Internals.AddObject(field);
+ var fields = new PdfArray(document);
+ fields.Elements.Add(field.Reference!);
+ var form = new PdfDictionary(document);
+ form.Elements.SetString("/FileeFormMarker", "form stays");
+ form.Elements["/Fields"] = fields;
+ document.Internals.AddObject(form);
+ document.Internals.Catalog.Elements["/AcroForm"] = form.Reference;
+ var labelStyle = new PdfDictionary(document);
+ labelStyle.Elements.SetName("/S", "/D");
+ labelStyle.Elements.SetString("/P", "Page ");
+ var numbers = new PdfArray(document);
+ numbers.Elements.Add(new PdfInteger(0));
+ numbers.Elements.Add(labelStyle);
+ var labels = new PdfDictionary(document);
+ labels.Elements.SetString("/FileeLabelMarker", "labels stay");
+ labels.Elements["/Nums"] = numbers;
+ document.Internals.AddObject(labels);
+ document.Internals.Catalog.Elements["/PageLabels"] = labels.Reference;
+ document.Save(path);
+ return path;
+ }
+
+ private static void AssertStructurePreserved(string path)
+ {
+ using var result = PdfReader.Open(path, PdfDocumentOpenMode.Import);
+ Assert.Equal("Preserve this title", result.Info.Title);
+ Assert.Equal("Filee tests", result.Info.Author);
+ Assert.Equal("First page", Assert.Single(result.Outlines).Title);
+ Assert.Equal("form stays", result.AcroForm.Elements.GetString("/FileeFormMarker"));
+ Assert.Equal("Customer", Assert.Single(result.AcroForm.Fields.Names));
+ Assert.Equal("labels stay", result.Internals.Catalog.Elements
+ .GetDictionary("/PageLabels")!.Elements.GetString("/FileeLabelMarker"));
+ }
+
[Fact]
public void Save_reorders_combines_and_rotates_pages_without_rasterising()
{
@@ -59,6 +107,46 @@ public class PdfPageToolsTests(EngineFixture fx) : IClassFixture<EngineFixture>
AssertBox(result.Pages[1].CropBox, 120, 80, 480, 480);
}
+ [Fact]
+ public void Whole_document_crop_preserves_outlines_forms_page_labels_and_information()
+ {
+ var folder = fx.NewFolder();
+ var source = MakeStructuredPdf(folder, "structured.pdf");
+ var output = Path.Combine(folder, "cropped.pdf");
+
+ PdfPageTools.CropAll(source, output, .1, .1, .8, .8, TestContext.Current.CancellationToken);
+
+ AssertStructurePreserved(output);
+ }
+
+ [Fact]
+ public void Whole_document_page_editor_rotation_preserves_document_structure()
+ {
+ var folder = fx.NewFolder();
+ var source = MakeStructuredPdf(folder, "structured.pdf");
+ var output = Path.Combine(folder, "rotated.pdf");
+
+ PdfPageTools.Save([new(source, 0, 90), new(source, 1, -90)], output,
+ TestContext.Current.CancellationToken);
+
+ AssertStructurePreserved(output);
+ using var result = PdfReader.Open(output, PdfDocumentOpenMode.Import);
+ Assert.Equal([90, 270], result.Pages.Cast<PdfPage>().Select(page => page.Rotate));
+ }
+
+ [Fact]
+ public void Preview_source_keeps_one_cached_snapshot_for_all_pages()
+ {
+ var folder = fx.NewFolder();
+ var source = MakePdf(folder, "preview.pdf", (200, 500, 0), (300, 500, 0));
+ var preview = PdfPreviewSource.Open(source);
+ File.Delete(source);
+
+ Assert.Equal(2, preview.PageCount);
+ Assert.NotEmpty(preview.Preview(0, 100).Png);
+ Assert.NotEmpty(preview.Preview(1, 100).Png);
+ }
+
[Theory]
[InlineData(PdfCompression.None)]
[InlineData(PdfCompression.Ebook)]
@@ -80,6 +168,29 @@ public class PdfPageToolsTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal([90, 180], result.Pages.Cast<PdfPage>().Select(p => p.Rotate));
}
+ [Theory]
+ [InlineData(PdfCompression.None)]
+ [InlineData(PdfCompression.Ebook)]
+ public async Task Pdf_rotation_preset_preserves_complete_document_structure(PdfCompression compression)
+ {
+ var folder = fx.NewFolder();
+ var source = MakeStructuredPdf(folder, "structured.pdf");
+ var preset = new Preset
+ {
+ TargetFormat = "pdf",
+ Output = { FileNamePattern = "{name}_right" },
+ Pdf = { Rotation = PdfRotation.Right90, Compression = compression },
+ };
+
+ var job = await fx.ConvertAsync([source], preset);
+
+ Assert.Equal(Filee.Core.Conversion.JobState.Completed, job.State);
+ var output = Assert.Single(job.Outputs);
+ AssertStructurePreserved(output);
+ using var result = PdfReader.Open(output, PdfDocumentOpenMode.Import);
+ Assert.All(result.Pages.Cast<PdfPage>(), page => Assert.Equal(90, page.Rotate));
+ }
+
private static void AssertBox(PdfRectangle actual, double x1, double y1, double x2, double y2)
{
Assert.Equal(x1, actual.X1, 6);