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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
fix(pdf): handle owner restrictions and read-only sources
Perricheno85d529ff9da0
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex ae673905..721dfa22 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -157,7 +157,10 @@ text, vectors, outlines, forms, page labels and document information remain PDF`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 previewrender 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.+An actual reorder, deletion, addition or extraction builds a new PDF from selected page objects. A PDF that opens+without a password but requires an owner password for modify mode uses the same page-copy fallback as compression;+its outlines and form fields are not preserved by that fallback. Generated copies are writable even when the source+has the read-only attribute; the source's bytes and attributes are left alone.## Settings and datadiff --git a/src/Filee.Engines/Pdf/PdfPageTools.cs b/src/Filee.Engines/Pdf/PdfPageTools.csindex 1719723a..3cf160cb 100644--- a/src/Filee.Engines/Pdf/PdfPageTools.cs+++ b/src/Filee.Engines/Pdf/PdfPageTools.cs@@ -184,8 +184,8 @@ public static class PdfPageToolsprivate 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);+ PdfSharpConverter.CopyWritable(inputPath, outputPath);+ using var document = PdfSharpConverter.OpenForChanges(outputPath);change(document);document.Save(outputPath);}diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.csindex 811a368a..fda52b21 100644--- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs@@ -137,7 +137,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransformect.ThrowIfCancellationRequested();var degrees = RotationDegrees(step.Preset.Pdf.Rotation);if (degrees == 0)- File.Copy(step.InputPath, complete, overwrite: true);+ CopyWritable(step.InputPath, complete);elsePdfPageTools.RotateAll(step.InputPath, complete, degrees, ct);progress?.Report(1);@@ -283,10 +283,10 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransformevar best = candidates.Select(path => new FileInfo(path)).MinBy(file => file.Length);if (best is not null && best.Length < original){- File.Copy(best.FullName, output, overwrite: true);+ CopyWritable(best.FullName, output);return true;}- File.Copy(plain, output, overwrite: true);+ CopyWritable(plain, output);return false;}@@ -294,7 +294,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{@@ -308,6 +308,17 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransformecopy.AddPage(page);return copy;}+ catch (PdfReaderException ex) when (ex.Message.Contains("password", StringComparison.OrdinalIgnoreCase))+ {+ throw PdfDocumentReader.PasswordProtected();+ }+ }++ /// <summary>Copies a PDF without passing a source's read-only attribute to the generated output.</summary>+ internal static void CopyWritable(string source, string destination)+ {+ File.Copy(source, destination, overwrite: true);+ File.SetAttributes(destination, File.GetAttributes(destination) & ~FileAttributes.ReadOnly);}/// <summary>Opens a PDF; a password-protected one fails with the message the other PDF conversions give.</summary>diff --git a/tests/Filee.Engines.Tests/PdfPageToolsTests.cs b/tests/Filee.Engines.Tests/PdfPageToolsTests.csindex 45803850..41b8ad42 100644--- a/tests/Filee.Engines.Tests/PdfPageToolsTests.cs+++ b/tests/Filee.Engines.Tests/PdfPageToolsTests.cs@@ -191,6 +191,88 @@ public class PdfPageToolsTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.All(result.Pages.Cast<PdfPage>(), page => Assert.Equal(90, page.Rotate));}+ [Theory]+ [InlineData(true, false)]+ [InlineData(false, true)]+ [InlineData(true, true)]+ public void Crop_and_editor_rotation_accept_owner_restrictions_and_read_only_sources(bool ownerOnly, bool readOnly)+ {+ var folder = fx.NewFolder();+ var source = MakeSpecialSource(folder, ownerOnly, readOnly);+ var original = File.ReadAllBytes(source);+ try+ {+ var cropped = Path.Combine(folder, "cropped.pdf");+ PdfPageTools.CropAll(source, cropped, .1, .2, .5, .6, TestContext.Current.CancellationToken);+ using (var result = PdfReader.Open(cropped, PdfDocumentOpenMode.Import))+ {+ Assert.Equal(2, result.PageCount);+ AssertBox(result.Pages[0].CropBox, 60, 160, 360, 640);+ }+ Assert.False(File.GetAttributes(cropped).HasFlag(FileAttributes.ReadOnly));++ var rotated = Path.Combine(folder, "rotated.pdf");+ PdfPageTools.Save([new(source, 0, 90), new(source, 1, -90)], rotated,+ TestContext.Current.CancellationToken);+ using (var result = PdfReader.Open(rotated, PdfDocumentOpenMode.Import))+ Assert.Equal([90, 0], result.Pages.Cast<PdfPage>().Select(page => page.Rotate));+ Assert.False(File.GetAttributes(rotated).HasFlag(FileAttributes.ReadOnly));+ Assert.Equal(original, File.ReadAllBytes(source));+ Assert.Equal(readOnly, File.GetAttributes(source).HasFlag(FileAttributes.ReadOnly));+ }+ finally { File.SetAttributes(source, File.GetAttributes(source) & ~FileAttributes.ReadOnly); }+ }++ [Theory]+ [InlineData(true, false, PdfCompression.None, PdfRotation.Right90)]+ [InlineData(true, false, PdfCompression.Ebook, PdfRotation.Right90)]+ [InlineData(false, true, PdfCompression.None, PdfRotation.Right90)]+ [InlineData(false, true, PdfCompression.Ebook, PdfRotation.Right90)]+ [InlineData(false, true, PdfCompression.None, PdfRotation.None)]+ [InlineData(false, true, PdfCompression.Ebook, PdfRotation.None)]+ public async Task Presets_accept_owner_restrictions_and_write_writable_outputs(bool ownerOnly, bool readOnly,+ PdfCompression compression, PdfRotation rotation)+ {+ var folder = fx.NewFolder();+ var source = MakeSpecialSource(folder, ownerOnly, readOnly);+ var original = File.ReadAllBytes(source);+ try+ {+ var job = await fx.ConvertAsync([source], new Preset+ {+ TargetFormat = "pdf",+ Output = { FileNamePattern = "{name}_edited" },+ Pdf = { Rotation = rotation, Compression = compression },+ });++ Assert.True(job.State == Filee.Core.Conversion.JobState.Completed,+ string.Join("; ", job.Files.Select(file => file.ErrorDetail)));+ var output = Assert.Single(job.Outputs);+ using var result = PdfReader.Open(output, PdfDocumentOpenMode.Import);+ var expected = rotation == PdfRotation.Right90 ? new[] { 90, 180 } : [0, 90];+ Assert.Equal(expected, result.Pages.Cast<PdfPage>().Select(page => page.Rotate));+ Assert.False(File.GetAttributes(output).HasFlag(FileAttributes.ReadOnly));+ Assert.Equal(original, File.ReadAllBytes(source));+ Assert.Equal(readOnly, File.GetAttributes(source).HasFlag(FileAttributes.ReadOnly));+ }+ finally { File.SetAttributes(source, File.GetAttributes(source) & ~FileAttributes.ReadOnly); }+ }++ private static string MakeSpecialSource(string folder, bool ownerOnly, bool readOnly)+ {+ var source = MakePdf(folder, "source.pdf", (600, 800, 0), (600, 800, 90));+ if (ownerOnly)+ {+ using var document = PdfReader.Open(source, PdfDocumentOpenMode.Modify);+ document.SecuritySettings.OwnerPassword = "owner-only";+ document.SecuritySettings.PermitModifyDocument = false;+ document.Save(source);+ }+ if (readOnly)+ File.SetAttributes(source, File.GetAttributes(source) | FileAttributes.ReadOnly);+ return source;+ }+private static void AssertBox(PdfRectangle actual, double x1, double y1, double x2, double y2){Assert.Equal(x1, actual.X1, 6);