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.

Remove empty Calc PDF pages

Perricheno7c1e700d252f
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index d6024c30..6bf226d0 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -105,6 +105,7 @@
"error.geo_unsupported_shape": "This kind of shape isn't supported",
"error.geo_too_large": "The Shapefile would pass the format's 2 GB limit",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
+ "notice.empty_spreadsheet_pages_removed": "Empty spreadsheet pages were removed",
"notice.live_photo_pair": "Saved as a photo and a MOV with the same name. Import both together (iCloud Photos, AirDrop or Photos on a Mac) to get a Live Photo",
"notice.geo_datum_assumed": "The datum isn't WGS 84; positions were converted as if it were and can be off by up to hundreds of metres",
"notice.geo_gpx_lossy": "GPX holds only points, routes and tracks with a few fields: other attributes were left out and polygons became tracks",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 3eb526c7..0e3c4e2a 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -105,6 +105,7 @@
"error.geo_unsupported_shape": "Такой тип фигуры не поддерживается",
"error.geo_too_large": "Shapefile превысил бы предел формата в 2 ГБ",
"notice.pdf_not_smaller": "Уменьшить не получилось, файл скопирован как есть",
+ "notice.empty_spreadsheet_pages_removed": "Пустые страницы таблицы удалены",
"notice.live_photo_pair": "Сохранено как фото и MOV с одинаковым именем. Импортируйте их вместе (Фото iCloud, AirDrop или «Фото» на Mac), чтобы получить Live Photo",
"notice.geo_datum_assumed": "Датум отличается от WGS 84; координаты пересчитаны как для WGS 84 и могут сместиться на сотни метров",
"notice.geo_gpx_lossy": "GPX хранит только точки, маршруты и треки с небольшим набором полей: остальные атрибуты не вошли, а полигоны стали треками",
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
index 68aa84d1..3cda8010 100644
--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -20,6 +20,7 @@
using Filee.Core.Conversion;
using Filee.Core.Formats;
using Filee.Engines.Infrastructure;
+using Filee.Engines.Pdf;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using PdfSharp.Pdf;
@@ -122,6 +123,26 @@ public sealed class LibreOfficeConverter : IConverter
throw new InvalidOperationException(
$"LibreOffice produced no output (exit {result.ExitCode}). {result.StandardError.Trim()}");
+ // Calc sometimes turns stale Excel print tiles into completely empty trailing PDF pages. Only remove pages
+ // with no painting operation at all; pages containing text, borders, charts, pictures or annotations stay.
+ if (step.To == "pdf" && FamilyOf(step.From, FormatRegistry.ExtensionOf(step.InputPath)) == "calc")
+ {
+ try
+ {
+ var removed = PdfBlankPages.Remove(produced);
+ if (removed > 0)
+ {
+ _logger.LogInformation("{File}: removed {Count} empty spreadsheet PDF pages", step.InputPath, removed);
+ step.Notice?.Invoke("notice.empty_spreadsheet_pages_removed");
+ }
+ }
+ catch (Exception e) when (e is not OperationCanceledException)
+ {
+ // Post-processing is an improvement, not a reason to discard LibreOffice's otherwise valid PDF.
+ _logger.LogInformation("{File}: could not check empty spreadsheet PDF pages: {Message}", step.InputPath, e.Message);
+ }
+ }
+
var target = step.Output.Allocate(step.To);
if (target is null)
return [];
diff --git a/src/Filee.Engines/Pdf/PdfBlankPages.cs b/src/Filee.Engines/Pdf/PdfBlankPages.cs
new file mode 100644
index 00000000..edfe1758
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfBlankPages.cs
@@ -0,0 +1,85 @@
+// Removes pages that contain no painting operations at all. This is deliberately stricter than "no text": charts,
+// borders, pictures, annotations and even a deliberately painted white rectangle keep a page. LibreOffice Calc can
+// append empty tiles when an imported spreadsheet's saved print range is wider or taller than its actual content.
+
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.Content;
+using PdfSharp.Pdf.Content.Objects;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Pdf;
+
+internal static class PdfBlankPages
+{
+ /// <summary>Operators that can put a visible mark on a page.</summary>
+ private static readonly HashSet<OpCodeName> Paint =
+ [
+ // Stroke / fill the current path.
+ OpCodeName.S, OpCodeName.s, OpCodeName.f, OpCodeName.F, OpCodeName.fx,
+ OpCodeName.B, OpCodeName.Bx, OpCodeName.b, OpCodeName.bx,
+ // XObjects, inline images and shadings.
+ OpCodeName.Do, OpCodeName.BI, OpCodeName.sh,
+ // Show text. Count it even when it happens to be empty or invisible: uncertain pages must stay.
+ OpCodeName.Tj, OpCodeName.TJ, OpCodeName.QuoteSingle, OpCodeName.QuoteDouble, OpCodeName.Tx,
+ ];
+
+ /// <summary>
+ /// Removes pages with no painting operators from <paramref name="path"/>, replacing it only after the cleaned PDF
+ /// was saved successfully. A wholly blank document is left alone: a valid PDF still needs a page, and an empty
+ /// workbook may have meant to produce one.
+ /// </summary>
+ /// <returns>The number of pages removed.</returns>
+ public static int Remove(string path)
+ {
+ var fullPath = Path.GetFullPath(path);
+ var temp = Path.Combine(Path.GetDirectoryName(fullPath)!, $".{Path.GetFileNameWithoutExtension(path)}-{Guid.NewGuid():N}.pdf");
+ try
+ {
+ int removed;
+ using (var document = PdfReader.Open(fullPath, PdfDocumentOpenMode.Modify))
+ {
+ var blank = Enumerable.Range(0, document.PageCount).Where(i => IsBlank(document.Pages[i])).ToList();
+ if (blank.Count == 0 || blank.Count == document.PageCount)
+ return 0;
+
+ for (var i = blank.Count - 1; i >= 0; i--)
+ document.Pages.RemoveAt(blank[i]);
+ removed = blank.Count;
+ document.Save(temp);
+ }
+ File.Move(temp, fullPath, overwrite: true);
+ return removed;
+ }
+ finally
+ {
+ try { File.Delete(temp); } catch (IOException) { } catch (UnauthorizedAccessException) { }
+ }
+ }
+
+ /// <summary>Unreadable content is not blank: uncertainty must never delete a user's page.</summary>
+ internal static bool IsBlank(PdfPage page)
+ {
+ if (page.Elements.GetArray("/Annots") is { Elements.Count: > 0 })
+ return false;
+ try
+ {
+ return !Paints(ContentReader.ReadContent(page));
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ return false;
+ }
+ }
+
+ private static bool Paints(CSequence content)
+ {
+ foreach (var item in content)
+ {
+ if (item is COperator op && Paint.Contains(op.OpCode.OpCodeName))
+ return true;
+ if (item is CSequence nested && Paints(nested))
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs b/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs
new file mode 100644
index 00000000..1efd0920
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs
@@ -0,0 +1,63 @@
+using Filee.Engines.Pdf;
+using PdfSharp.Drawing;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Tests;
+
+public class PdfBlankPagesTests
+{
+ [Fact]
+ public void Removes_only_pages_without_any_painting_operation()
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"filee-blank-pages-{Guid.NewGuid():N}.pdf");
+ try
+ {
+ using (var document = new PdfDocument())
+ {
+ document.AddPage(); // removed
+ var line = document.AddPage();
+ using (var graphics = XGraphics.FromPdfPage(line))
+ graphics.DrawLine(XPens.Black, 10, 10, 100, 100);
+ document.AddPage(); // removed
+ var white = document.AddPage();
+ using (var graphics = XGraphics.FromPdfPage(white))
+ graphics.DrawRectangle(XBrushes.White, 10, 10, 100, 100);
+ document.Save(path);
+ }
+
+ Assert.Equal(2, PdfBlankPages.Remove(path));
+ using var result = PdfReader.Open(path, PdfDocumentOpenMode.Import);
+ Assert.Equal(2, result.PageCount);
+ for (var i = 0; i < result.PageCount; i++)
+ Assert.False(PdfBlankPages.IsBlank(result.Pages[i]));
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public void Keeps_a_wholly_blank_document()
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"filee-blank-document-{Guid.NewGuid():N}.pdf");
+ try
+ {
+ using (var document = new PdfDocument())
+ {
+ document.AddPage();
+ document.AddPage();
+ document.Save(path);
+ }
+
+ Assert.Equal(0, PdfBlankPages.Remove(path));
+ using var result = PdfReader.Open(path, PdfDocumentOpenMode.Import);
+ Assert.Equal(2, result.PageCount);
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+}