From a01230773cce9183ae5e253ca94e97b0018b3f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Thu, 19 Nov 2026 15:07:43 +0100 Subject: [PATCH 1/7] Fixed issue where acrobat reader would detect cells as form fillable in an odd way. --- .../DocumentObjects/PdfBorderRenderer.cs | 13 +++++- .../DocumentObjects/PdfCatalog.cs | 7 +++ .../DocumentObjects/PdfContentStream.cs | 43 +++++++++++++++++-- src/EPPlus.Export.Pdf/ExcelPdf.cs | 16 +++++++ .../Settings/PdfDocumentSettings.cs | 4 +- .../Settings/PdfPageSettings.cs | 5 +++ 6 files changed, 81 insertions(+), 7 deletions(-) diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfBorderRenderer.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfBorderRenderer.cs index 7031399f4..93b799794 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfBorderRenderer.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfBorderRenderer.cs @@ -49,16 +49,25 @@ public PdfBorderRenderer(PdfCellBorderLayout cell) DiagonalDown = cell.BorderData.DiagonalDown; } + public bool HasBorder() + { + if (Top != null) return true; + if (Bottom != null) return true; + if (Left != null) return true; + if (Right != null) return true; + if (DiagonalUp != null) return true; + if (DiagonalDown != null) return true; + return false; + } + public void RenderBorder(PdfContentStream contentStream) { - contentStream.AddCommand("q"); if (Top != null) RenderBorder(contentStream, Top); if (Bottom != null) RenderBorder(contentStream, Bottom); if (Left != null) RenderBorder(contentStream, Left); if (Right != null) RenderBorder(contentStream, Right); if (DiagonalUp != null) RenderBorder(contentStream, DiagonalUp); if (DiagonalDown != null) RenderBorder(contentStream, DiagonalDown); - contentStream.AddCommand("Q"); } private void RenderBorder(PdfContentStream contentStream, PdfCellBorderData border) diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs index fbe409f8f..5daa886ae 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs @@ -20,6 +20,7 @@ internal class PdfCatalog : PdfObject private readonly int pagesObjectNumber; internal int NamesObjectNumber = 0; internal int OutlinesObjectNumber = 0; + internal int AcroFormObjectNumber = 0; public PdfCatalog(int objectNumber, int pagesObjectNumber, int version = 0) : base(objectNumber, version) @@ -32,8 +33,14 @@ private string Body() var sb = new System.Text.StringBuilder(); sb.Append("<< /Type /Catalog\n"); sb.Append($" /Pages {pagesObjectNumber.ToPdfStringF0()} 0 R"); + if (AcroFormObjectNumber > 0) + { + sb.Append($"\n /AcroForm {AcroFormObjectNumber.ToPdfStringF0()} 0 R"); + } if (NamesObjectNumber > 0) + { sb.Append($"\n /Names {NamesObjectNumber.ToPdfStringF0()} 0 R"); + } if (OutlinesObjectNumber > 0) { sb.Append($"\n /Outlines {OutlinesObjectNumber.ToPdfStringF0()} 0 R"); diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs index 90584d918..d906370a1 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs @@ -32,6 +32,21 @@ namespace EPPlus.Export.Pdf.DocumentObjects internal class PdfContentStream : PdfObject { private readonly List commands = new List(); + private readonly Stack<(int index, string header)> _artifactMarks = new Stack<(int, string)>(); + + public void BeginArtifact() => _artifactMarks.Push((commands.Count, "/Artifact BMC")); + public void BeginArtifact(string type) => _artifactMarks.Push((commands.Count, $"/Artifact << /Type /{type} >> BDC")); + + public void EndArtifact() + { + if (_artifactMarks.Count == 0) return; + var mark = _artifactMarks.Pop(); + if (commands.Count > mark.index) + { + commands.Insert(mark.index, mark.header); + commands.Add("EMC"); + } + } public PdfContentStream(int objectNumber, string command = null, int version = 0) : base(objectNumber, version) @@ -58,6 +73,7 @@ public void AddContentScale(double scale, double anchorX, double anchorY) public void AddCellLayout(PdfCellLayout cell, string label) { if (cell.Size.X <= 0d || cell.Size.Y <= 0d) return; + BeginArtifact(); if (cell.CellFillData.GradientFillData != null && cell.CellFillData.PatternStyle != ExcelFillStyle.Solid) { commands.Add("q"); @@ -96,12 +112,20 @@ public void AddCellLayout(PdfCellLayout cell, string label) commands.Add("f"); commands.Add("Q"); } + EndArtifact(); } public void AddBorderLayout(PdfCellBorderLayout cell) { var borderRenderer = new PdfBorderRenderer(cell); - borderRenderer.RenderBorder(this); + if (borderRenderer.HasBorder()) + { + BeginArtifact(); + commands.Add("q"); + borderRenderer.RenderBorder(this); + commands.Add("Q"); + EndArtifact(); + } } public void AddText(PdfCellContentLayout cell, Vector2 position, double textRotation, PdfDictionaries dictionaries, PdfPageSettings pageSettings) @@ -380,6 +404,7 @@ public void AddInnerGridLines(Transform pageLayout) { if (pageLayout is not PdfPageLayout pl) return; if (pl.isCommentsPage) return; + BeginArtifact(); commands.Add("q"); commands.Add($"{GridLine.Width.ToPdfString()} w"); commands.Add(Color.Black.ToFillCommand()); @@ -402,20 +427,23 @@ public void AddInnerGridLines(Transform pageLayout) } commands.Add("f"); commands.Add("Q"); + EndArtifact(); } public void AddImage(string label, double x, double y, double width, double height) { + BeginArtifact(); commands.Add("q"); commands.Add($"{width.ToPdfString()} 0 0 {height.ToPdfString()} {x.ToPdfString()} {y.ToPdfString()} cm"); commands.Add($"/{label} Do"); commands.Add("Q"); + EndArtifact(); } public void AddPrintTitleGridLines(Transform pageLayout) { if (pageLayout is not PdfPageLayout pl) return; if (pl.isCommentsPage) return; - + BeginArtifact(); commands.Add("q"); commands.Add($"{GridLine.Width.ToPdfString()} w"); commands.Add(Color.Black.ToFillCommand()); @@ -438,13 +466,14 @@ public void AddPrintTitleGridLines(Transform pageLayout) } commands.Add("f"); commands.Add("Q"); + EndArtifact(); } public void AddOuterGridBorder(Transform pageLayout) { if (pageLayout is not PdfPageLayout pl) return; if (pl.isCommentsPage) return; - + BeginArtifact(); commands.Add("q"); commands.Add("1.0 w"); commands.Add("2 J"); @@ -457,6 +486,7 @@ public void AddOuterGridBorder(Transform pageLayout) } commands.Add("S"); commands.Add("Q"); + EndArtifact(); } public void AddMarginClipping(PdfPageLayout pageLayout, PdfPageSettings pageSettings) @@ -516,6 +546,7 @@ public void AddDataBarLayout(PdfDataBarLayout bar) if (barW > 0d && bar.FillColor != Color.Empty) { + BeginArtifact(); commands.Add("q"); if (bar.Gradient) { @@ -552,10 +583,12 @@ public void AddDataBarLayout(PdfDataBarLayout bar) commands.Add("S"); } commands.Add("Q"); + EndArtifact(); } if (bar.AxisColor != null) // thin vertical axis line { + BeginArtifact(); commands.Add("q"); commands.Add(bar.AxisColor.Value.ToStrokeCommand()); commands.Add($"{(GridLine.Width*3).ToPdfString()} w"); // thicker (was GridLine.HalfWidth) @@ -564,6 +597,7 @@ public void AddDataBarLayout(PdfDataBarLayout bar) commands.Add($"{axisX.ToPdfString()} {(barY + barH).ToPdfString()} l"); commands.Add("S"); commands.Add("Q"); + EndArtifact(); } } @@ -599,11 +633,12 @@ public void AddIconLayout(PdfIconLayout icon) break; } double s = size / 100d; - + BeginArtifact(); commands.Add("q"); commands.Add($"{s.ToPdfString()} 0 0 {s.ToPdfString()} {iconX.ToPdfString()} {iconY.ToPdfString()} cm"); PdfIconRenderer.Render(icon.IconName, this); commands.Add("Q"); + EndArtifact(); } internal override string RenderDictionary() diff --git a/src/EPPlus.Export.Pdf/ExcelPdf.cs b/src/EPPlus.Export.Pdf/ExcelPdf.cs index 76962d646..e55d15e4e 100644 --- a/src/EPPlus.Export.Pdf/ExcelPdf.cs +++ b/src/EPPlus.Export.Pdf/ExcelPdf.cs @@ -480,6 +480,21 @@ private static bool TryResolveDest(List<(PdfPageLayout Layout, int PageObj)> ind return false; } + private void AddFormFieldSuppressor(PdfCatalog catalog, PdfPage[] pageObjs) + { + if (!_documentSettings.SuppressFormFieldDetection) return; + if (pageObjs.Length == 0) return; + + var page = pageObjs[0]; + var field = new PdfFormFieldObject(_document.Count + 1, page.objectNumber); + _document.Add(field); + page.annotationObjectNumbers.Add(field.objectNumber); // widget must also be in the page's /Annots + + var acro = new PdfAcroForm(_document.Count + 1, new List { field.objectNumber }); + _document.Add(acro); + catalog.AcroFormObjectNumber = acro.objectNumber; + } + //Add Info private PdfInfoObject AddInfoObject() { @@ -570,6 +585,7 @@ private void BuildDocument(PdfDocumentSettings documentSettings, PdfDictionaries { AddContent((PdfPageLayout)layout.ChildObjects[i], pageObjs[i], destIndex); } + AddFormFieldSuppressor(catalog, pageObjs); var catLayout = layout as PdfCatalogLayout; //Create Named destinations AddNamedDestinations(catalog, destIndex, catLayout); diff --git a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs index 170fbafc9..356e9ccea 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs @@ -31,6 +31,7 @@ internal class PdfDocumentSettings internal string Author; internal bool BlackAndWhite; internal string BookmarkNamePrefix; + internal bool SuppressFormFieldDetection; internal static PdfDocumentSettings From(PdfPageSettings s) { @@ -49,7 +50,8 @@ internal static PdfDocumentSettings From(PdfPageSettings s) Title = s.Title, Author = s.Author, BlackAndWhite = s.BlackAndWhite, - BookmarkNamePrefix = s.BookmarkNamePrefix + BookmarkNamePrefix = s.BookmarkNamePrefix, + SuppressFormFieldDetection = s.SuppressFormFieldDetection, }; } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs index db010ca83..c59f76a8c 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs @@ -60,6 +60,11 @@ public OpenTypeFontEngine FontEngine /// public string BookmarkNamePrefix = "bm_"; + /// + /// Set true to supress Acrobat Readers auto detecting of form fillable areas. + /// + public bool SuppressFormFieldDetection = true; + /// /// The order in how to create pages. /// From b533d318241a895fa134179cd2273c1600a61f84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Fri, 20 Nov 2026 11:09:51 +0100 Subject: [PATCH 2/7] forgot to include new files... --- .../DocumentObjects/PdfAcroForm .cs | 42 ++++++++++++++++ .../DocumentObjects/PdfFormFieldObject .cs | 48 +++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs create mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs new file mode 100644 index 000000000..c2cfd7ebf --- /dev/null +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs @@ -0,0 +1,42 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 + *************************************************************************************************/ +using EPPlus.Export.Pdf.Helpers; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace EPPlus.Export.Pdf.DocumentObjects +{ + // Minimal AcroForm whose only job is to declare that the document already + // has form fields (see PdfFormFieldObject). NeedAppearances is false so no + // viewer tries to regenerate appearances for the invisible field. + internal class PdfAcroForm : PdfObject + { + private readonly List fieldObjectNumbers; + + public PdfAcroForm(int objectNumber, List fieldObjectNumbers, int version = 0) + : base(objectNumber, version) + { + this.fieldObjectNumbers = fieldObjectNumbers; + } + + private string Body() + { + var fields = string.Join(" ", fieldObjectNumbers.Select(n => $"{n.ToPdfStringF0()} 0 R")); + return $"<< /Fields [ {fields} ]\n /NeedAppearances false >>"; + } + + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs new file mode 100644 index 000000000..f7884f74d --- /dev/null +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs @@ -0,0 +1,48 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 + *************************************************************************************************/ +using EPPlus.Export.Pdf.Helpers; +using System.IO; + +namespace EPPlus.Export.Pdf.DocumentObjects +{ + // A single hidden, read-only widget/field. Its only purpose is to make the + // document count as an already-prepared AcroForm, so Acrobat's Fill & Sign + // auto-detection stands down instead of offering fillable areas over our + // gridline tables. It never renders and cannot be interacted with. + internal class PdfFormFieldObject : PdfObject + { + private readonly int pageObjectNumber; + private readonly string fieldName; + + public PdfFormFieldObject(int objectNumber, int pageObjectNumber, string fieldName = "epplus_noautofield", int version = 0) + : base(objectNumber, version) + { + this.pageObjectNumber = pageObjectNumber; + this.fieldName = fieldName; + } + + private string Body() + { + return $"<< /Type /Annot /Subtype /Widget\n" + + $" /FT /Tx\n" + + $" /T {fieldName.ToPdfTextString()}\n" + + $" /Ff 1\n" + + $" /F 2\n" + + $" /Rect [ 0 0 1 1 ]\n" + + $" /P {pageObjectNumber.ToPdfStringF0()} 0 R >>"; + } + + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + } +} \ No newline at end of file From 112ca3fa529a2d3cf44cf43d0929eec8095ea65d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Fri, 20 Nov 2026 14:26:57 +0100 Subject: [PATCH 3/7] progress --- src/EPPlus.Export.Pdf.Tests/FontTests.cs | 8 +- .../LigatureDligReproTests.cs | 2 +- .../MeasurementRenderWidthParityTests.cs | 6 +- .../MultipleSubstitutionReproTests.cs | 2 +- .../PdfCellLayoutShadingTests.cs | 2 +- .../PdfPageSettingsOrientationTests.cs | 2 +- src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs | 10 +-- src/EPPlus.Export.Pdf.Tests/PdfTests.cs | 10 +-- .../PdfTextShaperShapingOptionsTests.cs | 4 +- .../VariationSequenceReproTests.cs | 2 +- .../DocumentObjects/PdfContentStream.cs | 6 +- src/EPPlus.Export.Pdf/ExcelPdf.cs | 2 +- .../Layout/PdfCellContentLayout.cs | 4 +- src/EPPlus.Export.Pdf/Layout/PdfCellLayout.cs | 2 +- src/EPPlus.Export.Pdf/Layout/PdfPageLayout.cs | 2 +- .../Resources/PdfDictionaries.cs | 10 +-- .../Resources/PdfFontResource.cs | 2 +- .../Settings/PdfDocumentSettings.cs | 4 +- ...dfPageSettings.cs => PdfRenderSettings.cs} | 76 ++++++++--------- src/EPPlus/ExcelWorksheet.cs | 5 ++ src/EPPlus/Export/PdfExport/Data/PageData.cs | 2 +- .../Export/PdfExport/EPPlusToPdfWriter.cs | 68 +++++++-------- .../PdfExport/Layout/PdfGridlinesLayout.cs | 2 +- .../PdfExport/Layout/PdfHeaderFooterLayout.cs | 16 ++-- .../PdfExport/Layout/PdfHeadingLayout.cs | 14 ++-- .../PdfExport/Layout/PdfImagePlacement.cs | 4 +- .../Export/PdfExport/Layout/PdfLayout.cs | 24 +++--- .../PdfExport/Layout/PdfMergedCellLayout.cs | 4 +- .../Export/PdfExport/Layout/PdfPaginator.cs | 10 +-- .../Export/PdfExport/Layout/PdfSpillLayout.cs | 4 +- .../Export/PdfExport/PdfExportSettings.cs | 83 +++++++++++++++++++ .../PdfExport/PdfExportSettingsOverrides.cs | 19 +++++ .../PdfExport/Settings/GetPdfSettings.cs | 40 ++++++++- .../TextMapping/PdfAdditionalContent.cs | 2 +- .../TextMapping/PdfHeaderFooterCollection.cs | 2 +- .../TextMapping/PdfHeaderFooterTextBuilder.cs | 2 +- .../TextMapping/PdfTextFragmentBuilder.cs | 8 +- .../PdfExport/TextMapping/PdfTextMap.cs | 8 +- .../PdfExport/TextShaping/PdfTextShaper.cs | 6 +- 39 files changed, 307 insertions(+), 172 deletions(-) rename src/EPPlus.Export.Pdf/Settings/{PdfPageSettings.cs => PdfRenderSettings.cs} (83%) create mode 100644 src/EPPlus/Export/PdfExport/PdfExportSettings.cs create mode 100644 src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs diff --git a/src/EPPlus.Export.Pdf.Tests/FontTests.cs b/src/EPPlus.Export.Pdf.Tests/FontTests.cs index 33ab4ad5c..5fe4c90ef 100644 --- a/src/EPPlus.Export.Pdf.Tests/FontTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/FontTests.cs @@ -53,14 +53,14 @@ private static OpenTypeFontEngine CreateEngine() }); } - private static PdfPageSettings CreateSettings(OpenTypeFontEngine engine, bool embeddFonts) + private static PdfRenderSettings CreateSettings(OpenTypeFontEngine engine, bool embeddFonts) { - var settings = new PdfPageSettings(engine); + var settings = new PdfRenderSettings(engine); settings.EmbeddFonts = embeddFonts; return settings; } - private static PdfDictionaries CreateDictionariesWithSingleFont(PdfPageSettings settings, OpenTypeFontEngine engine) + private static PdfDictionaries CreateDictionariesWithSingleFont(PdfRenderSettings settings, OpenTypeFontEngine engine) { var dictionaries = new PdfDictionaries(); @@ -182,7 +182,7 @@ public void FontObjects_ForSubsetFont_ShareIdenticalTaggedName() var font = engine.LoadFont("Calibri"); var subset = new SingleFontSubsetter().Subset(font, new HashSet { 65, 66, 67 }, true); - var resource = new PdfFontResource("Calibri", FontSubFamily.Regular, 1, new PdfPageSettings(engine)); + var resource = new PdfFontResource("Calibri", FontSubFamily.Regular, 1, new PdfRenderSettings(engine)); resource.fontData = subset; // Object numbers are arbitrary; they only need to be set in dependency order. diff --git a/src/EPPlus.Export.Pdf.Tests/LigatureDligReproTests.cs b/src/EPPlus.Export.Pdf.Tests/LigatureDligReproTests.cs index bdb2ad147..ede4468bd 100644 --- a/src/EPPlus.Export.Pdf.Tests/LigatureDligReproTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/LigatureDligReproTests.cs @@ -87,7 +87,7 @@ public void Th_EBGaramond48_DligOn_MergesIntoLigature() // GsubFeature.Dlig cannot be requested through the plain SaveAsPdf overloads - // see PdfTestBase's PdfPageSettings-accepting overload for why. - var settings = new PdfPageSettings(engine) + var settings = new PdfRenderSettings(engine) { GsubFeatures = GsubFeature.Liga | GsubFeature.Clig | GsubFeature.Dlig }; diff --git a/src/EPPlus.Export.Pdf.Tests/MeasurementRenderWidthParityTests.cs b/src/EPPlus.Export.Pdf.Tests/MeasurementRenderWidthParityTests.cs index 060b68f27..6e7523d28 100644 --- a/src/EPPlus.Export.Pdf.Tests/MeasurementRenderWidthParityTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/MeasurementRenderWidthParityTests.cs @@ -96,7 +96,7 @@ public void MeasuredWidth_MatchesRenderedWidth_ForKernedText() sheet.Row(1).Height = 70; var engine = package.Workbook.RenderContext.FontEngine; - var settings = new PdfPageSettings(engine); + var settings = new PdfRenderSettings(engine); var range = sheet.Cells["A1"]; double measuredWidth = GetMeasuredWidth(settings, range); @@ -123,14 +123,14 @@ public void MeasuredWidth_MatchesRenderedWidth_ForKernedText() } } - private static double GetMeasuredWidth(PdfPageSettings settings, ExcelRangeBase range) + private static double GetMeasuredWidth(PdfRenderSettings settings, ExcelRangeBase range) { var catalog = new EPPlusToPdfWriter(); var cells = catalog.GetCellCollectionFromRange(settings, range); return cells[range.Start.Row, range.Start.Column].TotalTextLength; } - private static byte[] RenderToBytes(PdfPageSettings settings, ExcelWorksheet sheet) + private static byte[] RenderToBytes(PdfRenderSettings settings, ExcelWorksheet sheet) { using (var stream = new MemoryStream()) { diff --git a/src/EPPlus.Export.Pdf.Tests/MultipleSubstitutionReproTests.cs b/src/EPPlus.Export.Pdf.Tests/MultipleSubstitutionReproTests.cs index 9c3abbd5c..e1c2dfe24 100644 --- a/src/EPPlus.Export.Pdf.Tests/MultipleSubstitutionReproTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/MultipleSubstitutionReproTests.cs @@ -152,7 +152,7 @@ public void MultipleSubstitution_Roboto_ReproSheet() var engine = CreateEngine(); InjectDigitFiveExpandsToHi(engine); - var settings = new PdfPageSettings(engine); + var settings = new PdfRenderSettings(engine); // Written to disk for visual inspection - this is the whole point of the test. SaveAsPdf(sheet, "MultipleSubstitutionRepro", settings); diff --git a/src/EPPlus.Export.Pdf.Tests/PdfCellLayoutShadingTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfCellLayoutShadingTests.cs index 8323cb172..ef8d1798d 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfCellLayoutShadingTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfCellLayoutShadingTests.cs @@ -11,7 +11,7 @@ public class PdfCellLayoutShadingTests { private const double Tol = 1e-9; - private static PdfPageSettings NewSettings() => new PdfPageSettings(new OpenTypeFontEngine()); + private static PdfRenderSettings NewSettings() => new PdfRenderSettings(new OpenTypeFontEngine()); private static PdfCellLayout LinearCell(double degree) { diff --git a/src/EPPlus.Export.Pdf.Tests/PdfPageSettingsOrientationTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfPageSettingsOrientationTests.cs index 4570faa7f..a93990acd 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfPageSettingsOrientationTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfPageSettingsOrientationTests.cs @@ -9,7 +9,7 @@ public class PdfPageSettingsOrientationTests { private const double Tol = 1e-9; - private static PdfPageSettings NewSettings() => new PdfPageSettings(new OpenTypeFontEngine()); + private static PdfRenderSettings NewSettings() => new PdfRenderSettings(new OpenTypeFontEngine()); [TestMethod] public void Orientation_Landscape_MakesWidthExceedHeight_AndRecalculatesBounds() diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs b/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs index d2e7101db..4b9e9a96b 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs @@ -54,7 +54,7 @@ protected void SaveAsPdf(byte[] pdfBytes, string pdfFileName) /// (GetPdfSettings.GetPdfSettingsFromPrinterSettings) with no way to override it. /// Drives PdfCatalog directly: the same internal entry point SaveAsPdf itself calls into. /// - protected void SaveAsPdf(ExcelWorksheet sheet, string pdfFileName, PdfPageSettings settings) + protected void SaveAsPdf(ExcelWorksheet sheet, string pdfFileName, PdfRenderSettings settings) { if (!pdfFileName.ToLower().EndsWith(".pdf")) { @@ -69,10 +69,10 @@ protected void SaveAsPdf(ExcelWorksheet sheet, string pdfFileName, PdfPageSettin } /// - /// Workbook-level counterpart to . + /// Workbook-level counterpart to . /// See that overload's remarks for why this bypasses ExcelWorkbook.SaveAsPdf. /// - protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfPageSettings settings) + protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings settings) { if (!pdfFileName.ToLower().EndsWith(".pdf")) { @@ -83,10 +83,10 @@ protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfPageSettings s } /// - /// Range-collection counterpart to . + /// Range-collection counterpart to . /// See that overload's remarks for why this bypasses ExcelRangeBase/ExcelWorkbook.SaveAsPdf. /// - protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfPageSettings settings, params ExcelRangeBase[] ranges) + protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings settings, params ExcelRangeBase[] ranges) { string path = GetPdfFilePath(pdfFileName); if (ranges.Count() > 1) diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs index 5220e474a..e81db9480 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs @@ -379,7 +379,7 @@ public void SaveWorksheetToStreamViaCatalogTest() { using var p = OpenTemplatePackage("PDFTest.xlsx"); var ws = p.Workbook.Worksheets[0]; - var pageSettings = new PdfPageSettings(ws.Workbook.RenderContext.FontEngine); + var pageSettings = new PdfRenderSettings(ws.Workbook.RenderContext.FontEngine); using var ms = new MemoryStream(); var pdfCatalog = new EPPlusToPdfWriter(pageSettings, ws); pdfCatalog.Save(ms); @@ -670,7 +670,7 @@ public void WorkbookTests(string sourceFile, string outputPath, string wsName) var d = ws.Dimension; var d2 = ws.DimensionByValue; - PdfPageSettings pageSettings = new PdfPageSettings(ws.Workbook.RenderContext.FontEngine); + PdfRenderSettings pageSettings = new PdfRenderSettings(ws.Workbook.RenderContext.FontEngine); pageSettings.CommentsAndNotes = CommentsAndNotes.AtEndOfSheet; pageSettings.CellErrors = CellErrors.Displayed; @@ -925,7 +925,7 @@ public void HeaderFooterTest1() [TestMethod] public void GetOriginX_CenteringOff_ReturnsContentBoundsLeft() { - var s = new PdfPageSettings(null); + var s = new PdfRenderSettings(null); var p = new Page() { FromRow = 1, @@ -943,7 +943,7 @@ public void GetOriginX_CenteringOff_ReturnsContentBoundsLeft() [TestMethod] public void GetOrigin_FlagsAreIndependent() { - var s = new PdfPageSettings(null); + var s = new PdfRenderSettings(null); s.CenterOnPageHorizontally = true; var p = new Page() { @@ -962,7 +962,7 @@ public void GetOrigin_FlagsAreIndependent() [TestMethod] public void GetClampedCellWidth_CellFitsWithinPage_ReturnsCellWidthUnchanged() { - var s = new PdfPageSettings(null); + var s = new PdfRenderSettings(null); Assert.AreEqual(51.71d, PdfLayout.GetClampedCellWidth(s, 126.31d, 51.71d), 0.0001); } diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTextShaperShapingOptionsTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfTextShaperShapingOptionsTests.cs index 3533f764d..19c8dffc8 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTextShaperShapingOptionsTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTextShaperShapingOptionsTests.cs @@ -33,12 +33,12 @@ public class PdfTextShaperShapingOptionsTests { public TestContext? TestContext { get; set; } - private static PdfPageSettings CreateSettings() + private static PdfRenderSettings CreateSettings() { // BuildShapingOptions never touches pageSettings.FontEngine, but the engine is kept // alive (not disposed) regardless, so this helper stays valid if that ever changes. var engine = new OpenTypeFontEngine(); - return new PdfPageSettings(engine); + return new PdfRenderSettings(engine); } [TestMethod] diff --git a/src/EPPlus.Export.Pdf.Tests/VariationSequenceReproTests.cs b/src/EPPlus.Export.Pdf.Tests/VariationSequenceReproTests.cs index 188cf9835..28b2d1c2d 100644 --- a/src/EPPlus.Export.Pdf.Tests/VariationSequenceReproTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/VariationSequenceReproTests.cs @@ -79,7 +79,7 @@ public void VariationSequence_BizUdGothic_ReproSheet() BuildReproSheet(sheet); var engine = CreateEngine(); - var settings = new PdfPageSettings(engine); + var settings = new PdfRenderSettings(engine); // Written to disk for visual inspection - this is the whole point of the test. SaveAsPdf(sheet, "VariationSequenceRepro", settings); diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs index 90584d918..cf3c9e9a7 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs @@ -104,7 +104,7 @@ public void AddBorderLayout(PdfCellBorderLayout cell) borderRenderer.RenderBorder(this); } - public void AddText(PdfCellContentLayout cell, Vector2 position, double textRotation, PdfDictionaries dictionaries, PdfPageSettings pageSettings) + public void AddText(PdfCellContentLayout cell, Vector2 position, double textRotation, PdfDictionaries dictionaries, PdfRenderSettings pageSettings) { double advanceY = 0d; double line0Width = cell.TextLines.Count > 0 ? cell.TextLines[0].Width : 0d; @@ -363,7 +363,7 @@ private static ushort GetUnitsPerEm(ushort[] fontUnitsPerEm, byte fontId, ushort return defaultUnitsPerEm > 0 ? defaultUnitsPerEm : (ushort)1000; } - public void AddCellContentLayout(PdfCellContentLayout cell, PdfDictionaries dictionaries, PdfPageSettings pageSettings) + public void AddCellContentLayout(PdfCellContentLayout cell, PdfDictionaries dictionaries, PdfRenderSettings pageSettings) { commands.Add("q"); if (cell.Clip) AddClipping(cell); @@ -459,7 +459,7 @@ public void AddOuterGridBorder(Transform pageLayout) commands.Add("Q"); } - public void AddMarginClipping(PdfPageLayout pageLayout, PdfPageSettings pageSettings) + public void AddMarginClipping(PdfPageLayout pageLayout, PdfRenderSettings pageSettings) { if (pageLayout is not PdfPageLayout pl) return; if (pageLayout.isCommentsPage) return; diff --git a/src/EPPlus.Export.Pdf/ExcelPdf.cs b/src/EPPlus.Export.Pdf/ExcelPdf.cs index 76962d646..8193a52d0 100644 --- a/src/EPPlus.Export.Pdf/ExcelPdf.cs +++ b/src/EPPlus.Export.Pdf/ExcelPdf.cs @@ -153,7 +153,7 @@ private void AddImageData() } //Create Page - private PdfPage AddPage(int pagesObjectNumber, List contentObjectNumbers, PdfPageSettings settings) + private PdfPage AddPage(int pagesObjectNumber, List contentObjectNumbers, PdfRenderSettings settings) { var page = new PdfPage(_document.Count + 1, pagesObjectNumber, contentObjectNumbers, settings.PageSize, _dictionaries); _document.Add(page); diff --git a/src/EPPlus.Export.Pdf/Layout/PdfCellContentLayout.cs b/src/EPPlus.Export.Pdf/Layout/PdfCellContentLayout.cs index 3f6579df5..75e92efc6 100644 --- a/src/EPPlus.Export.Pdf/Layout/PdfCellContentLayout.cs +++ b/src/EPPlus.Export.Pdf/Layout/PdfCellContentLayout.cs @@ -45,7 +45,7 @@ internal class PdfCellContentLayout : Transform public List ShapedTexts { get; set; } - public PdfCellContentLayout(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfCellBase cell, double x, double y, double width, double height, double scaleX = 1, double scaleY = 1, double rotation = 0, Transform parent = null) + public PdfCellContentLayout(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfCellBase cell, double x, double y, double width, double height, double scaleX = 1, double scaleY = 1, double rotation = 0, Transform parent = null) : base(x, y-height, width, height, scaleX, scaleY, rotation, parent) { Z = 2; @@ -63,7 +63,7 @@ public PdfCellContentLayout(PdfPageSettings pageSettings, PdfDictionaries dictio LocalPosition = PdfCellAlignment.CalculateAlignment(CellAlignmentData, cell.Text, TextLines.LineFragments[0].Width, totalTextHeight, firstLineAscent, lastLineAscent, LocalPosition.X, LocalPosition.Y, width, height, rightMargin, bottomMargin); } - public PdfCellContentLayout(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter headerFooter, double x, double y, double width, double height, double scaleX = 1, double scaleY = 1, double rotation = 0, Transform parent = null) + public PdfCellContentLayout(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter headerFooter, double x, double y, double width, double height, double scaleX = 1, double scaleY = 1, double rotation = 0, Transform parent = null) : base(x, y, width, height, scaleX, scaleY, rotation, parent) { Z = 2; diff --git a/src/EPPlus.Export.Pdf/Layout/PdfCellLayout.cs b/src/EPPlus.Export.Pdf/Layout/PdfCellLayout.cs index c0967c411..701d823a5 100644 --- a/src/EPPlus.Export.Pdf/Layout/PdfCellLayout.cs +++ b/src/EPPlus.Export.Pdf/Layout/PdfCellLayout.cs @@ -103,7 +103,7 @@ private string AddShadingResourceData(Dictionary sha return key; } - public void UpdateShadingPositionMatrix(PdfPageSettings pageSettings) + public void UpdateShadingPositionMatrix(PdfRenderSettings pageSettings) { if (CellFillData.GradientFillData != null) { diff --git a/src/EPPlus.Export.Pdf/Layout/PdfPageLayout.cs b/src/EPPlus.Export.Pdf/Layout/PdfPageLayout.cs index 0a3a2c789..11b521f86 100644 --- a/src/EPPlus.Export.Pdf/Layout/PdfPageLayout.cs +++ b/src/EPPlus.Export.Pdf/Layout/PdfPageLayout.cs @@ -30,7 +30,7 @@ internal class PdfPageLayout : Transform public bool isCommentsPage = false; public bool ScaleHeaderFooterWithDocument; internal List HeaderFooterParts = new List(); - internal PdfPageSettings Settings; + internal PdfRenderSettings Settings; internal List Links = new List(); public string SheetName; public string CommentsSourceSheet; diff --git a/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs b/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs index 3f348aad3..cd160c642 100644 --- a/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs +++ b/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs @@ -38,7 +38,7 @@ private static string BuildRequestCacheKey(string family, FontSubFamily subFamil return fam + "|" + ((int)subFamily); } - internal FontKey ResolveFontKey(PdfPageSettings pageSettings, string family, FontSubFamily subFamily) + internal FontKey ResolveFontKey(PdfRenderSettings pageSettings, string family, FontSubFamily subFamily) { var cacheKey = BuildRequestCacheKey(family, subFamily); FontKey key; @@ -52,20 +52,20 @@ internal FontKey ResolveFontKey(PdfPageSettings pageSettings, string family, Fon return key; } - public void AddFont(PdfPageSettings pageSettings, string fontName, FontSubFamily subFamily, string text) + public void AddFont(PdfRenderSettings pageSettings, string fontName, FontSubFamily subFamily, string text) { EnsureBuilder(pageSettings); ResolveFontKey(pageSettings, fontName, subFamily); _subsetBuilder.AddText(fontName, subFamily, text); } - private void EnsureBuilder(PdfPageSettings pageSettings) + private void EnsureBuilder(PdfRenderSettings pageSettings) { if (_subsetBuilder == null) _subsetBuilder = new DocumentFontSubsetBuilder(pageSettings.FontEngine); } - internal void BuildSubsets(PdfPageSettings pageSettings) + internal void BuildSubsets(PdfRenderSettings pageSettings) { if (_subsetBuilder == null) return; _subsetBuilder.Build(); @@ -78,7 +78,7 @@ internal void BuildSubsets(PdfPageSettings pageSettings) } } - internal PdfFontResource GetFont(PdfPageSettings pageSettings, string fontName, FontSubFamily subFamily) + internal PdfFontResource GetFont(PdfRenderSettings pageSettings, string fontName, FontSubFamily subFamily) { var requestedKey = ResolveFontKey(pageSettings, fontName, subFamily); IFontProvider provider; diff --git a/src/EPPlus.Export.Pdf/Resources/PdfFontResource.cs b/src/EPPlus.Export.Pdf/Resources/PdfFontResource.cs index 32e0b7d04..2726b0e8c 100644 --- a/src/EPPlus.Export.Pdf/Resources/PdfFontResource.cs +++ b/src/EPPlus.Export.Pdf/Resources/PdfFontResource.cs @@ -45,7 +45,7 @@ internal class PdfFontResource : PdfResource internal HashSet Gids = new HashSet(); internal Dictionary charactermappings = new Dictionary(); - public PdfFontResource(string fontName, FontSubFamily subFamily, int labelNumber, PdfPageSettings pageSettings) + public PdfFontResource(string fontName, FontSubFamily subFamily, int labelNumber, PdfRenderSettings pageSettings) : base("F", labelNumber) { this.fontName = fontName; diff --git a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs index 170fbafc9..810f6b5c8 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs @@ -31,8 +31,9 @@ internal class PdfDocumentSettings internal string Author; internal bool BlackAndWhite; internal string BookmarkNamePrefix; + internal bool SuppressFormFieldDetection; - internal static PdfDocumentSettings From(PdfPageSettings s) + internal static PdfDocumentSettings From(PdfRenderSettings s) { return new PdfDocumentSettings { @@ -50,6 +51,7 @@ internal static PdfDocumentSettings From(PdfPageSettings s) Author = s.Author, BlackAndWhite = s.BlackAndWhite, BookmarkNamePrefix = s.BookmarkNamePrefix + SuppressFormFieldDetection = s.SuppressFormFieldDetection }; } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs similarity index 83% rename from src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs rename to src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs index db010ca83..6f9743b96 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfPageSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs @@ -20,7 +20,7 @@ namespace EPPlus.Export.Pdf.Settings /// /// Settings object for exporting to PDF. /// - public class PdfPageSettings + internal class PdfRenderSettings { internal string Author { get; set; } internal string Title { get; set; } @@ -31,7 +31,7 @@ public class PdfPageSettings /// /// Get the current font engine that is being used by EPPlus. /// - public OpenTypeFontEngine FontEngine + internal OpenTypeFontEngine FontEngine { get { @@ -42,94 +42,94 @@ public OpenTypeFontEngine FontEngine /// /// Add additional folders to search for fonts. /// - public List FontDirectories = new List(); + internal List FontDirectories = new List(); /// /// If true, epplus will look for fonts in the system directories for installed fonts. c:\windows\fonts /// - public bool SearchSystemDirectories = true; + internal bool SearchSystemDirectories = true; /// /// If true, subsetted fonts will be embedded into the PDF document. /// - public bool EmbeddFonts = true; + internal bool EmbeddFonts = true; /// /// Prefix for marking a defined name as a bookmark for PDF export. The prefix gets stripped from the bookmark name. /// The name used for the bookmark is first check on the cells content. If the cell has no content it uses the defined name instead. /// - public string BookmarkNamePrefix = "bm_"; + internal string BookmarkNamePrefix = "bm_"; /// /// The order in how to create pages. /// - public PageOrders PageOrders = PageOrders.DownThenOver; + internal PageOrders PageOrders = PageOrders.DownThenOver; /// /// Set to true to center content on page vertically. /// - public bool CenterOnPageVertically; + internal bool CenterOnPageVertically; /// /// Set to true to center content on page horizontally. /// - public bool CenterOnPageHorizontally; + internal bool CenterOnPageHorizontally; /// /// Set true to show grid lines. /// - public bool ShowGridLines = false; + internal bool ShowGridLines = false; /// /// Set true to show row and column headings. /// - public bool ShowHeadings = false; + internal bool ShowHeadings = false; /// /// Set to true for to only use black and white. /// - public bool BlackAndWhite = false; + internal bool BlackAndWhite = false; /// /// Set to true for to make a draft. /// - public bool Draft = false; + internal bool Draft = false; /// /// Set the range to repeat at the top of the page. /// - public string RowsToRepeatAtTop = null; + internal string RowsToRepeatAtTop = null; /// /// Set the range to repeat to the left of the page. /// - public string ColumnsToRepeatAtLeft = null; + internal string ColumnsToRepeatAtLeft = null; /// /// Specific range to print. /// - public string PrintArea = null; + internal string PrintArea = null; /// /// Set if comments and notes should be included. /// - public CommentsAndNotes CommentsAndNotes = CommentsAndNotes.None; + internal CommentsAndNotes CommentsAndNotes = CommentsAndNotes.None; /// /// Sets how to display errors in cells. /// - public CellErrors CellErrors = CellErrors.Displayed; + internal CellErrors CellErrors = CellErrors.Displayed; /// /// Set the starting page number. /// - public int FirstPageNumber = 1; + internal int FirstPageNumber = 1; PdfPageSize _pageSize = PdfPageSize.A4; /// /// Set the size of pages. /// - public PdfPageSize PageSize + internal PdfPageSize PageSize { get { @@ -158,7 +158,7 @@ public PdfPageSize PageSize /// /// Set the orientation of the pages. /// - public Orientations Orientation + internal Orientations Orientation { get { @@ -177,7 +177,7 @@ public Orientations Orientation /// /// Set the page margins. /// - public PdfMargins Margins + internal PdfMargins Margins { get { @@ -194,7 +194,7 @@ public PdfMargins Margins /// /// Set the scaling. NOT IMPLEMENTED /// - public PdfScaling Scaling + internal PdfScaling Scaling { get { @@ -236,7 +236,7 @@ internal double ContentScale /// on the font actually defining it; see for what each flag /// means and which fonts typically support it. /// - public GsubFeature GsubFeatures { get; set; } = GsubFeature.Liga | GsubFeature.Clig | GsubFeature.Calt | GsubFeature.Ccmp; + internal GsubFeature GsubFeatures { get; set; } = GsubFeature.Liga | GsubFeature.Clig | GsubFeature.Calt | GsubFeature.Ccmp; /// /// GPOS (glyph positioning) features to request when shaping text for this export, e.g. @@ -248,18 +248,20 @@ internal double ContentScale /// on the font actually defining it; see for what each flag /// means. /// - public GposFeature GposFeatures { get; set; } = GposFeature.Kern | GposFeature.Mark; + internal GposFeature GposFeatures { get; set; } = GposFeature.Kern | GposFeature.Mark; internal PdfContentBounds ContentBounds = new PdfContentBounds(PdfMargins.Normal, PdfPageSize.A4); internal string defaultFontName = ""; internal string AdditionalContent; + internal bool SuppressFormFieldDetection { get; set; } = true; + //DEBUG internal bool Debug = false; internal bool PrintAsText = false; - public PdfPageSettings(OpenTypeFontEngine fontEngine) + internal PdfRenderSettings(OpenTypeFontEngine fontEngine) { _fontEngine = fontEngine; } @@ -273,18 +275,10 @@ private static PdfPageSize ApplyOrientation(PdfPageSize size, Orientations orien : new PdfPageSize(size.Height, size.Width); // swap (ctor is width, height) } - internal PdfPageSettings CloneForSheet() + internal PdfRenderSettings CloneForSheet() { - var c = new PdfPageSettings(_fontEngine); - c.FontDirectories = FontDirectories; - c.SearchSystemDirectories = SearchSystemDirectories; - c.EmbeddFonts = EmbeddFonts; - c.defaultFontName = defaultFontName; - c.GsubFeatures = GsubFeatures; - c.GposFeatures = GposFeatures; - c.Debug = Debug; - c.PrintAsText = PrintAsText; - c.AdditionalContent = AdditionalContent; + var c = (PdfRenderSettings)MemberwiseClone(); + c.ContentBounds = new PdfContentBounds(_margins, _pageSize); return c; } } @@ -292,7 +286,7 @@ internal PdfPageSettings CloneForSheet() /// /// Orientation of pages. /// - public enum Orientations + internal enum Orientations { /// /// Portrait orientation. @@ -307,7 +301,7 @@ public enum Orientations /// /// Order of pages. /// - public enum PageOrders + internal enum PageOrders { /// /// Order Down then over. @@ -322,7 +316,7 @@ public enum PageOrders /// /// How comments will be displayed. /// - public enum CommentsAndNotes + internal enum CommentsAndNotes { /// /// Comments and Notes will be ignored. @@ -341,7 +335,7 @@ public enum CommentsAndNotes /// /// How errors will be displayed. /// - public enum CellErrors + internal enum CellErrors { /// /// Errors will be displayed diff --git a/src/EPPlus/ExcelWorksheet.cs b/src/EPPlus/ExcelWorksheet.cs index 24617249a..8a42d8993 100644 --- a/src/EPPlus/ExcelWorksheet.cs +++ b/src/EPPlus/ExcelWorksheet.cs @@ -3733,6 +3733,11 @@ internal bool IsDisposed // Replaces all SaveAsPdf / SaveAsPdfAsync methods in OfficeOpenXml.ExcelWorksheet. + /// + /// Worksheet specific overrides for PDF export. + /// + public PdfExportSettingsOverrides PdfExportOverrides { get; } = new PdfExportSettingsOverrides(); + /// /// Export worksheet to PDF. /// diff --git a/src/EPPlus/Export/PdfExport/Data/PageData.cs b/src/EPPlus/Export/PdfExport/Data/PageData.cs index 1b2d79c95..fbe944269 100644 --- a/src/EPPlus/Export/PdfExport/Data/PageData.cs +++ b/src/EPPlus/Export/PdfExport/Data/PageData.cs @@ -87,7 +87,7 @@ internal struct Pages public string HeadingFontName; public float HeadingFontSize; public ExcelFill HeadingFill; - public PdfPageSettings Settings; + public PdfRenderSettings Settings; public int SheetIndex; public string SheetName; public int Count diff --git a/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs b/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs index 2c84cf417..3e926c4fe 100644 --- a/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs +++ b/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs @@ -55,7 +55,7 @@ private static bool IsFullEdition // The build returns the finished layout. Any temporary comments/notes worksheet created while // building is registered in _sheetsWithTemporaryComments as soon as it exists, and is removed // by the Save methods, also when the build or the write fails. - private readonly PdfPageSettings _pageSettings; + private readonly PdfRenderSettings _pageSettings; private readonly Func _build; private readonly List _sheetsWithTemporaryComments = new List(); private bool _isUsed; @@ -66,25 +66,25 @@ public EPPlusToPdfWriter() { } // CONSTRUCTORS FOR MULTIPLE WORKSHEETS AS INPUT // - public EPPlusToPdfWriter(PdfPageSettings pageSettings, ExcelWorkbook workbook) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, ExcelWorkbook workbook) { _pageSettings = pageSettings; var worksheets = workbook.Worksheets.ToArray(); _build = () => HandleWorksheetCollection(pageSettings, worksheets); } - public EPPlusToPdfWriter(PdfPageSettings pageSettings, ExcelWorksheet[] worksheets) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, ExcelWorksheet[] worksheets) { _pageSettings = pageSettings; _build = () => HandleWorksheetCollection(pageSettings, worksheets); } - public EPPlusToPdfWriter(PdfPageSettings pageSettings, List worksheets) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, List worksheets) : this(pageSettings, worksheets.ToArray()) { } - private Transform HandleWorksheetCollection(PdfPageSettings pageSettings, ExcelWorksheet[] worksheets) + private Transform HandleWorksheetCollection(PdfRenderSettings pageSettings, ExcelWorksheet[] worksheets) { InitDocumentSettings(pageSettings, worksheets[0].Workbook); @@ -107,7 +107,7 @@ private Transform HandleWorksheetCollection(PdfPageSettings pageSettings, ExcelW // CONSTRUCTORS FOR SINGLE WORKSHEET AS INPUT // - public EPPlusToPdfWriter(PdfPageSettings pageSettings, ExcelWorksheet worksheet) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, ExcelWorksheet worksheet) { _pageSettings = pageSettings; _build = () => BuildPdf(pageSettings, worksheet); @@ -120,7 +120,7 @@ private static string AddAdditionalContent() return "null"; } - private Transform BuildPdf(PdfPageSettings pageSettings, ExcelWorksheet worksheet) + private Transform BuildPdf(PdfRenderSettings pageSettings, ExcelWorksheet worksheet) { InitDocumentSettings(pageSettings, worksheet.Workbook); @@ -142,13 +142,13 @@ private Transform BuildPdf(PdfPageSettings pageSettings, ExcelWorksheet workshee // CONSTRUCTORS FOR RANGE AS INPUT // - public EPPlusToPdfWriter(PdfPageSettings pageSettings, ExcelRangeBase range) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, ExcelRangeBase range) { _pageSettings = pageSettings; _build = () => BuildPdfFromRange(pageSettings, range); } - private Transform BuildPdfFromRange(PdfPageSettings pageSettings, ExcelRangeBase range) + private Transform BuildPdfFromRange(PdfRenderSettings pageSettings, ExcelRangeBase range) { InitDocumentSettings(pageSettings, range.Worksheet.Workbook); var pdfSheet = GetPdfWorksheet(pageSettings, range); @@ -158,18 +158,18 @@ private Transform BuildPdfFromRange(PdfPageSettings pageSettings, ExcelRangeBase return GetLayout(pageSettings, pdfSheet); } - public EPPlusToPdfWriter(PdfPageSettings pageSettings, ExcelRangeBase[] ranges) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, ExcelRangeBase[] ranges) { _pageSettings = pageSettings; _build = () => HandleRangeCollection(pageSettings, ranges); } - public EPPlusToPdfWriter(PdfPageSettings pageSettings, List ranges) + public EPPlusToPdfWriter(PdfRenderSettings pageSettings, List ranges) : this(pageSettings, ranges.ToArray()) { } - private Transform HandleRangeCollection(PdfPageSettings pageSettings, ExcelRangeBase[] ranges) + private Transform HandleRangeCollection(PdfRenderSettings pageSettings, ExcelRangeBase[] ranges) { InitDocumentSettings(pageSettings, ranges[0].Worksheet.Workbook); @@ -188,7 +188,7 @@ private Transform HandleRangeCollection(PdfPageSettings pageSettings, ExcelRange // Document-level settings shared by all build paths: metadata/license info, default font // and additional content. Previously the worksheet-collection path did not set the metadata. - private void InitDocumentSettings(PdfPageSettings pageSettings, ExcelWorkbook workbook) + private void InitDocumentSettings(PdfRenderSettings pageSettings, ExcelWorkbook workbook) { GetLicenseInfo(pageSettings, workbook); pageSettings.defaultFontName = workbook.ThemeManager.GetOrCreateTheme().FontScheme.MinorFont[0].Typeface; @@ -262,7 +262,7 @@ private void DeleteTemporarySheets() _sheetsWithTemporaryComments.Clear(); } - internal PdfCellCollection GetCellCollectionFromRange(PdfPageSettings pageSettings, ExcelRangeBase range) + internal PdfCellCollection GetCellCollectionFromRange(PdfRenderSettings pageSettings, ExcelRangeBase range) { PdfWorksheet pdfSheet = GetPdfWorksheet(pageSettings, range); ShapeTextInPdfWorksheet(pageSettings, pdfSheet); @@ -272,7 +272,7 @@ internal PdfCellCollection GetCellCollectionFromRange(PdfPageSettings pageSettin //Private Methods - private void GetLicenseInfo(PdfPageSettings pageSettings, ExcelWorkbook workbook) + private void GetLicenseInfo(PdfRenderSettings pageSettings, ExcelWorkbook workbook) { pageSettings.Title = string.IsNullOrEmpty(workbook.Properties.Title) ? workbook._package.File == null @@ -301,32 +301,32 @@ private void GetLicenseInfo(PdfPageSettings pageSettings, ExcelWorkbook workbook //Create Layout Methods - private Transform GetLayout(PdfPageSettings pageSettings, PdfWorksheet[] pdfSheets) + private Transform GetLayout(PdfRenderSettings pageSettings, PdfWorksheet[] pdfSheets) { - var sheetSettings = new PdfPageSettings[pdfSheets.Length]; + var sheetSettings = new PdfRenderSettings[pdfSheets.Length]; for (int i = 0; i < pdfSheets.Length; i++) - sheetSettings[i] = GetPdfSettings.GetPdfSettingsForSheet(pageSettings, pdfSheets[i].Worksheet.PrinterSettings); + sheetSettings[i] = GetPdfSettings.GetPdfSettingsForSheet(pageSettings, pdfSheets[i].Worksheet.PrinterSettings, pdfSheets[i].Worksheet.PdfExportOverrides); var Layout = PdfLayout.GetLayout(sheetSettings, _dictionaries, pdfSheets); return Layout; } - private Transform GetLayout(PdfPageSettings pageSettings, PdfWorksheet pdfSheet) + private Transform GetLayout(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet) { PdfWorksheet[] pdfSheets = new PdfWorksheet[1] { pdfSheet }; - var sheetSettings = new PdfPageSettings[1] { pageSettings }; + var sheetSettings = new PdfRenderSettings[1] { pageSettings }; var Layout = PdfLayout.GetLayout(sheetSettings, _dictionaries, pdfSheets); return Layout; } // Build subsets ONCE for the whole document, after all sheets have been collected. // Replaces the old per-sheet pass-2 loop over _dictionaries.Fonts. - internal void BuildSubsets(PdfPageSettings pageSettings) + internal void BuildSubsets(PdfRenderSettings pageSettings) { _dictionaries.BuildSubsets(pageSettings); } // Pass 3: shape one sheet using the already-built providers. Call after BuildSubsets. - internal void ShapeTextInPdfWorksheet(PdfPageSettings pageSettings, PdfWorksheet pdfSheet) + internal void ShapeTextInPdfWorksheet(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet) { IterateCells(pdfSheet, cell => PdfTextShaper.ShapeText(pageSettings, _dictionaries, cell)); @@ -360,7 +360,7 @@ private void IterateCells(PdfWorksheet pdfSheet, System.Action action) } //Collect Text Methods - private PdfWorksheet[] GetPdfWorksheets(PdfPageSettings pageSettings, ExcelWorksheet[] worksheets) + private PdfWorksheet[] GetPdfWorksheets(PdfRenderSettings pageSettings, ExcelWorksheet[] worksheets) { PdfWorksheet[] pdfSheets = new PdfWorksheet[worksheets.Length]; for (int i = 0; i < pdfSheets.Length; i++) @@ -370,7 +370,7 @@ private PdfWorksheet[] GetPdfWorksheets(PdfPageSettings pageSettings, ExcelWorks return pdfSheets; } - internal PdfWorksheet GetPdfWorksheet(PdfPageSettings pageSettings, ExcelWorksheet worksheet) + internal PdfWorksheet GetPdfWorksheet(PdfRenderSettings pageSettings, ExcelWorksheet worksheet) { PdfWorksheet pdfSheet = new PdfWorksheet(); pdfSheet.Ranges = new List(); @@ -387,7 +387,7 @@ internal PdfWorksheet GetPdfWorksheet(PdfPageSettings pageSettings, ExcelWorkshe return pdfSheet; } - private PdfWorksheet GetPdfWorksheet(PdfPageSettings pageSettings, ExcelRangeBase excelRange) + private PdfWorksheet GetPdfWorksheet(PdfRenderSettings pageSettings, ExcelRangeBase excelRange) { PdfWorksheet pdfSheet = new PdfWorksheet(); pdfSheet.Ranges = new List(); @@ -404,7 +404,7 @@ private PdfWorksheet GetPdfWorksheet(PdfPageSettings pageSettings, ExcelRangeBas return pdfSheet; } - private PdfWorksheet[] GetPdfWorksheets(PdfPageSettings pageSettings, ExcelRangeBase[] ranges) + private PdfWorksheet[] GetPdfWorksheets(PdfRenderSettings pageSettings, ExcelRangeBase[] ranges) { // Group ranges by worksheet, preserving input order. var sheetOrder = new List(); @@ -430,7 +430,7 @@ private PdfWorksheet[] GetPdfWorksheets(PdfPageSettings pageSettings, ExcelRange return pdfSheets; } - private PdfWorksheet GetPdfWorksheet(PdfPageSettings pageSettings, ExcelWorksheet worksheet, List ranges) + private PdfWorksheet GetPdfWorksheet(PdfRenderSettings pageSettings, ExcelWorksheet worksheet, List ranges) { PdfWorksheet pdfSheet = new PdfWorksheet(); pdfSheet.Worksheet = worksheet; @@ -484,7 +484,7 @@ private List GetRanges(ExcelWorksheet worksheet) return ranges; } - private void GetMaps(PdfPageSettings pageSettings, PdfWorksheet pdfSheet, List ranges) + private void GetMaps(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet, List ranges) { for (int i = 0; i < ranges.Count; i++) { @@ -492,7 +492,7 @@ private void GetMaps(PdfPageSettings pageSettings, PdfWorksheet pdfSheet, List

0) { - var cnPageSettings = new PdfPageSettings(pdfSheet.Worksheet.Workbook.RenderContext.FontEngine); + var cnPageSettings = new PdfRenderSettings(pdfSheet.Worksheet.Workbook.RenderContext.FontEngine); cnPageSettings.CommentsAndNotes = CommentsAndNotes.None; cnPageSettings.ShowHeadings = false; pdfSheet.CommentsAndNotesSheet = PdfCommentsAndNotes.CreateCommentAndNotesPages(pdfSheet.CommentsAndNotesCollections, pdfSheet.Worksheet); diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfGridlinesLayout.cs b/src/EPPlus/Export/PdfExport/Layout/PdfGridlinesLayout.cs index 81e9d96a5..43e2fa13c 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfGridlinesLayout.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfGridlinesLayout.cs @@ -38,7 +38,7 @@ internal static class PdfGridlinesLayout /// that are not blocked by a cell border or a merged cell spanning the gap. /// 5. Add the four outer-frame lines to BorderLines. ///

- public static void AddGridLines(PdfPageSettings pageSettings, Page page, PdfPageLayout pageLayout, bool borderOnly = false) + public static void AddGridLines(PdfRenderSettings pageSettings, Page page, PdfPageLayout pageLayout, bool borderOnly = false) { int rowCount = page.ToRow - page.FromRow + 1; int colCount = page.ToColumn - page.FromColumn + 1; diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfHeaderFooterLayout.cs b/src/EPPlus/Export/PdfExport/Layout/PdfHeaderFooterLayout.cs index b2214a133..c871d4480 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfHeaderFooterLayout.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfHeaderFooterLayout.cs @@ -38,7 +38,7 @@ internal static Pages GetHeaderFooter(PdfRange range, Pages pdfPages, PdfWorkshe return pdfPages; } - internal static void AddHeaderFooter(PdfPageLayout pageLayout, Page page, PdfPageSettings pageSettings, PdfDictionaries dictionaries, int displayedPageNumber, int physicalPageIndex, int totalPages) + internal static void AddHeaderFooter(PdfPageLayout pageLayout, Page page, PdfRenderSettings pageSettings, PdfDictionaries dictionaries, int displayedPageNumber, int physicalPageIndex, int totalPages) { if (page.HeaderFooters == null) return; pageLayout.ScaleHeaderFooterWithDocument = page.HeaderFooters.ScaleWithDocument; @@ -198,20 +198,20 @@ internal static void AddHeaderFooter(PdfPageLayout pageLayout, Page page, PdfPag } } - private static void SubstitutePageNumbers(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter hf, int pageNumber, int totalPages) + private static void SubstitutePageNumbers(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter hf, int pageNumber, int totalPages) { if (hf == null) return; ApplyPageNumbers(hf, pageNumber, totalPages); PdfTextShaper.ShapeText(pageSettings, dictionaries, hf.Content); } - internal static bool ShapeHeaderFooterText(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter hf, int pageNumber, int totalPages) + internal static bool ShapeHeaderFooterText(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter hf, int pageNumber, int totalPages) { SubstitutePageNumbers(pageSettings, dictionaries, hf, pageNumber, totalPages); return hf.Content != null && hf.Content.TextLines != null && hf.Content.TextLines.Count > 0; } - internal static Vector2 HeaderFooterPivot(HeaderFooterSection section, HeaderFooterAlignment align, PdfPageSettings ps, bool alignWithMargins) + internal static Vector2 HeaderFooterPivot(HeaderFooterSection section, HeaderFooterAlignment align, PdfRenderSettings ps, bool alignWithMargins) { var (left, width) = HeaderFooterBox(ps, alignWithMargins); double x = align == HeaderFooterAlignment.Left ? left : (align == HeaderFooterAlignment.Right ? left + width : left + width / 2d); @@ -219,7 +219,7 @@ internal static Vector2 HeaderFooterPivot(HeaderFooterSection section, HeaderFoo return new Vector2(x, y); } - internal static (double Left, double Width) HeaderFooterBox(PdfPageSettings ps, bool alignWithMargins) + internal static (double Left, double Width) HeaderFooterBox(PdfRenderSettings ps, bool alignWithMargins) { if (alignWithMargins) { @@ -229,7 +229,7 @@ internal static (double Left, double Width) HeaderFooterBox(PdfPageSettings ps, return (d, ps.PageSize.WidthPu - 2d * d); } - internal static void AddHeaderFooterTextPart(PdfPageLayout pageLayout, PdfDictionaries dictionaries, PdfCellContentLayout text, HeaderFooterSection section, HeaderFooterAlignment align, PdfPageSettings ps, bool alignWithMargins) + internal static void AddHeaderFooterTextPart(PdfPageLayout pageLayout, PdfDictionaries dictionaries, PdfCellContentLayout text, HeaderFooterSection section, HeaderFooterAlignment align, PdfRenderSettings ps, bool alignWithMargins) { text.IsHeaderFooter = true; text.GidsAndCharMap(dictionaries); @@ -251,7 +251,7 @@ internal static void ApplyPageNumbers(PdfHeaderFooter hf, int pageNumber, int to } } - internal static PdfHeaderFooter ShapeHeaderFooterRun(PdfPageSettings pageSettings, PdfDictionaries dictionaries, List frags, HeaderFooterSection section, out double width, out double ascent, out double descent) + internal static PdfHeaderFooter ShapeHeaderFooterRun(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, List frags, HeaderFooterSection section, out double width, out double ascent, out double descent) { width = 0d; ascent = 0d; descent = 0d; if (frags == null || frags.Count == 0) @@ -274,7 +274,7 @@ internal static PdfHeaderFooter ShapeHeaderFooterRun(PdfPageSettings pageSetting return sub; } - internal static PdfCellContentLayout PlaceHeaderFooterRun(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter run, double x, double baselineY) + internal static PdfCellContentLayout PlaceHeaderFooterRun(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfHeaderFooter run, double x, double baselineY) { var layout = new PdfCellContentLayout(pageSettings, dictionaries, run, x, baselineY, 0, 0); layout.IsHeaderFooter = true; diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfHeadingLayout.cs b/src/EPPlus/Export/PdfExport/Layout/PdfHeadingLayout.cs index bc6f1b2fe..ce7d5c8ad 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfHeadingLayout.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfHeadingLayout.cs @@ -25,7 +25,7 @@ namespace OfficeOpenXml.Export.PdfExport.Layout { internal static class PdfHeadingLayout { - internal static Pages PrecomputePrintTitleCells(PdfPageSettings pageSettings, PdfWorksheet pdfSheet, PdfRange range, Pages pdfPages) + internal static Pages PrecomputePrintTitleCells(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet, PdfRange range, Pages pdfPages) { for (int i = 0; i < pdfPages.Page.Length; i++) { @@ -34,7 +34,7 @@ internal static Pages PrecomputePrintTitleCells(PdfPageSettings pageSettings, Pd return pdfPages; } - private static Page PrecomputePagePrintTitleCells(PdfPageSettings pageSettings, PdfWorksheet pdfSheet, PdfRange range, Page page) + private static Page PrecomputePagePrintTitleCells(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet, PdfRange range, Page page) { page.PrintTitleCells = new List(); page.PrintTitleBorders = new List(); @@ -176,7 +176,7 @@ private static Page PrecomputePagePrintTitleCells(PdfPageSettings pageSettings, return page; } - internal static void AddPrintTitleCells(PdfPageSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout) + internal static void AddPrintTitleCells(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout) { if (page.PrintTitleCells == null) return; pageLayout.PrintTitleGridLines = page.PrintTitleGridLines ?? new List(); @@ -220,7 +220,7 @@ internal static void AddPrintTitleCells(PdfPageSettings pageSettings, PdfDiction } } - internal static void AddHeadingCell(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfPageLayout pageLayout, PdfCellStyle headingStyle, string label, double x, double y, double width, double height, string fontName, float fontSize, string namePrefix) + internal static void AddHeadingCell(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfPageLayout pageLayout, PdfCellStyle headingStyle, string label, double x, double y, double width, double height, string fontName, float fontSize, string namePrefix) { if (width == 0d || height == 0d) return; var fill = new PdfCellLayout(x, y, width, height); @@ -245,7 +245,7 @@ internal static void AddHeadingCell(PdfPageSettings pageSettings, PdfDictionarie } } - internal static void AddHeadingCells(PdfPageSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout, double contentStartX, double contentStartY, double headingWidth, double headingHeight, string fontName, float fontSize, ExcelFill fill) + internal static void AddHeadingCells(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout, double contentStartX, double contentStartY, double headingWidth, double headingHeight, string fontName, float fontSize, ExcelFill fill) { var headingStyle = new PdfCellStyle(); headingStyle.xfFill = fill; @@ -287,7 +287,7 @@ internal static void AddHeadingCells(PdfPageSettings pageSettings, PdfDictionari } } - internal static void AddPrintTitleHeadings(PdfPageSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout, string fontName, float fontSize, ExcelFill fill) + internal static void AddPrintTitleHeadings(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout, string fontName, float fontSize, ExcelFill fill) { if (page.PrintTitleHeadings == null || page.PrintTitleHeadings.Count == 0) return; var headingStyle = new PdfCellStyle(); @@ -310,7 +310,7 @@ private static void AddHeadingCellBorder(PdfPageLayout pageLayout, double x, dou pageLayout.BorderLines.Add(new GridLine(right, y, right, bottom)); } - private static PdfCell CreateHeadingPdfCell(PdfPageSettings pageSettings, PdfDictionaries dictionaries, string text, ExcelHorizontalAlignment hAlign, double width, double height, string fontName, float fontSize) + private static PdfCell CreateHeadingPdfCell(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, string text, ExcelHorizontalAlignment hAlign, double width, double height, string fontName, float fontSize) { var cell = new PdfCell(); cell.ColumnWidth = width; diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfImagePlacement.cs b/src/EPPlus/Export/PdfExport/Layout/PdfImagePlacement.cs index 10ba4abec..5989375ab 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfImagePlacement.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfImagePlacement.cs @@ -107,7 +107,7 @@ private static double CellImageOffsetY(PdfCellAlignmentData align, double slack) } } - internal static Pages PrecomputeImages(PdfPageSettings pageSettings, PdfRange range, Pages pdfPages, List drawings, double zeroCharWidth) + internal static Pages PrecomputeImages(PdfRenderSettings pageSettings, PdfRange range, Pages pdfPages, List drawings, double zeroCharWidth) { if (drawings == null || drawings.Count == 0) { @@ -148,7 +148,7 @@ internal static Pages PrecomputeImages(PdfPageSettings pageSettings, PdfRange ra private static double RowEdge(double[] rowPrefix, int localRow) => rowPrefix[Math.Max(0, Math.Min(localRow, rowPrefix.Length - 1))]; - private static Page PrecomputePageImages(PdfPageSettings pageSettings, PdfRange range, Page page, List drawings, double[] colPrefix, double[] rowPrefix, double rangeOriginX, double rangeOriginY) + private static Page PrecomputePageImages(PdfRenderSettings pageSettings, PdfRange range, Page page, List drawings, double[] colPrefix, double[] rowPrefix, double rangeOriginX, double rangeOriginY) { page.Images = new List(); int fromCol = range.Range._fromCol; diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfLayout.cs b/src/EPPlus/Export/PdfExport/Layout/PdfLayout.cs index 199a89c2a..9cd412260 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfLayout.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfLayout.cs @@ -31,7 +31,7 @@ internal static class PdfLayout { internal const double rowHeadingWith1CharWidth = 18d; - public static Transform GetLayout(PdfPageSettings[] sheetSettings, PdfDictionaries dictionaries, PdfWorksheet[] pdfSheets) + public static Transform GetLayout(PdfRenderSettings[] sheetSettings, PdfDictionaries dictionaries, PdfWorksheet[] pdfSheets) { var PagesCollection = GetPages(sheetSettings, pdfSheets); var Catalog = GetCatalog(sheetSettings[0].FirstPageNumber, dictionaries, PagesCollection); @@ -130,7 +130,7 @@ internal static Transform GetCatalog(int firstPageNumber, PdfDictionaries dictio return Catalog; } - private static PdfPageLayout CreatePageLayout(Pages sheet, Page page, PdfPageSettings pageSettings, PdfDictionaries dictionaries, out double contentStartX, out double contentStartY) + private static PdfPageLayout CreatePageLayout(Pages sheet, Page page, PdfRenderSettings pageSettings, PdfDictionaries dictionaries, out double contentStartX, out double contentStartY) { var pageLayout = new PdfPageLayout(0d, 0d, 0d, 0d); pageLayout.Settings = pageSettings; @@ -172,7 +172,7 @@ private static PdfPageLayout CreatePageLayout(Pages sheet, Page page, PdfPageSet return pageLayout; } - private static void CreateCellLayouts(PdfPageLayout pageLayout, Page page, PdfPageSettings pageSettings, PdfDictionaries dictionaries, double contentStartX, double contentStartY, bool isDraft, bool isBlackWhite) + private static void CreateCellLayouts(PdfPageLayout pageLayout, Page page, PdfRenderSettings pageSettings, PdfDictionaries dictionaries, double contentStartX, double contentStartY, bool isDraft, bool isBlackWhite) { var drawnMergedCells = new HashSet(); double y = contentStartY; @@ -217,7 +217,7 @@ private static void CreateCellLayouts(PdfPageLayout pageLayout, Page page, PdfPa private static bool CellHasPicture(PdfCell cell) => cell?.CellPictureBytes != null; - private static void CreateMergedCellLayout(PdfPageLayout pageLayout, PdfCell map, MergedCellDrawInfo info, PdfPageSettings pageSettings, PdfDictionaries dictionaries, bool isDraft, bool isBlackWhite) + private static void CreateMergedCellLayout(PdfPageLayout pageLayout, PdfCell map, MergedCellDrawInfo info, PdfRenderSettings pageSettings, PdfDictionaries dictionaries, bool isDraft, bool isBlackWhite) { if (!isDraft) { @@ -262,7 +262,7 @@ private static void CreateMergedCellLayout(PdfPageLayout pageLayout, PdfCell map } } - private static void CreateCellLayout(PdfPageLayout pageLayout, Page page, PdfCell map, PdfPageSettings pageSettings, PdfDictionaries dictionaries, double x, double y, double rowHeight, int row, int col, bool isDraft, bool isBlackWhite) + private static void CreateCellLayout(PdfPageLayout pageLayout, Page page, PdfCell map, PdfRenderSettings pageSettings, PdfDictionaries dictionaries, double x, double y, double rowHeight, int row, int col, bool isDraft, bool isBlackWhite) { var effectiveWidth = GetClampedCellWidth(pageSettings, x, map.ColumnWidth); if (!isDraft) @@ -289,7 +289,7 @@ private static void CreateCellLayout(PdfPageLayout pageLayout, Page page, PdfCel } } - private static void CreateCellFillLayout(PdfPageLayout pageLayout, PdfCellStyle style, string text, double x, double y, double width, double height, string name, PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfCellAlignmentData contentAlignment) + private static void CreateCellFillLayout(PdfPageLayout pageLayout, PdfCellStyle style, string text, double x, double y, double width, double height, string name, PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfCellAlignmentData contentAlignment) { var fill = new PdfCellLayout(x, y, width, height); PdfFillResolver.SetFill(dictionaries, style, text, fill); @@ -358,7 +358,7 @@ private static void CreateCellBorderLayout(PdfPageLayout pageLayout, Page page, pageLayout.AddChild(border); } - private static void AddAdditionalContent(PdfPageLayout pageLayout, Page page, PdfPageSettings pageSettings, PdfDictionaries dictionaries) + private static void AddAdditionalContent(PdfPageLayout pageLayout, Page page, PdfRenderSettings pageSettings, PdfDictionaries dictionaries) { if (page.AddedContent == null || page.AddedContent.content?.TextLines == null || page.AddedContent.content.TextLines.Count == 0) return; var content = page.AddedContent.content; @@ -406,7 +406,7 @@ static MergedCellCorners GetCorners(ExcelAddressBase addr, int row, int col) return result; } - internal static List GetPages(PdfPageSettings[] sheetSettings, PdfWorksheet[] pdfSheets) + internal static List GetPages(PdfRenderSettings[] sheetSettings, PdfWorksheet[] pdfSheets) { List PagesCollection = new List(); for (int si = 0; si < pdfSheets.Length; si++) @@ -462,7 +462,7 @@ internal static List GetPages(PdfPageSettings[] sheetSettings, PdfWorkshe return PagesCollection; } - internal static double[] BuildColumnXPositions(PdfPageSettings pageSettings, Page page) + internal static double[] BuildColumnXPositions(PdfRenderSettings pageSettings, Page page) { int colCount = page.ToColumn - page.FromColumn + 1; var colX = new double[colCount]; @@ -491,7 +491,7 @@ private static Pages GetAdditionalContent(Pages pdfPages, PdfWorksheet pdfSheet) /// The X coordinate where the page's printed block begins. /// Currently the left content bound; will include the centering offset. ///
- internal static double GetOriginX(PdfPageSettings pageSettings, Page page) + internal static double GetOriginX(PdfRenderSettings pageSettings, Page page) { if (!pageSettings.CenterOnPageHorizontally) return pageSettings.ContentBounds.Left; var contentWidth = page.IsCommentsPage ? pageSettings.ContentBounds.Width : pageSettings.EffectiveContentWidth; @@ -502,7 +502,7 @@ internal static double GetOriginX(PdfPageSettings pageSettings, Page page) /// /// The Y coordinate where the page's printed block begins (top edge). /// - internal static double GetOriginY(PdfPageSettings pageSettings, Page page) + internal static double GetOriginY(PdfRenderSettings pageSettings, Page page) { if (!pageSettings.CenterOnPageVertically) return pageSettings.ContentBounds.Top; var contentHeight = page.IsCommentsPage ? pageSettings.ContentBounds.Height : pageSettings.EffectiveContentHeight; @@ -510,7 +510,7 @@ internal static double GetOriginY(PdfPageSettings pageSettings, Page page) return pageSettings.ContentBounds.Top - Math.Max(0d, offset); } - internal static double GetClampedCellWidth(PdfPageSettings pageSettings, double cellX, double cellWidth) + internal static double GetClampedCellWidth(PdfRenderSettings pageSettings, double cellX, double cellWidth) { double s = pageSettings.ContentScale; double pageRightNatural = pageSettings.ContentBounds.Left + (pageSettings.PageSize.WidthPu - pageSettings.ContentBounds.Left) / s; diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfMergedCellLayout.cs b/src/EPPlus/Export/PdfExport/Layout/PdfMergedCellLayout.cs index bb7183877..0f890ba5e 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfMergedCellLayout.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfMergedCellLayout.cs @@ -19,7 +19,7 @@ namespace OfficeOpenXml.Export.PdfExport.Layout { internal static class PdfMergedCellLayout { - internal static Pages PrecomputeMergedCells(PdfPageSettings pageSettings, PdfRange range, Pages pdfPages) + internal static Pages PrecomputeMergedCells(PdfRenderSettings pageSettings, PdfRange range, Pages pdfPages) { for (int i = 0; i < pdfPages.Page.Length; i++) { @@ -28,7 +28,7 @@ internal static Pages PrecomputeMergedCells(PdfPageSettings pageSettings, PdfRan return pdfPages; } - private static Page PrecomputePageMergedCells(PdfPageSettings pageSettings, PdfRange range, Page page) + private static Page PrecomputePageMergedCells(PdfRenderSettings pageSettings, PdfRange range, Page page) { page.MergedCells = new Dictionary(); var colX = PdfLayout.BuildColumnXPositions(pageSettings, page); diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfPaginator.cs b/src/EPPlus/Export/PdfExport/Layout/PdfPaginator.cs index 25ef1e142..1edda149c 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfPaginator.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfPaginator.cs @@ -31,7 +31,7 @@ public PageSegment(int from, int to) } } - internal static Pages GetNumberOfPages(PdfPageSettings pageSettings, PdfWorksheet pdfSheet, ref PdfRange range) + internal static Pages GetNumberOfPages(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet, ref PdfRange range) { var xPages = (int)Math.Max(1, Math.Ceiling(range.TotalWidth / pageSettings.EffectiveContentWidth)); var yPages = (int)Math.Max(1, Math.Ceiling(range.TotalHeight / pageSettings.EffectiveContentHeight)); @@ -115,7 +115,7 @@ internal static Pages MapPage(PdfRange range, Pages pdfPages) return pdfPages; } - private static List GetColumnSegments(PdfPageSettings pageSettings, PdfRange range, ExcelWorksheet worksheet, double addedWidth, double titleWidth, int printTitleColTo) + private static List GetColumnSegments(PdfRenderSettings pageSettings, PdfRange range, ExcelWorksheet worksheet, double addedWidth, double titleWidth, int printTitleColTo) { var segments = new List(); int segStartIdx = 0; @@ -155,7 +155,7 @@ private static List GetColumnSegments(PdfPageSettings pageSettings, return segments; } - private static List GetRowSegments(PdfPageSettings pageSettings, PdfRange range, ExcelWorksheet worksheet, double addedHeight, double titleHeight, int printTitleRowTo) + private static List GetRowSegments(PdfRenderSettings pageSettings, PdfRange range, ExcelWorksheet worksheet, double addedHeight, double titleHeight, int printTitleRowTo) { var segments = new List(); int segStartIdx = 0; @@ -188,7 +188,7 @@ private static List GetRowSegments(PdfPageSettings pageSettings, Pd return segments; } - internal static Pages AssignRangeToPages(PdfPageSettings pageSettings, PdfRange range, Pages pdfPages) + internal static Pages AssignRangeToPages(PdfRenderSettings pageSettings, PdfRange range, Pages pdfPages) { var pages = pdfPages; var worksheet = range.Range.Worksheet; @@ -242,7 +242,7 @@ internal static Pages AssignRangeToPages(PdfPageSettings pageSettings, PdfRange return pdfPages; } - internal static void ResolveFitScale(PdfPageSettings pageSettings, PdfWorksheet pdfSheet, PdfRange range) + internal static void ResolveFitScale(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet, PdfRange range) { var scaling = pageSettings.Scaling; if (scaling == null || scaling.ScalingMode != ScalingMode.FitToPages) return; diff --git a/src/EPPlus/Export/PdfExport/Layout/PdfSpillLayout.cs b/src/EPPlus/Export/PdfExport/Layout/PdfSpillLayout.cs index 0e41a607b..e3eac4d06 100644 --- a/src/EPPlus/Export/PdfExport/Layout/PdfSpillLayout.cs +++ b/src/EPPlus/Export/PdfExport/Layout/PdfSpillLayout.cs @@ -21,7 +21,7 @@ namespace OfficeOpenXml.Export.PdfExport.Layout { internal static class PdfSpillLayout { - internal static Pages PrecomputeSpillCells(PdfPageSettings pageSettings, PdfRange range, Pages pdfPages) + internal static Pages PrecomputeSpillCells(PdfRenderSettings pageSettings, PdfRange range, Pages pdfPages) { for (int i = 0; i < pdfPages.Page.Length; i++) { @@ -169,7 +169,7 @@ private static double FirstBlockedX(Page page, PdfRange range, int row, int wind return windowOriginX; } - internal static void AddSpillCells(PdfPageSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout) + internal static void AddSpillCells(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, Page page, PdfPageLayout pageLayout) { if (page.SpillCells == null) return; foreach (var s in page.SpillCells) diff --git a/src/EPPlus/Export/PdfExport/PdfExportSettings.cs b/src/EPPlus/Export/PdfExport/PdfExportSettings.cs new file mode 100644 index 000000000..d9406d648 --- /dev/null +++ b/src/EPPlus/Export/PdfExport/PdfExportSettings.cs @@ -0,0 +1,83 @@ +using EPPlus.Fonts.OpenType; +using OfficeOpenXml.Interfaces.Fonts; +using System.Collections.Generic; + +namespace OfficeOpenXml.Export.PdfExport +{ + /// + /// Document-level options for exporting a workbook, worksheets or ranges to PDF. + /// + /// These are settings that have no representation in the worksheet's print setup + /// (). Page layout — margins, orientation, paper size, + /// gridlines, headings, repeat rows/columns, print area, comments, errors and so on — is + /// not configured here; it is taken from each worksheet's + /// at export time. Where a setting below can also be varied per worksheet, the worksheet-level + /// override takes precedence over the value set here. + /// + /// + public class PdfExportSettings + { + /// + /// If true, the subsetted fonts used in the document are embedded into the PDF. + /// Embedding produces a self-contained, portable file at the cost of size. Default is true. + /// + public bool EmbeddFonts { get; set; } = true; + + /// + /// If true, EPPlus also looks for fonts in the operating system's font directories + /// (for example c:\windows\fonts). Default is true. + /// + public bool SearchSystemDirectories { get; set; } = true; + + /// + /// Additional folders to search for fonts, beyond the system directories. + /// + public List FontDirectories { get; } = new List(); + + /// + /// Font family used when a cell's font cannot be resolved. Empty means EPPlus picks a default. + /// + public string DefaultFontName { get; set; } = ""; + + /// + /// Prefix that marks a defined name as a PDF bookmark. The prefix is stripped from the + /// bookmark title. The bookmark text is taken from the target cell's content, or the defined + /// name (minus the prefix) when the cell is empty. Default is "bm_". + /// This is the document-wide default; it can be overridden per worksheet. + /// + public string BookmarkNamePrefix { get; set; } = "bm_"; + + /// + /// If true, the export adds a single hidden, read-only form field so the document presents + /// itself as an already-prepared form. This stops Adobe Acrobat / Reader from auto-detecting + /// the cell grid as fillable form fields. Default is true. + /// + public bool SuppressFormFieldDetection { get; set; } = true; + + /// + /// GSUB (glyph substitution) features requested when shaping text, e.g. ligatures and + /// contextual alternates. Applies to the whole export. Whether a feature has a visible effect + /// still depends on the font defining it. + /// + public GsubFeature GsubFeatures { get; set; } = GsubFeature.Liga | GsubFeature.Clig | GsubFeature.Calt | GsubFeature.Ccmp; + + /// + /// GPOS (glyph positioning) features requested when shaping text, e.g. kerning and mark + /// attachment. Applies to the whole export. Whether a feature has a visible effect still + /// depends on the font defining it. + /// + public GposFeature GposFeatures { get; set; } = GposFeature.Kern | GposFeature.Mark; + + /// + /// Value written to the PDF's /Author metadata. When null or empty, the workbook's + /// document properties are used. + /// + public string Author { get; set; } + + /// + /// Value written to the PDF's /Title metadata. When null or empty, the workbook's + /// document properties are used. + /// + public string Title { get; set; } + } +} \ No newline at end of file diff --git a/src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs b/src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs new file mode 100644 index 000000000..21f706388 --- /dev/null +++ b/src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OfficeOpenXml.Export.PdfExport +{ + public class PdfExportSettingsOverrides + { + /// + /// Prefix that marks a defined name as a PDF bookmark. The prefix is stripped from the + /// bookmark title. The bookmark text is taken from the target cell's content, or the defined + /// name (minus the prefix) when the cell is empty. Default is "bm_". + /// This is the document-wide default; it can be overridden per worksheet. + /// + public string BookmarkNamePrefix { get; set; } + } +} diff --git a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs index cb93622c7..32517b2fb 100644 --- a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs +++ b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs @@ -19,22 +19,30 @@ namespace OfficeOpenXml.Export.PdfExport.Settings { internal static class GetPdfSettings { - internal static PdfPageSettings GetPdfSettingsFromPrinterSettings(ExcelWorkbook workbook, ExcelPrinterSettings eps) + internal static PdfRenderSettings BuildBase(ExcelWorkbook wb, ExcelPrinterSettings eps, PdfExportSettings export) + { + var s = new PdfRenderSettings(wb.RenderContext.FontEngine); + ApplyPrinterSettings(s, eps); + ApplyExportSettings(s, export); + return s; + } + + internal static PdfRenderSettings GetPdfSettingsFromPrinterSettings(ExcelWorkbook workbook, ExcelPrinterSettings eps) { bool stampNonCommercial = ExcelPackage.License.LicenseType == EPPlusLicenseType.NonCommercialOrganization; - var settings = new PdfPageSettings(workbook.RenderContext.FontEngine); + var settings = new PdfRenderSettings(workbook.RenderContext.FontEngine); ApplyPrinterSettings(settings, eps); return settings; } - internal static PdfPageSettings GetPdfSettingsForSheet(PdfPageSettings baseSettings, ExcelPrinterSettings eps) + internal static PdfRenderSettings GetPdfSettingsForSheet(PdfRenderSettings baseSettings, ExcelPrinterSettings eps) { var s = baseSettings.CloneForSheet(); ApplyPrinterSettings(s, eps); return s; } - private static void ApplyPrinterSettings(PdfPageSettings settings, ExcelPrinterSettings eps) + private static void ApplyPrinterSettings(PdfRenderSettings settings, ExcelPrinterSettings eps) { var leftMargin = UnitConversion.ToMillimeters(eps.LeftMargin); var rightMargin = UnitConversion.ToMillimeters(eps.RightMargin); @@ -65,6 +73,30 @@ private static void ApplyPrinterSettings(PdfPageSettings settings, ExcelPrinterS settings.FirstPageNumber = eps.FirstPageNumber; } + private static void ApplyExportSettings(PdfRenderSettings s, PdfExportSettings e) + { + if (e == null) return; + s.EmbeddFonts = e.EmbeddFonts; + s.SearchSystemDirectories = e.SearchSystemDirectories; + s.FontDirectories = e.FontDirectories; + s.defaultFontName = e.DefaultFontName; + s.BookmarkNamePrefix = e.BookmarkNamePrefix; + s.SuppressFormFieldDetection = e.SuppressFormFieldDetection; + s.GsubFeatures = e.GsubFeatures; + s.GposFeatures = e.GposFeatures; + s.Author = e.Author; + s.Title = e.Title; + } + + internal static PdfRenderSettings GetPdfSettingsForSheet(PdfRenderSettings baseSettings, ExcelPrinterSettings eps, PdfExportSettingsOverrides overrides) + { + var s = baseSettings.CloneForSheet(); + ApplyPrinterSettings(s, eps); + if (overrides != null) + s.BookmarkNamePrefix = overrides.BookmarkNamePrefix ?? s.BookmarkNamePrefix; + return s; + } + private static PdfPageSize GetPageSize(ePaperSize PaperSize) { switch (PaperSize) diff --git a/src/EPPlus/Export/PdfExport/TextMapping/PdfAdditionalContent.cs b/src/EPPlus/Export/PdfExport/TextMapping/PdfAdditionalContent.cs index 083a6ae4a..bc4618cfc 100644 --- a/src/EPPlus/Export/PdfExport/TextMapping/PdfAdditionalContent.cs +++ b/src/EPPlus/Export/PdfExport/TextMapping/PdfAdditionalContent.cs @@ -27,7 +27,7 @@ internal class PdfAdditionalContent internal const float FontSize = 7f; internal PdfCellBase content; - public PdfAdditionalContent(PdfPageSettings pageSettings, PdfDictionaries dictionaries, ExcelWorksheet ws) + public PdfAdditionalContent(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, ExcelWorksheet ws) { if (string.IsNullOrEmpty(pageSettings.AdditionalContent)) { diff --git a/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterCollection.cs b/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterCollection.cs index 742d3b874..e43c539e5 100644 --- a/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterCollection.cs +++ b/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterCollection.cs @@ -28,7 +28,7 @@ internal class PdfHeaderFooterCollection public bool HasFirstPage = false; public bool HasOddEvenPages = false; - public PdfHeaderFooterCollection(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfWorksheet pdfSheet, ExcelHeaderFooter headerFooter) + public PdfHeaderFooterCollection(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfWorksheet pdfSheet, ExcelHeaderFooter headerFooter) { bool differentFirst = pdfSheet.Worksheet.HeaderFooter.differentFirst; bool differentOddEven = pdfSheet.Worksheet.HeaderFooter.differentOddEven; diff --git a/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs b/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs index 651fe8333..c6ca98967 100644 --- a/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs +++ b/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs @@ -25,7 +25,7 @@ namespace OfficeOpenXml.Export.PdfExport.TextMapping { internal static class PdfHeaderFooterTextBuilder { - internal static PdfHeaderFooter GetTextFormats(PdfPageSettings pageSettings, PdfDictionaries dictionaries, ExcelWorksheet ws, ExcelHeaderFooterTextCollection textCollection, HeaderFooterType type, HeaderFooterAlignment alignment, HeaderFooterSection section) + internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, ExcelWorksheet ws, ExcelHeaderFooterTextCollection textCollection, HeaderFooterType type, HeaderFooterAlignment alignment, HeaderFooterSection section) { if (textCollection == null || textCollection.Count <= 1) return null; var ns = ws.Workbook.Styles.GetNormalStyle(); diff --git a/src/EPPlus/Export/PdfExport/TextMapping/PdfTextFragmentBuilder.cs b/src/EPPlus/Export/PdfExport/TextMapping/PdfTextFragmentBuilder.cs index ccfb6baae..efea27697 100644 --- a/src/EPPlus/Export/PdfExport/TextMapping/PdfTextFragmentBuilder.cs +++ b/src/EPPlus/Export/PdfExport/TextMapping/PdfTextFragmentBuilder.cs @@ -24,7 +24,7 @@ namespace OfficeOpenXml.Export.PdfExport.TextMapping { internal static class PdfTextFragmentBuilder { - internal static List GetTextFragments(PdfPageSettings pageSettings, PdfDictionaries dictionaries, ExcelRangeBase cell, PdfCellStyle cellStyle) + internal static List GetTextFragments(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, ExcelRangeBase cell, PdfCellStyle cellStyle) { bool dxfBold, dxfItalic, dxfStrike, dxfUnderline; ExcelUnderLineType dxfUnderLineType; @@ -38,7 +38,7 @@ internal static List GetTextFragments(PdfPageSettings pageSettings return GetTextFragmentsFromCellStyle(pageSettings, dictionaries, cell, forcedText, dxfBold, dxfItalic, dxfStrike, dxfUnderline, dxfUnderLineType, dxfColor); } - private static List GetTextFragmentsFromRichText(PdfPageSettings pageSettings, PdfDictionaries dictionaries, ExcelRichTextCollection richText, string forcedText, bool dxfBold, bool dxfItalic, bool dxfStrike, bool dxfUnderline, ExcelUnderLineType dxfUnderLineType, System.Drawing.Color? dxfColor) + private static List GetTextFragmentsFromRichText(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, ExcelRichTextCollection richText, string forcedText, bool dxfBold, bool dxfItalic, bool dxfStrike, bool dxfUnderline, ExcelUnderLineType dxfUnderLineType, System.Drawing.Color? dxfColor) { var textFragments = new List(richText.Count); for (int i = 0; i < richText.Count; i++) @@ -63,7 +63,7 @@ private static List GetTextFragmentsFromRichText(PdfPageSettings p return textFragments; } - private static List GetTextFragmentsFromCellStyle(PdfPageSettings pageSettings, PdfDictionaries dictionaries, ExcelRangeBase cell, string forcedText, bool dxfBold, bool dxfItalic, bool dxfStrike, bool dxfUnderline, ExcelUnderLineType dxfUnderLineType, System.Drawing.Color? dxfColor) + private static List GetTextFragmentsFromCellStyle(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, ExcelRangeBase cell, string forcedText, bool dxfBold, bool dxfItalic, bool dxfStrike, bool dxfUnderline, ExcelUnderLineType dxfUnderLineType, System.Drawing.Color? dxfColor) { var font = cell.Style.Font; var textFragments = new List(1); @@ -181,7 +181,7 @@ internal static FontSubFamily ComputeFontStyle(TextFragment textFrag) return FontSubFamily.Regular; } - private static string ResolveErrorText(PdfPageSettings pageSettings, ExcelRangeBase cell) + private static string ResolveErrorText(PdfRenderSettings pageSettings, ExcelRangeBase cell) { if (!ExcelErrorValue.IsErrorValue(cell.Text)) return null; switch (pageSettings.CellErrors) diff --git a/src/EPPlus/Export/PdfExport/TextMapping/PdfTextMap.cs b/src/EPPlus/Export/PdfExport/TextMapping/PdfTextMap.cs index 6aa050af5..d5c8d0344 100644 --- a/src/EPPlus/Export/PdfExport/TextMapping/PdfTextMap.cs +++ b/src/EPPlus/Export/PdfExport/TextMapping/PdfTextMap.cs @@ -28,7 +28,7 @@ namespace OfficeOpenXml.Export.PdfExport.TextMapping { internal class PdfTextMap { - readonly PdfPageSettings _pageSettings; + readonly PdfRenderSettings _pageSettings; readonly PdfDictionaries _dictionaries; readonly PdfWorksheet _pdfSheet; readonly ExcelWorksheet _worksheet; @@ -41,7 +41,7 @@ internal class PdfTextMap PdfRange _range; - private PdfTextMap(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfWorksheet pdfSheet, PdfRange range) + private PdfTextMap(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfWorksheet pdfSheet, PdfRange range) { _pageSettings = pageSettings; _dictionaries = dictionaries; @@ -55,7 +55,7 @@ private PdfTextMap(PdfPageSettings pageSettings, PdfDictionaries dictionaries, P _pdfSheet.ToRow = _pdfSheet.ToRow < range.Range._toRow ? range.Range._toRow : _pdfSheet.ToRow; } - public static PdfCellCollection SetTextMap(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfWorksheet pdfSheet, ref PdfRange pdfRange) + public static PdfCellCollection SetTextMap(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfWorksheet pdfSheet, ref PdfRange pdfRange) { var builder = new PdfTextMap(pageSettings, dictionaries, pdfSheet, pdfRange); var map = builder.Build(); @@ -310,7 +310,7 @@ private static void LoadCellPicture(ExcelCellPicture picture, PdfCell target) ///
/// The worksheet to check. /// The number of columns to add. - internal static int AddColumnsForNonWrappedText(PdfPageSettings pageSettings, ExcelWorksheet ws, PdfWorksheet pdfSheet) + internal static int AddColumnsForNonWrappedText(PdfRenderSettings pageSettings, ExcelWorksheet ws, PdfWorksheet pdfSheet) { if (ws.Dimension == null) return 0; //If dimension is null, there are no cells to check, so return 0. int columnsToAdd = 0; diff --git a/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs b/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs index b311f641c..c0233331f 100644 --- a/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs +++ b/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs @@ -31,7 +31,7 @@ internal static class PdfTextShaper private static ConcurrentDictionary shaperCache = new ConcurrentDictionary(); private static ConcurrentDictionary layoutEngineCache = new ConcurrentDictionary(); - public static void ShapeText(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfCell cell) + public static void ShapeText(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfCell cell) { var totalTextLength = 0d; var maxLineHeight = 0d; @@ -108,7 +108,7 @@ public static void ShapeText(PdfPageSettings pageSettings, PdfDictionaries dicti cell.TotalTextLength = totalTextLength; } - public static void ShapeText(PdfPageSettings pageSettings, PdfDictionaries dictionaries, PdfCellBase cell) + public static void ShapeText(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfCellBase cell) { var totalTextLength = 0d; var maxLineHeight = 0d; @@ -193,7 +193,7 @@ public static void ShapeText(PdfPageSettings pageSettings, PdfDictionaries dicti /// outright, which is unambiguous regardless of what an empty tag list would otherwise be /// interpreted as further down. /// - internal static ShapingOptions BuildShapingOptions(PdfPageSettings pageSettings) + internal static ShapingOptions BuildShapingOptions(PdfRenderSettings pageSettings) { var options = ShapingOptions.Default; From 339535a2c4b38e1ad7632f23834ec0ae5723463d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Fri, 20 Nov 2026 16:26:18 +0100 Subject: [PATCH 4/7] progress --- src/EPPlus.Export.Pdf.Tests/PdfTests.cs | 38 +++---- .../{PdfAcroForm .cs => PdfAcroForm.cs} | 0 ...mFieldObject .cs => PdfFormFieldObject.cs} | 0 .../Settings/PdfRenderSettings.cs | 2 - src/EPPlus/ExcelRangeBase.cs | 28 +++-- src/EPPlus/ExcelWorkbook.cs | 103 ++++++++++-------- src/EPPlus/ExcelWorksheet.cs | 28 +++-- .../PdfExport/Settings/GetPdfSettings.cs | 8 -- 8 files changed, 107 insertions(+), 100 deletions(-) rename src/EPPlus.Export.Pdf/DocumentObjects/{PdfAcroForm .cs => PdfAcroForm.cs} (100%) rename src/EPPlus.Export.Pdf/DocumentObjects/{PdfFormFieldObject .cs => PdfFormFieldObject.cs} (100%) diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs index e81db9480..a8fb3c907 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs @@ -112,7 +112,7 @@ public void SaveWorksheetsAsPdfTest2() var ws1 = wb.Worksheets[1]; var ws2 = wb.Worksheets[2]; string path = _pdfPath + "WorksheetsTest2.pdf"; - wb.SaveAsPdf(path, ws0, ws1, ws2); + wb.SaveAsPdf(path, null, ws0, ws1, ws2); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } @@ -125,7 +125,7 @@ public void SaveWorksheetsAsPdfTest1() var ws0 = wb.Worksheets[0]; var ws2 = wb.Worksheets[2]; string path = _pdfPath + "WorksheetsTest1.pdf"; - wb.SaveAsPdf(path, ws0, ws2); + wb.SaveAsPdf(path, null, ws0, ws2); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } @@ -141,7 +141,7 @@ public void SaveRangesAsPdfTest1() var r3 = ws.Cells["K49:Q58"]; var r4 = ws.Cells["L142:Q147"]; string path = _pdfPath + "RangesTest1.pdf"; - wb.SaveAsPdf(path, r1, r2, r3, r4); + wb.SaveAsPdf(path, null, r1, r2, r3, r4); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } @@ -173,7 +173,7 @@ public async Task SaveWorksheetsAsPdfAsyncTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, ws0, ws2); + await wb.SaveAsPdfAsync(tempFile, null, ws0, ws2); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -192,7 +192,7 @@ public async Task SaveWorksheetsAsPdfAsyncWithTokenTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, CancellationToken.None, ws0, ws2); + await wb.SaveAsPdfAsync(tempFile, CancellationToken.None, null, ws0, ws2); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -212,7 +212,7 @@ public async Task SaveRangesAsPdfAsyncTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, r1, r2); + await wb.SaveAsPdfAsync(tempFile, null, r1, r2); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -232,7 +232,7 @@ public async Task SaveRangesAsPdfAsyncWithTokenTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, CancellationToken.None, r1, r2); + await wb.SaveAsPdfAsync(tempFile, CancellationToken.None, null, r1, r2); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -283,7 +283,7 @@ public void SaveWorksheetsAsPdfToStreamTest() var ws0 = wb.Worksheets[0]; var ws2 = wb.Worksheets[2]; using var ms = new MemoryStream(); - wb.SaveAsPdf(ms, ws0, ws2); + wb.SaveAsPdf(ms, null, ws0, ws2); AssertLooksLikePdf(ms.ToArray()); } @@ -296,7 +296,7 @@ public void SaveRangesAsPdfToStreamTest() var r1 = ws.Cells["D3:F6"]; var r2 = ws.Cells["B36:F39"]; using var ms = new MemoryStream(); - wb.SaveAsPdf(ms, r1, r2); + wb.SaveAsPdf(ms, null, r1, r2); AssertLooksLikePdf(ms.ToArray()); } @@ -435,7 +435,7 @@ public async Task SaveWorksheetAsPdfAsyncToStreamWithCanceledTokenThrowsTest() using var ms = new MemoryStream(); using var cts = new CancellationTokenSource(); cts.Cancel(); - await Assert.ThrowsExactlyAsync(() => ws.SaveAsPdfAsync(ms, cts.Token)); + await Assert.ThrowsExactlyAsync(() => ws.SaveAsPdfAsync(ms, null, cts.Token)); } [TestMethod] @@ -505,7 +505,7 @@ public async Task SaveRangeAsPdfAsyncToStreamWithCanceledTokenThrowsTest() using var ms = new MemoryStream(); using var cts = new CancellationTokenSource(); cts.Cancel(); - await Assert.ThrowsAsync(() => range.SaveAsPdfAsync(ms, cts.Token)); + await Assert.ThrowsAsync(() => range.SaveAsPdfAsync(ms, null, cts.Token)); } [TestMethod] @@ -691,7 +691,7 @@ public void TableDiff() var wb = p.Workbook; var ws0 = wb.Worksheets[0]; string path = _pdfPath + "TableDiff.pdf"; - wb.SaveAsPdf(path, ws0); + wb.SaveAsPdf(path, null, ws0); } [TestMethod] @@ -702,7 +702,7 @@ public void PictureOutside() var ws0 = wb.Worksheets[0]; ws0.PrinterSettings.ShowGridLines = true; string path = _pdfPath + "PictureOutside.pdf"; - wb.SaveAsPdf(path, ws0); + wb.SaveAsPdf(path, null, ws0); } [TestMethod] @@ -811,9 +811,7 @@ public void EachWorksheetUsesItsOwnOrientation() package.Workbook.Worksheets[0].PrinterSettings.Orientation = eOrientation.Portrait; package.Workbook.Worksheets[1].PrinterSettings.Orientation = eOrientation.Landscape; - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings( - package.Workbook, - package.Workbook.Worksheets[0].PrinterSettings); + var settings = GetPdfSettings.BuildBase(package.Workbook, package.Workbook.Worksheets[0].PrinterSettings, null); byte[] pdf; using (var ms = new MemoryStream()) @@ -851,9 +849,7 @@ public void EachWorksheetUsesItsOwnShowGridLines() package.Workbook.Worksheets[0].PrinterSettings.ShowGridLines = false; package.Workbook.Worksheets[1].PrinterSettings.ShowGridLines = true; - var baseSettings = GetPdfSettings.GetPdfSettingsFromPrinterSettings( - package.Workbook, - package.Workbook.Worksheets[0].PrinterSettings); + var baseSettings = GetPdfSettings.BuildBase(package.Workbook, package.Workbook.Worksheets[0].PrinterSettings, null); var s0 = GetPdfSettings.GetPdfSettingsForSheet( baseSettings, package.Workbook.Worksheets[0].PrinterSettings); @@ -878,9 +874,7 @@ public void EachWorksheetUsesItsOwnPaperSize() package.Workbook.Worksheets[0].PrinterSettings.PaperSize = ePaperSize.A4; package.Workbook.Worksheets[1].PrinterSettings.PaperSize = ePaperSize.A3; - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings( - package.Workbook, - package.Workbook.Worksheets[0].PrinterSettings); + var settings = GetPdfSettings.BuildBase(package.Workbook, package.Workbook.Worksheets[0].PrinterSettings, null); byte[] pdf; using (var ms = new MemoryStream()) diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm.cs similarity index 100% rename from src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs rename to src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm.cs diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject.cs similarity index 100% rename from src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs rename to src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject.cs diff --git a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs index 2af69932b..7e4ce034a 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs @@ -260,8 +260,6 @@ internal double ContentScale internal string AdditionalContent; - internal bool SuppressFormFieldDetection { get; set; } = true; - //DEBUG internal bool Debug = false; internal bool PrintAsText = false; diff --git a/src/EPPlus/ExcelRangeBase.cs b/src/EPPlus/ExcelRangeBase.cs index 868ea0437..652ba8f20 100644 --- a/src/EPPlus/ExcelRangeBase.cs +++ b/src/EPPlus/ExcelRangeBase.cs @@ -1145,10 +1145,11 @@ public IExcelHtmlRangeExporter CreateHtmlExporter() /// Save range to PDF. ///
/// Name of file. If the export fails, the file is deleted. - public void SaveAsPdf(string fileName) + /// Additional EPPlus specific PDF Export settings. + public void SaveAsPdf(string fileName, PdfExportSettings settings = null) { - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Worksheet.Workbook, this.Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); pdfWriter.Save(fileName); } @@ -1156,15 +1157,16 @@ public void SaveAsPdf(string fileName) /// Save range to PDF asynchronously. ///
/// Name of file. If the export fails or is cancelled, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Worksheet.Workbook, this.Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } @@ -1172,10 +1174,11 @@ public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellation /// Save range to PDF, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. - public void SaveAsPdf(Stream stream) + /// Additional EPPlus specific PDF Export settings. + public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) { - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Worksheet.Workbook, this.Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); pdfWriter.Save(stream); } @@ -1183,15 +1186,16 @@ public void SaveAsPdf(Stream stream) /// Save range to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Worksheet.Workbook, this.Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); } diff --git a/src/EPPlus/ExcelWorkbook.cs b/src/EPPlus/ExcelWorkbook.cs index b3c26162a..ea7b0ba95 100644 --- a/src/EPPlus/ExcelWorkbook.cs +++ b/src/EPPlus/ExcelWorkbook.cs @@ -738,10 +738,11 @@ public IExcelHtmlRangeExporter CreateHtmlExporter(params ExcelRangeBase[] ranges /// Export workbook to PDF. /// /// Name of file. If the export fails, the file is deleted. - public void SaveAsPdf(string fileName) + /// Additional EPPlus specific PDF Export settings. + public void SaveAsPdf(string fileName, PdfExportSettings settings = null) { - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, Worksheets[View.ActiveTab].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); pdfWriter.Save(fileName); } @@ -749,13 +750,14 @@ public void SaveAsPdf(string fileName) /// Export selected worksheets to PDF. /// /// Name of File. If the export fails, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Worksheets to export. /// No worksheets are supplied. - public void SaveAsPdf(string fileName, params ExcelWorksheet[] worksheets) + public void SaveAsPdf(string fileName, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) { ValidatePdfWorksheets(worksheets); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, worksheets[0].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, worksheets); + var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); pdfWriter.Save(fileName); } @@ -763,13 +765,14 @@ public void SaveAsPdf(string fileName, params ExcelWorksheet[] worksheets) /// Export selected ranges to PDF. /// /// Name of file. If the export fails, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Ranges to export. /// No ranges are supplied. - public void SaveAsPdf(string fileName, params ExcelRangeBase[] ranges) + public void SaveAsPdf(string fileName, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) { ValidatePdfRanges(ranges); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, ranges[0].Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, ranges); + var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); pdfWriter.Save(fileName); } @@ -781,11 +784,11 @@ public void SaveAsPdf(string fileName, params ExcelRangeBase[] ranges) /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default, PdfExportSettings settings = null) { cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, Worksheets[View.ActiveTab].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } @@ -793,29 +796,31 @@ public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellation /// Export selected worksheets to PDF asynchronously. /// /// Name of file. If the export fails, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Worksheets to export. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(string fileName, params ExcelWorksheet[] worksheets) - => SaveAsPdfAsync(fileName, CancellationToken.None, worksheets); + public Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) + => SaveAsPdfAsync(fileName, CancellationToken.None, settings, worksheets); /// /// Export selected worksheets to PDF asynchronously. /// /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// Worksheets to export. /// A task representing the asynchronous operation. /// No worksheets are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken, params ExcelWorksheet[] worksheets) + public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) { ValidatePdfWorksheets(worksheets); cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, worksheets[0].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, worksheets); + var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } @@ -823,29 +828,31 @@ public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellation /// Export selected ranges to PDF asynchronously. /// /// Name of file. If the export fails, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Ranges to export. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(string fileName, params ExcelRangeBase[] ranges) - => SaveAsPdfAsync(fileName, CancellationToken.None, ranges); + public Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) + => SaveAsPdfAsync(fileName, CancellationToken.None, settings, ranges); /// /// Export selected ranges to PDF asynchronously. /// /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// Ranges to export. /// A task representing the asynchronous operation. /// No ranges are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken, params ExcelRangeBase[] ranges) + public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) { ValidatePdfRanges(ranges); cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, ranges[0].Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, ranges); + var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } @@ -853,10 +860,11 @@ public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellation /// Export workbook to PDF, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. - public void SaveAsPdf(Stream stream) + /// Additional EPPlus specific PDF Export settings. + public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) { - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, Worksheets[View.ActiveTab].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); pdfWriter.Save(stream); } @@ -864,13 +872,14 @@ public void SaveAsPdf(Stream stream) /// Export selected worksheets to PDF, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Worksheets to export. /// No worksheets are supplied. - public void SaveAsPdf(Stream stream, params ExcelWorksheet[] worksheets) + public void SaveAsPdf(Stream stream, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) { ValidatePdfWorksheets(worksheets); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, worksheets[0].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, worksheets); + var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); pdfWriter.Save(stream); } @@ -878,13 +887,14 @@ public void SaveAsPdf(Stream stream, params ExcelWorksheet[] worksheets) /// Export selected ranges to PDF, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Ranges to export. /// No ranges are supplied. - public void SaveAsPdf(Stream stream, params ExcelRangeBase[] ranges) + public void SaveAsPdf(Stream stream, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) { ValidatePdfRanges(ranges); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, ranges[0].Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, ranges); + var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); pdfWriter.Save(stream); } @@ -892,15 +902,16 @@ public void SaveAsPdf(Stream stream, params ExcelRangeBase[] ranges) /// Export workbook to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default, PdfExportSettings settings = null) { cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, Worksheets[View.ActiveTab].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); } @@ -908,29 +919,31 @@ public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationTo /// Export selected worksheets to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Worksheets to export. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(Stream stream, params ExcelWorksheet[] worksheets) - => SaveAsPdfAsync(stream, CancellationToken.None, worksheets); + public Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) + => SaveAsPdfAsync(stream, CancellationToken.None, settings, worksheets); /// /// Export selected worksheets to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// Worksheets to export. /// A task representing the asynchronous operation. /// No worksheets are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken, params ExcelWorksheet[] worksheets) + public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) { ValidatePdfWorksheets(worksheets); cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, worksheets[0].PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, worksheets); + var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); } @@ -938,29 +951,31 @@ public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationTo /// Export selected ranges to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Ranges to export. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(Stream stream, params ExcelRangeBase[] ranges) - => SaveAsPdfAsync(stream, CancellationToken.None, ranges); + public Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) + => SaveAsPdfAsync(stream, CancellationToken.None, settings, ranges); /// /// Export selected ranges to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// Ranges to export. /// A task representing the asynchronous operation. /// No ranges are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken, params ExcelRangeBase[] ranges) + public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) { ValidatePdfRanges(ranges); cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this, ranges[0].Worksheet.PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, ranges); + var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); } diff --git a/src/EPPlus/ExcelWorksheet.cs b/src/EPPlus/ExcelWorksheet.cs index 8a42d8993..3b900af83 100644 --- a/src/EPPlus/ExcelWorksheet.cs +++ b/src/EPPlus/ExcelWorksheet.cs @@ -3742,10 +3742,11 @@ internal bool IsDisposed /// Export worksheet to PDF. /// /// Name of file. If the export fails, the file is deleted. - public void SaveAsPdf(string fileName) + /// Additional EPPlus specific PDF Export settings. + public void SaveAsPdf(string fileName, PdfExportSettings settings = null) { - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Workbook, PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); pdfWriter.Save(fileName); } @@ -3753,15 +3754,16 @@ public void SaveAsPdf(string fileName) /// Export worksheet to PDF asynchronously. /// /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Workbook, PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } @@ -3769,10 +3771,11 @@ public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellation /// Export worksheet to PDF, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. - public void SaveAsPdf(Stream stream) + /// Additional EPPlus specific PDF Export settings. + public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) { - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Workbook, PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); pdfWriter.Save(stream); } @@ -3780,15 +3783,16 @@ public void SaveAsPdf(Stream stream) /// Export worksheet to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Additional EPPlus specific PDF Export settings. /// Token to cancel the operation. /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var settings = GetPdfSettings.GetPdfSettingsFromPrinterSettings(this.Workbook, PrinterSettings); - var pdfWriter = new EPPlusToPdfWriter(settings, this); + var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); } diff --git a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs index 32517b2fb..cf8c248a9 100644 --- a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs +++ b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs @@ -27,14 +27,6 @@ internal static PdfRenderSettings BuildBase(ExcelWorkbook wb, ExcelPrinterSettin return s; } - internal static PdfRenderSettings GetPdfSettingsFromPrinterSettings(ExcelWorkbook workbook, ExcelPrinterSettings eps) - { - bool stampNonCommercial = ExcelPackage.License.LicenseType == EPPlusLicenseType.NonCommercialOrganization; - var settings = new PdfRenderSettings(workbook.RenderContext.FontEngine); - ApplyPrinterSettings(settings, eps); - return settings; - } - internal static PdfRenderSettings GetPdfSettingsForSheet(PdfRenderSettings baseSettings, ExcelPrinterSettings eps) { var s = baseSettings.CloneForSheet(); From 269a32ab733e054c222467277c1b905383af4dd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Tue, 24 Nov 2026 17:14:34 +0100 Subject: [PATCH 5/7] progress --- src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs | 6 +- src/EPPlus.Export.Pdf.Tests/PdfTests.cs | 40 +++-- .../DocumentObjects/Fonts/PdfCIDFont.cs | 101 ++++------- .../DocumentObjects/Fonts/PdfCidSet.cs | 24 +-- .../DocumentObjects/Fonts/PdfFont.cs | 42 +---- .../Fonts/PdfFontDescriptor.cs | 23 +-- .../DocumentObjects/Fonts/PdfFontStream.cs | 19 +-- .../DocumentObjects/Fonts/PdfFontWidths.cs | 9 +- .../DocumentObjects/Fonts/PdfToUnicodeCMap.cs | 68 +++++--- .../DocumentObjects/Fonts/PdfType0FontDict.cs | 20 +-- .../PdfExponentialInterpolationFunction.cs | 17 +- .../PdfPostScriptCalculatorFunction.cs | 34 ++-- .../Functions/PdfStichingFunction.cs | 18 +- .../Patterns/PdfShadingPattern.cs | 19 +-- .../Patterns/PdfTilingPattern.cs | 39 +---- .../DocumentObjects/PdfContentStream.cs | 15 +- .../DocumentObjects/PdfCrossRefTable.cs | 42 +++-- .../DocumentObjects/PdfImageXObject.cs | 25 +-- .../DocumentObjects/PdfInfoObject.cs | 41 ++--- .../PdfLinkAnnotationObject.cs | 11 +- .../DocumentObjects/PdfPage.cs | 45 +---- .../DocumentObjects/PdfPages.cs | 12 +- .../DocumentObjects/PdfStreamObject.cs | 26 +++ .../Shadings/PdfAxialShading.cs | 32 +--- .../Shadings/PdfFunctionBasedShading.cs | 6 +- .../Shadings/PdfMeshShading.cs | 34 +++- .../Shadings/PdfRadialShading.cs | 27 +-- .../DocumentObjects/Shadings/PdfShading.cs | 24 +-- src/EPPlus.Export.Pdf/Enums/EPPlusEnums.cs | 12 +- src/EPPlus.Export.Pdf/ExcelPdf.cs | 8 +- ...fDataBarLayout .cs => PdfDataBarLayout.cs} | 0 .../{PdfIconLayout .cs => PdfIconLayout.cs} | 0 ...fImageResource .cs => PdfImageResource.cs} | 0 .../Settings/PdfPageSizes/PdfMargins.cs | 2 +- .../Settings/PdfPageSizes/PdfPageSize.cs | 2 +- .../Settings/PdfPageSizes/PdfScaling.cs | 4 +- src/EPPlus/ExcelRangeBase.cs | 46 +++-- src/EPPlus/ExcelWorkbook.cs | 161 ++++++++++-------- src/EPPlus/ExcelWorksheet.cs | 48 ++++-- .../Export/PdfExport/EPPlusToPdfWriter.cs | 5 +- .../Export/PdfExport/PdfExportSettings.cs | 49 ++---- .../PdfExport/PdfExportSettingsOverrides.cs | 19 --- .../PdfExportSettingsWorksheetOverrides.cs | 27 +++ .../PdfExport/Settings/GetPdfSettings.cs | 14 +- 44 files changed, 537 insertions(+), 679 deletions(-) create mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs rename src/EPPlus.Export.Pdf/Layout/{PdfDataBarLayout .cs => PdfDataBarLayout.cs} (100%) rename src/EPPlus.Export.Pdf/Layout/{PdfIconLayout .cs => PdfIconLayout.cs} (100%) rename src/EPPlus.Export.Pdf/Resources/{PdfImageResource .cs => PdfImageResource.cs} (100%) delete mode 100644 src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs create mode 100644 src/EPPlus/Export/PdfExport/PdfExportSettingsWorksheetOverrides.cs diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs b/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs index 4b9e9a96b..bfab13189 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTestBase.cs @@ -54,7 +54,7 @@ protected void SaveAsPdf(byte[] pdfBytes, string pdfFileName) /// (GetPdfSettings.GetPdfSettingsFromPrinterSettings) with no way to override it. /// Drives PdfCatalog directly: the same internal entry point SaveAsPdf itself calls into. /// - protected void SaveAsPdf(ExcelWorksheet sheet, string pdfFileName, PdfRenderSettings settings) + internal void SaveAsPdf(ExcelWorksheet sheet, string pdfFileName, PdfRenderSettings settings) { if (!pdfFileName.ToLower().EndsWith(".pdf")) { @@ -72,7 +72,7 @@ protected void SaveAsPdf(ExcelWorksheet sheet, string pdfFileName, PdfRenderSett /// Workbook-level counterpart to . /// See that overload's remarks for why this bypasses ExcelWorkbook.SaveAsPdf. /// - protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings settings) + internal void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings settings) { if (!pdfFileName.ToLower().EndsWith(".pdf")) { @@ -86,7 +86,7 @@ protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings /// Range-collection counterpart to . /// See that overload's remarks for why this bypasses ExcelRangeBase/ExcelWorkbook.SaveAsPdf. /// - protected void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings settings, params ExcelRangeBase[] ranges) + internal void SaveAsPdf(ExcelWorkbook wb, string pdfFileName, PdfRenderSettings settings, params ExcelRangeBase[] ranges) { string path = GetPdfFilePath(pdfFileName); if (ranges.Count() > 1) diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs index a8fb3c907..1cf8b3c0c 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs @@ -112,7 +112,7 @@ public void SaveWorksheetsAsPdfTest2() var ws1 = wb.Worksheets[1]; var ws2 = wb.Worksheets[2]; string path = _pdfPath + "WorksheetsTest2.pdf"; - wb.SaveAsPdf(path, null, ws0, ws1, ws2); + wb.SaveAsPdf(path, new[] { ws0, ws1, ws2 }); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } @@ -125,7 +125,7 @@ public void SaveWorksheetsAsPdfTest1() var ws0 = wb.Worksheets[0]; var ws2 = wb.Worksheets[2]; string path = _pdfPath + "WorksheetsTest1.pdf"; - wb.SaveAsPdf(path, null, ws0, ws2); + wb.SaveAsPdf(path, new[] { ws0, ws2 }); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } @@ -141,7 +141,7 @@ public void SaveRangesAsPdfTest1() var r3 = ws.Cells["K49:Q58"]; var r4 = ws.Cells["L142:Q147"]; string path = _pdfPath + "RangesTest1.pdf"; - wb.SaveAsPdf(path, null, r1, r2, r3, r4); + wb.SaveAsPdf(path, new[] { r1, r2, r3, r4 }); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } @@ -173,7 +173,7 @@ public async Task SaveWorksheetsAsPdfAsyncTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, null, ws0, ws2); + await wb.SaveAsPdfAsync(tempFile, new[] { ws0, ws2 }); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -192,7 +192,7 @@ public async Task SaveWorksheetsAsPdfAsyncWithTokenTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, CancellationToken.None, null, ws0, ws2); + await wb.SaveAsPdfAsync(tempFile, new[] { ws0, ws2 }, CancellationToken.None); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -212,7 +212,7 @@ public async Task SaveRangesAsPdfAsyncTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, null, r1, r2); + await wb.SaveAsPdfAsync(tempFile, new[] { r1, r2 }); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -232,7 +232,7 @@ public async Task SaveRangesAsPdfAsyncWithTokenTest() string tempFile = Path.GetTempFileName(); try { - await wb.SaveAsPdfAsync(tempFile, CancellationToken.None, null, r1, r2); + await wb.SaveAsPdfAsync(tempFile, new[] { r1, r2}, CancellationToken.None); AssertLooksLikePdf(File.ReadAllBytes(tempFile)); } finally @@ -283,7 +283,7 @@ public void SaveWorksheetsAsPdfToStreamTest() var ws0 = wb.Worksheets[0]; var ws2 = wb.Worksheets[2]; using var ms = new MemoryStream(); - wb.SaveAsPdf(ms, null, ws0, ws2); + wb.SaveAsPdf(ms, new[] { ws0, ws2 }); AssertLooksLikePdf(ms.ToArray()); } @@ -296,7 +296,7 @@ public void SaveRangesAsPdfToStreamTest() var r1 = ws.Cells["D3:F6"]; var r2 = ws.Cells["B36:F39"]; using var ms = new MemoryStream(); - wb.SaveAsPdf(ms, null, r1, r2); + wb.SaveAsPdf(ms, new[] { r1, r2 }); AssertLooksLikePdf(ms.ToArray()); } @@ -691,7 +691,7 @@ public void TableDiff() var wb = p.Workbook; var ws0 = wb.Worksheets[0]; string path = _pdfPath + "TableDiff.pdf"; - wb.SaveAsPdf(path, null, ws0); + wb.SaveAsPdf(path, new[] { ws0 }); } [TestMethod] @@ -702,7 +702,7 @@ public void PictureOutside() var ws0 = wb.Worksheets[0]; ws0.PrinterSettings.ShowGridLines = true; string path = _pdfPath + "PictureOutside.pdf"; - wb.SaveAsPdf(path, null, ws0); + wb.SaveAsPdf(path, new[] { ws0 }); } [TestMethod] @@ -1398,6 +1398,24 @@ public void PdfRotatedTextTest1() ws.PrinterSettings.ShowGridLines = true; ws.PrinterSettings.PaperSize = ePaperSize.A4; string path = _pdfPath + "PdfRotatedText1.pdf"; + PdfExportSettings pset = new PdfExportSettings(); + pset.SuppressFormFieldDetection = true; + p.Workbook.SaveAsPdf(path, pset); + } + + [TestMethod] + public void PdfBookmarkPrefixTest1() + { + using var p = OpenTemplatePackage("BookmarkPrefixTest.xlsx"); + var ws = p.Workbook.Worksheets[0]; + ws.PrinterSettings.ShowGridLines = true; + ws.PrinterSettings.PaperSize = ePaperSize.A4; + ws.PdfExportOverrides.BookmarkNamePrefix = "sheet1_"; + + var ws1 = p.Workbook.Worksheets[1]; + ws1.PrinterSettings.PaperSize = ePaperSize.A4; + ws1.PdfExportOverrides.BookmarkNamePrefix = "sheet2_"; + string path = _pdfPath + "BookmarkPrefixTest.pdf"; p.Workbook.SaveAsPdf(path); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs index 569c24ba5..1e588f94c 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs @@ -34,9 +34,9 @@ internal class PdfCIDFont : PdfObject private readonly int FontDescriptorObjectNumber; private int? DW; // Default width - private readonly List W; // Width array - private readonly int[] DW2; // Default metrics for vertical writing (2 numbers) - private readonly List W2; // Vertical writing metrics + //private readonly List W; // Width array + //private readonly int[] DW2; // Default metrics for vertical writing (2 numbers) + //private readonly List W2; // Vertical writing metrics private readonly string CIDToGIDMap; // Can be string "Identity" or stream reference private HashSet Gids; @@ -57,43 +57,31 @@ public PdfCIDFont(int objectNumber, OpenTypeFont fontData, HashSet gids, CIDToGIDMap = CIDToGDI; } - internal override string RenderDictionary() + private string BuildWidthsArray() { + var sortedGids = Gids.OrderBy(g => g).ToList(); var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Font\n" + - $" /Subtype /{Subtype.ToString()}\n" + - $" /BaseFont /{BaseFont}\n" + - $" /CIDSystemInfo << /Registry ({CIDInfoObject.Registry}) /Ordering ({CIDInfoObject.Ordering}) /Supplement {CIDInfoObject.Supplement} >>\n" + - $" /FontDescriptor {FontDescriptorObjectNumber.ToPdfStringF0()} 0 R"); - if (DW != null) - { - sb.AppendFormat($"\n /DW {DW.ToPdfStringF0()}"); - } - if (Gids != null) - { - sb.AppendFormat($"\n /W [{BuildWidthsArray()}]"); - } - if (DW2 != null) - { - sb.AppendFormat($"\n /DW2 {DW2}"); - } - if (W2 != null) - { - var widthsStr = string.Join(" ", W2.Select(w => w.ToString()).ToArray()); - sb.AppendFormat($"\n /W2 [{widthsStr}]"); - } - if (Subtype == CIDFontSubtype.CIDFontType2) + int i = 0; + while (i < sortedGids.Count) { - if(string.IsNullOrEmpty( CIDToGIDMap )) - sb.AppendFormat($"\n /CIDToGIDMap /Identity"); - else - sb.AppendFormat($"\n /CIDToGIDMap {CIDToGIDMap}"); + ushort startGid = sortedGids[i]; + var widths = new List(); + + while (i < sortedGids.Count && sortedGids[i] == startGid + widths.Count) + { + int rawWidth = FontData.HmtxTable.GetAdvanceWidth(sortedGids[i]); + int scaledWidth = (int)Math.Round(1000.0d * rawWidth / FontData.HeadTable.UnitsPerEm); + widths.Add(scaledWidth); + i++; + } + sb.Append($"{startGid} ["); + sb.Append(string.Join(" ", widths.Select(w => w.ToPdfStringF0()).ToArray())); + sb.Append("] "); } - sb.Append(" >>"); return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) + private string Body() { var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Font\n" + @@ -107,17 +95,17 @@ internal override void RenderDictionary(BinaryWriter bw) } if (Gids != null) { - sb.AppendFormat($"\n /W [ {BuildWidthsArray()} ]"); - } - if (DW2 != null) - { - sb.AppendFormat($"\n /DW2 {DW2}"); - } - if (W2 != null) - { - var widthsStr = string.Join(" ", W2.Select(w => w.ToString()).ToArray()); - sb.AppendFormat($"\n /W2 [ {widthsStr} ]"); + sb.AppendFormat($"\n /W [{BuildWidthsArray()}]"); } + //if (DW2 != null) + //{ + // sb.AppendFormat($"\n /DW2 {DW2}"); + //} + //if (W2 != null) + //{ + // var widthsStr = string.Join(" ", W2.Select(w => w.ToString()).ToArray()); + // sb.AppendFormat($"\n /W2 [{widthsStr}]"); + //} if (Subtype == CIDFontSubtype.CIDFontType2) { if (string.IsNullOrEmpty(CIDToGIDMap)) @@ -126,31 +114,10 @@ internal override void RenderDictionary(BinaryWriter bw) sb.AppendFormat($"\n /CIDToGIDMap {CIDToGIDMap}"); } sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - } - - private string BuildWidthsArray() - { - var sortedGids = Gids.OrderBy(g => g).ToList(); - var sb = new StringBuilder(); - int i = 0; - while (i < sortedGids.Count) - { - ushort startGid = sortedGids[i]; - var widths = new List(); - - while (i < sortedGids.Count && sortedGids[i] == startGid + widths.Count) - { - int rawWidth = FontData.HmtxTable.GetAdvanceWidth(sortedGids[i]); - int scaledWidth = (int)Math.Round(1000.0d * rawWidth / FontData.HeadTable.UnitsPerEm); - widths.Add(scaledWidth); - i++; - } - sb.Append($"{startGid} ["); - sb.Append(string.Join(" ", widths.Select(w => w.ToPdfStringF0()).ToArray())); - sb.Append("] "); - } return sb.ToString(); } + + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs index cad13a41e..fdc8e09e0 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs @@ -12,10 +12,11 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.IO; +using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Fonts { - internal class PdfCidSet : PdfObject + internal class PdfCidSet : PdfStreamObject { byte[] CidSet; @@ -24,25 +25,12 @@ public PdfCidSet(int objectNumber, byte[] cidSet , int version = 0) : base(objec CidSet = cidSet; } - internal override string RenderDictionary() - { - return $"<< /Length {CidSet.Length.ToPdfStringF0()} >>\n" + $"stream\n|BINARY DATA|\nendstream"; - } - - internal override void RenderDictionary(BinaryWriter bw) + protected override (string dictionary, byte[] bytes) BuildStream() { var body = PdfFlate.Compress(CidSet); - if (body.Length < CidSet.Length) - { - WriteAscii(bw, $"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); - bw.Write(body); - } - else - { - WriteAscii(bw, $"<< /Length {CidSet.Length.ToPdfStringF0()} >>\nstream\n"); - bw.Write(CidSet); - } - WriteAscii(bw, "\nendstream"); + return body.Length < CidSet.Length + ? ($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>", body) + : ($"<< /Length {CidSet.Length.ToPdfStringF0()} >>", CidSet); } } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs index fccd9d078..260aae3d0 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs @@ -56,7 +56,7 @@ public PdfFont(int objectNumber, string fontName = "Helvetica", PdfFontSubType s fontDescriptorObjectNumber = fontDescObjectNumner; } - internal override string RenderDictionary() + private string Body() { var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Font\n" + @@ -75,7 +75,7 @@ internal override string RenderDictionary() { sb.AppendFormat($" /FirstChar {firstChar.ToPdfStringF0()}\n"); } - if(lastChar > -1) + if (lastChar > -1) { sb.AppendFormat($" /LastChar {lastChar.ToPdfStringF0()}\n"); } @@ -91,41 +91,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Font\n" + - $" /Subtype /{subType}\n" + - $" /BaseFont /{baseFont.Replace(" ", "")}"); - if (encoding == PdfFontEncoding.None) - { - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - return; - } - else - { - sb.Append("\n"); - } - if (firstChar > -1) - { - sb.AppendFormat($" /FirstChar {firstChar.ToPdfStringF0()}\n"); - } - if (lastChar > -1) - { - sb.AppendFormat($" /LastChar {lastChar.ToPdfStringF0()}\n"); - } - if (widthObjectNumber > -1) - { - sb.AppendFormat($" /Widths {widthObjectNumber.ToPdfStringF0()} 0 R\n"); - } - if (fontDescriptorObjectNumber > -1) - { - sb.AppendFormat($" /FontDescriptor {fontDescriptorObjectNumber.ToPdfStringF0()} 0 R\n"); - } - sb.AppendFormat($" /Encoding /{encoding} >>"); - WriteAscii(bw, sb.ToString()); - return; - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs index d7a935b65..91320a557 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs @@ -64,7 +64,7 @@ public PdfFontDescriptor(int objectNumber, string fontName, int flags, Rect font FontFile2ObjectNumber = fontFile2ObjectNumber; } - internal override string RenderDictionary() + private string Body() { StringBuilder sb = new StringBuilder(); sb.AppendFormat($"<< /Type /FontDescriptor\n" + @@ -88,24 +88,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /FontDescriptor\n" + - $" /FontName /{fontName.Replace(" ", "")}\n" + - $" /Flags {flags.ToPdfStringF0()}\n" + - $" /FontBBox [{fontBBox.X.ToPdfStringF0()} {fontBBox.Y.ToPdfStringF0()} {fontBBox.Width.ToPdfStringF0()} {fontBBox.Height.ToPdfStringF0()}]\n" + - $" /Ascent {ascent.ToPdfStringF0()}\n" + - $" /Descent {descent.ToPdfStringF0()}\n" + - $" /CapHeight {capheight.ToPdfStringF0()}\n" + - $" /ItalicAngle {((int)italicAngle).ToPdfStringF0()}\n" + - $" /StemV {((int)stemV).ToPdfStringF0()}"); - if (FontFile2ObjectNumber > 0) - { - sb.AppendFormat($"\n /FontFile2 {FontFile2ObjectNumber.ToPdfStringF0()} 0 R"); - } - sb.AppendFormat(" >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs index eca8cfc8b..1e7aca2d4 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs @@ -17,7 +17,7 @@ Date Author Change namespace EPPlus.Export.Pdf.DocumentObjects.Fonts { - internal class PdfFontStream : PdfObject + internal class PdfFontStream : PdfStreamObject { private readonly OpenTypeFont FontData; @@ -26,20 +26,11 @@ public PdfFontStream(int objectNumber, OpenTypeFont fontData, int version = 0) : FontData = fontData; } - internal override string RenderDictionary() + protected override (string dictionary, byte[] bytes) BuildStream() { - var fontBytes = FontData.Serialize(); - var fontData = Encoding.ASCII.GetString(fontBytes); - return $"<< /Length {fontBytes.Length.ToPdfStringF0()} /Length1 {fontBytes.Length.ToPdfStringF0()} >>\n" + $"stream\n|BINARY DATA|\nendstream"; - } - - internal override void RenderDictionary(BinaryWriter bw) - { - var fontBytes = FontData.Serialize(); - var body = PdfFlate.Compress(fontBytes); - WriteAscii(bw, $"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} /Length1 {fontBytes.Length.ToPdfStringF0()} >>\nstream\n"); - bw.Write(body); - WriteAscii(bw, "\nendstream"); + var raw = FontData.Serialize(); + var body = PdfFlate.Compress(raw); + return ($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} /Length1 {raw.Length.ToPdfStringF0()} >>", body); } } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs index 1e515f51f..b9ee4fa26 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs @@ -26,16 +26,13 @@ public PdfFontWidths(int objectNumber, List widths, int version = 0) this.widths = widths.ToArray(); } - internal override string RenderDictionary() + private string Body() { var widthsStr = string.Join(" ", widths.Select(w => w.ToString()).ToArray()); return $" [ {widthsStr} ]"; } - internal override void RenderDictionary(BinaryWriter bw) - { - var widthsStr = string.Join(" ", widths.Select(w => w.ToString()).ToArray()); - WriteAscii(bw, $" [ {widthsStr} ]"); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs index b751bb2af..075451006 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs @@ -42,28 +42,6 @@ public PdfToUnicodeCMap(int objectNumber, Dictionary characterMa BytesPerCode = bytesPerCode; } - internal override string RenderDictionary() - { - var cmapContent = GenerateCMapContent(); - var length = Encoding.UTF8.GetByteCount(cmapContent); - var sb = new StringBuilder(); - sb.AppendLine(string.Format("<< /Length {0} >>", length.ToPdfStringF0())); - sb.AppendLine("stream"); - sb.Append(cmapContent); - sb.Append("\nendstream"); - return sb.ToString(); - } - - internal override void RenderDictionary(BinaryWriter bw) - { - var cmapContent = GenerateCMapContent(); - var cmapBytes = Encoding.ASCII.GetBytes(cmapContent); - var body = PdfFlate.Compress(cmapBytes); - WriteAscii(bw, $"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); - bw.Write(body); - WriteAscii(bw, "\nendstream"); - } - private string GenerateCMapContent() { var sb = new StringBuilder(); @@ -253,5 +231,51 @@ public CharacterMapping(int code, string unicode) Unicode = unicode; } } + + //private string Body(bool compress) + //{ + // var cmapContent = GenerateCMapContent(); + // var length = Encoding.UTF8.GetByteCount(cmapContent); + // var sb = new StringBuilder(); + // sb.AppendLine(string.Format("<< /Length {0} >>", length.ToPdfStringF0())); + // sb.AppendLine("stream"); + // sb.Append(cmapContent); + // sb.Append("\nendstream"); + // return sb.ToString(); + //} + + //internal override void RenderDictionary() + //{ + // var cmapContent = GenerateCMapContent(); + // var cmapBytes = Encoding.ASCII.GetBytes(cmapContent); + // var body = PdfFlate.Compress(cmapBytes); + // WriteAscii(bw, $"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); + // bw.Write(body); + // WriteAscii(bw, "\nendstream"); + //} + + private string Body(bool compress) + { + var cmapContent = GenerateCMapContent(); + var cmapBytes = Encoding.ASCII.GetBytes(cmapContent); + var cmapBytesCompressed = compress ? PdfFlate.Compress(cmapBytes) : null; + + var sb = new StringBuilder(); + if (compress) + { + sb.AppendFormat($"<< /Filter /FlateDecode /Length {cmapBytesCompressed.Length.ToPdfStringF0()} >>\nstream\n"); + sb.AppendFormat($"{cmapBytesCompressed}"); + } + else + { + sb.AppendFormat($"<< /Length {cmapBytes.Length.ToPdfStringF0()} \nstream>>"); + sb.Append(cmapContent); + } + sb.Append("\nendstream"); + return sb.ToString(); + } + + internal override string RenderDictionary() => Body(false); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body(true)); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs index ec6c1c9cb..9ca5ab415 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs @@ -33,7 +33,7 @@ public PdfType0FontDict(int objectNumber, string basefont, string encoding, int ToUnicodeObjectNumber = toUnicodeObjectNumber; } - internal override string RenderDictionary() + private string Body() { //var DescendantFonts = string.Join(" ", DescendantFontsObjectNumbers.Select(w => ($"{w} 0 R ").ToString()).ToArray()); var sb = new StringBuilder(); @@ -50,21 +50,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - //var DescendantFonts = string.Join(" ", DescendantFontsObjectNumbers.Select(w => ($"{w} 0 R ").ToString()).ToArray()); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Font\n" + - $" /Subtype /Type0\n" + - $" /BaseFont /{BaseFont}\n" + - $" /Encoding /{Encoding}\n" + - $" /DescendantFonts [{DescendantFontsObjectNumbers.ToPdfStringF0()} 0 R]"); - if (ToUnicodeObjectNumber > 0) - { - sb.AppendFormat($"\n /ToUnicode {ToUnicodeObjectNumber.ToPdfStringF0()} 0 R"); - } - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs index 41b2a9994..ff8842b16 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs @@ -25,7 +25,7 @@ internal class PdfExponentialInterpolationFunction : PdfFunction public PdfExponentialInterpolationFunction(int objectNumber, int version = 0) : base(objectNumber, version) { } - internal override string RenderDictionary() + private string Body() { var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); var c0Str = string.Join(" ", C0.Select(w => w.ToPdfString()).ToArray()); @@ -39,18 +39,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); - var c0Str = string.Join(" ", C0.Select(w => w.ToPdfString()).ToArray()); - var c1Str = string.Join(" ", C1.Select(w => w.ToPdfString()).ToArray()); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /FunctionType 2\n" + - $" /Domain [ {domainStr} ]\n" + - $" /C0 [ {c0Str} ]\n" + - $" /C1 [ {c1Str} ]\n" + - $" /N {N.ToPdfString()} >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs index 03b121d22..e79e857a5 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs @@ -79,19 +79,33 @@ private static void GetFocus(PdfCellGradientFillData g, out double fx, out doubl } } - internal override string RenderDictionary() - { - return "<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + - $"/Length {Encoding.ASCII.GetByteCount(_code)} >>\nstream\n{_code}\nendstream"; - } + //internal override string RenderDictionary() + //{ + // return "<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + + // $"/Length {Encoding.ASCII.GetByteCount(_code)} >>\nstream\n{_code}\nendstream"; + //} + + //internal override void RenderDictionary(BinaryWriter bw) + //{ + // var bytes = Encoding.ASCII.GetBytes(_code); + // WriteAscii(bw, "<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + + // $"/Length {bytes.Length.ToPdfStringF0()} >>\nstream\n"); + // bw.Write(bytes); + // WriteAscii(bw, "\nendstream"); + //} - internal override void RenderDictionary(BinaryWriter bw) + private string Body() { var bytes = Encoding.ASCII.GetBytes(_code); - WriteAscii(bw, "<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + - $"/Length {bytes.Length.ToPdfStringF0()} >>\nstream\n"); - bw.Write(bytes); - WriteAscii(bw, "\nendstream"); + StringBuilder sb = new StringBuilder(); + sb.AppendFormat($"<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + + $"/Length {bytes.Length.ToPdfStringF0()} >>\nstream\n"); + sb.AppendFormat($"{bytes}"); + sb.Append("\nendstream"); + return sb.ToString(); } + + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs index 694caff8d..a36926fe9 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs @@ -26,7 +26,7 @@ internal class PdfStichingFunction : PdfFunction public PdfStichingFunction(int objectNumber, int version = 0) : base(objectNumber, version) { } - internal override string RenderDictionary() + private string Body() { var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); var functionsStr = string.Join("\n", Functions.Select(w => w.RenderDictionary()).ToArray()); @@ -41,19 +41,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); - var functionsStr = string.Join("\n", Functions.Select(w => w.RenderDictionary()).ToArray()); - var boundsStr = string.Join(" ", Bounds.Select(w => w.ToPdfString()).ToArray()); - var encodeStr = string.Join(" ", Encode.Select(w => w.ToPdfString()).ToArray()); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /FunctionType 3\n" + - $" /Domain [ {domainStr} ]\n"); - sb.AppendFormat($" /Functions [ {functionsStr} ]\n"); - sb.AppendFormat($" /Bounds [ {boundsStr} ]\n" + - $" /Encode [ {encodeStr} ] >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs index f412c30cf..0756ae3a0 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs @@ -29,7 +29,7 @@ public PdfShadingPattern(int objectNumber, int shadingObjectNumber, int version this.shadingObjectNumber = shadingObjectNumber; } - internal override string RenderDictionary() + private string Body() { var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Pattern\n" + @@ -44,19 +44,8 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Pattern\n" + - $" /PatternType 2\n" + - $" /Shading {shadingObjectNumber.ToPdfStringF0()} 0 R"); - if (Matrix != null) - { - var matrixStr = string.Join(" ", Matrix.Select(w => w.ToPdfStringF4()).ToArray()); - sb.AppendFormat($"\n /Matrix [ {matrixStr} ]"); - } - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs index 296c744f1..fdbd60914 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs @@ -33,7 +33,7 @@ public PdfTilingPattern(int objectNumber, PdfPatternFill patternFill, double[] B this.YStep = YStep; } - internal override string RenderDictionary() + private string Body() { var bboxStr = string.Join(" ", BBox.Select(x => x.ToPdfString()).ToArray()); var sb = new StringBuilder(); @@ -65,39 +65,8 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var bboxStr = string.Join(" ", BBox.Select(x => x.ToPdfString()).ToArray()); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Pattern\n" + - $" /PatternType 1\n" + - $" /PaintType 1\n" + - $" /TilingType 1\n" + - $" /BBox [ {bboxStr} ]\n" + - $" /XStep {XStep.ToPdfString()}\n" + - $" /YStep {YStep.ToPdfString()}\n" + - $" /Resources << >>"); - if (Matrix != null) - { - var matrixStr = string.Join(" ", Matrix.Select(w => w.ToPdfStringF4()).ToArray()); - sb.AppendFormat($"\n /Matrix [ {matrixStr} ]"); - } - if (fill != null) - { - var streamContent = fill.CreatePatternResource(); - var body = PdfFlate.Compress(Encoding.ASCII.GetBytes(streamContent)); - sb.AppendFormat($"\n /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()}"); - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - WriteAscii(bw, "\nstream\n"); - bw.Write(body); - WriteAscii(bw, "\nendstream"); - } - else - { - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - } - } + internal override string RenderDictionary() => Body(); + + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs index aaf40af25..9c7e1d270 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs @@ -29,7 +29,7 @@ Date Author Change namespace EPPlus.Export.Pdf.DocumentObjects { - internal class PdfContentStream : PdfObject + internal class PdfContentStream : PdfStreamObject { private readonly List commands = new List(); private readonly Stack<(int index, string header)> _artifactMarks = new Stack<(int, string)>(); @@ -641,20 +641,17 @@ public void AddIconLayout(PdfIconLayout icon) EndArtifact(); } - internal override string RenderDictionary() + protected override (string dictionary, byte[] bytes) BuildStream() { var content = string.Join("\n", commands.ToArray()) + "\n"; - var bytes = Encoding.ASCII.GetBytes(content); - return $"<< /Length {bytes.Length.ToPdfStringF0()} >>\n" + $"stream\n{content}endstream"; + var body = PdfFlate.Compress(Encoding.ASCII.GetBytes(content)); + return ($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>", body); } - internal override void RenderDictionary(BinaryWriter bw) + internal override string RenderDictionary() { var content = string.Join("\n", commands.ToArray()) + "\n"; - var body = PdfFlate.Compress(Encoding.ASCII.GetBytes(content)); - WriteAscii(bw, $"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); - bw.Write(body); - WriteAscii(bw, "\nendstream"); + return $"<< /Length {Encoding.ASCII.GetByteCount(content).ToPdfStringF0()} >>\nstream\n{content}endstream"; } } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs index 271467d58..e1bff0d29 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs @@ -14,6 +14,7 @@ Date Author Change using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Reflection; using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects @@ -28,8 +29,34 @@ internal void AddPosition(long position) positions.Add(position); } - internal string WriteString(int bodyCount) + //internal string WriteString(int bodyCount) + //{ + // StringBuilder sb = new StringBuilder(); + // sb.Append("xref\n"); + // sb.AppendFormat($"0 {(bodyCount + 1).ToPdfStringF0()}\n"); + // sb.Append("0000000000 65535 f \n"); + // foreach (long pos in positions) + // { + // sb.AppendFormat(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n"); + // } + // return sb.ToString(); + //} + + //internal void Write(BinaryWriter bw, long startPosition, int bodyCount) + //{ + // StartPosition = startPosition; + // bw.Write(Encoding.ASCII.GetBytes("xref\n")); + // bw.Write(Encoding.ASCII.GetBytes($"0 {(bodyCount + 1).ToPdfStringF0()}\n")); + // bw.Write(Encoding.ASCII.GetBytes("0000000000 65535 f \n")); + // foreach (long pos in positions) + // { + // bw.Write(Encoding.ASCII.GetBytes(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n")); + // } + //} + + private string Body(long startPosition, int bodyCount) { + StartPosition = startPosition; StringBuilder sb = new StringBuilder(); sb.Append("xref\n"); sb.AppendFormat($"0 {(bodyCount + 1).ToPdfStringF0()}\n"); @@ -41,16 +68,7 @@ internal string WriteString(int bodyCount) return sb.ToString(); } - internal void Write(BinaryWriter bw, long startPosition, int bodyCount) - { - StartPosition = startPosition; - bw.Write(Encoding.ASCII.GetBytes("xref\n")); - bw.Write(Encoding.ASCII.GetBytes($"0 {(bodyCount + 1).ToPdfStringF0()}\n")); - bw.Write(Encoding.ASCII.GetBytes("0000000000 65535 f \n")); - foreach (long pos in positions) - { - bw.Write(Encoding.ASCII.GetBytes(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n")); - } - } + internal string Write(long startPosition, int bodyCount) => Body(startPosition, bodyCount); + internal void Write(BinaryWriter bw, long startPosition, int bodyCount) => bw.Write(Encoding.ASCII.GetBytes(Body(startPosition, bodyCount))); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs index 75ba824d3..10fa92c90 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs @@ -12,10 +12,11 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.IO; +using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects { - internal class PdfImageXObject : PdfObject + internal class PdfImageXObject : PdfStreamObject { private readonly byte[] _bytes; internal int Width { get; } @@ -287,16 +288,18 @@ private string DictHeader() $" /Length {_bytes.Length.ToPdfStringF0()} >>"; } - internal override string RenderDictionary() - { - return DictHeader() + $"\nstream\n<{_bytes.Length.ToPdfStringF0()} bytes of image data>\nendstream"; - } + //internal override string RenderDictionary() + //{ + // return DictHeader() + $"\nstream\n<{_bytes.Length.ToPdfStringF0()} bytes of image data>\nendstream"; + //} - internal override void RenderDictionary(BinaryWriter bw) - { - WriteAscii(bw, DictHeader() + "\nstream\n"); - bw.Write(_bytes); - WriteAscii(bw, "\nendstream"); - } + //internal override void RenderDictionary(BinaryWriter bw) + //{ + // WriteAscii(bw, DictHeader() + "\nstream\n"); + // bw.Write(_bytes); + // WriteAscii(bw, "\nendstream"); + //} + + protected override (string dictionary, byte[] bytes) BuildStream() => (DictHeader(), _bytes); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs index 077f60f8c..4a9996ffd 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs @@ -32,42 +32,25 @@ public PdfInfoObject(int objectNumber, PdfDocumentSettings documentSettings, int LicenseHolder = documentSettings.LicenseHolder; } - internal override string RenderDictionary() + private string Body() { DateTime now = DateTime.Now; TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(now); string sign = offset < TimeSpan.Zero ? "-" : "+"; offset = offset.Duration(); string pdfDate = string.Format("D:{0:yyyyMMddHHmmss}{1}{2:00}'{3:00}'", now, sign, offset.Hours, offset.Minutes); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Title ({Title})\n" + - $" /Author ({Author})\n" + - $" /Subject (EPPlus PDF Export with {LicenseType} for {LicenseHolder})\n" + - $" /Keywords (EPPlus, EPPlus Software, PDF, Export, {LicenseType}, {LicenseHolder})" + - $" /Creator (EPPlus Software {LicenseType}, {LicenseHolder})\n" + - $" /Producer (EPPlus Software PDF Exporter)\n" + - $" /CreationDate ({pdfDate})\n" + - $" /ModDate ({pdfDate})\n" + - $" /Trapped /False >>"); - return sb.ToString(); + return $"<< /Title ({Title})\n" + + $" /Author ({Author})\n" + + $" /Subject (EPPlus PDF Export with {LicenseType} for {LicenseHolder})\n" + + $" /Keywords (EPPlus, EPPlus Software, PDF, Export, {LicenseType}, {LicenseHolder})" + + $" /Creator (EPPlus Software {LicenseType}, {LicenseHolder})\n" + + $" /Producer (EPPlus Software PDF Exporter)\n" + + $" /CreationDate ({pdfDate})\n" + + $" /ModDate ({pdfDate})\n" + + $" /Trapped /False >>"; } - internal override void RenderDictionary(BinaryWriter bw) - { - DateTime now = DateTime.Now; - TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(now); - string sign = offset < TimeSpan.Zero ? "-" : "+"; - offset = offset.Duration(); - string pdfDate = string.Format("D:{0:yyyyMMddHHmmss}{1}{2:00}'{3:00}'", now, sign, offset.Hours, offset.Minutes); - WriteAscii(bw, $"<< /Title ({Title})\n" + - $" /Author ({Author})\n" + - $" /Subject (EPPlus PDF Export with {LicenseType} for {LicenseHolder})\n" + - $" /Keywords (EPPlus, EPPlus Software, PDF, Export, {LicenseType}, {LicenseHolder})" + - $" /Creator (EPPlus Software {LicenseType}, {LicenseHolder})\n" + - $" /Producer (EPPlus Software PDF Exporter)\n" + - $" /CreationDate ({pdfDate})\n" + - $" /ModDate ({pdfDate})\n" + - $" /Trapped /False >>"); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs index b672d4370..70ce9d8e2 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs @@ -50,14 +50,7 @@ private string Body() $" {action} >>"; } - internal override string RenderDictionary() - { - return Body(); - } - - internal override void RenderDictionary(BinaryWriter bw) - { - WriteAscii(bw, Body()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs index f91de9137..ee53cf488 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs @@ -38,7 +38,7 @@ public PdfPage(int objectNumber, int parentObjectNumber, List contentObject Size = size; } - internal override string RenderDictionary() + private string Body() { var fontEntries = dictionaries.Fonts.Select(f => $"/{f.Value.Label} {f.Value.fontObjectNumber.ToPdfStringF0()} 0 R").ToArray(); var fonts = string.Join(" ", fontEntries); @@ -65,44 +65,6 @@ internal override string RenderDictionary() if (hasImage) sb.AppendFormat($" /XObject << {images} >>\n"); sb.AppendFormat($" >>\n"); } - sb.AppendFormat($" /MediaBox [ 0 0 {Size.WidthPu.ToPdfString()} {Size.HeightPu.ToPdfString()} ]\n" + - $" /Contents [ {string.Join(" ", contentEntries)} ]"); - if (annotationObjectNumbers.Count > 0) - { - var annots = string.Join(" ", annotationObjectNumbers.Select(a => $"{a.ToPdfStringF0()} 0 R")); - sb.AppendFormat($"\n /Annots [ {annots} ]"); - } - sb.Append(" >>"); - return sb.ToString(); - } - - internal override void RenderDictionary(BinaryWriter bw) - { - var fontEntries = dictionaries.Fonts.Select(f => $"/{f.Value.Label} {f.Value.fontObjectNumber.ToPdfStringF0()} 0 R").ToArray(); - var fonts = string.Join(" ", fontEntries); - var patternEntries = dictionaries.Patterns.Select(p => $"/{p.Value.Label} {p.Value.objectNumber.ToPdfStringF0()} 0 R").ToArray(); - var patterns = string.Join(" ", patternEntries); - var shadingEntries = dictionaries.Shadings.Select(s => $"/{s.Value.Label} {s.Value.objectNumber.ToPdfStringF0()} 0 R").ToArray(); - var shadings = string.Join(" ", shadingEntries); - var imageEntries = dictionaries.Images.Select(im => $"/{im.Value.Label} {im.Value.objectNumber.ToPdfStringF0()} 0 R").ToArray(); - var images = string.Join(" ", imageEntries); - var contentEntries = contentObjectNumbers.Select(con => $"{con.ToPdfStringF0()} 0 R").ToArray(); - StringBuilder sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Page\n" + - $" /Parent {parentObjectNumber.ToPdfStringF0()} 0 R\n"); - bool hasFont = !string.IsNullOrEmpty(fonts); - bool hasPattern = !string.IsNullOrEmpty(patterns); - bool hasShading = !string.IsNullOrEmpty(shadings); - bool hasImage = !string.IsNullOrEmpty(images); - if (hasFont || hasPattern || hasShading) - { - sb.AppendFormat($" /Resources <<\n"); - if (hasFont ) sb.AppendFormat($" /Font << {fonts} >>\n"); - if (hasPattern) sb.AppendFormat($" /Pattern << {patterns} >>\n"); - if (hasShading) sb.AppendFormat($" /Shading << {shadings} >>\n"); - if (hasImage) sb.AppendFormat($" /XObject << {images} >>\n"); - sb.AppendFormat($" >>\n"); - } if (HasTransparency) sb.AppendFormat($" /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>\n"); sb.AppendFormat($" /MediaBox [ 0 0 {Size.WidthPu.ToPdfString()} {Size.HeightPu.ToPdfString()} ]\n" + @@ -113,7 +75,10 @@ internal override void RenderDictionary(BinaryWriter bw) sb.AppendFormat($"\n /Annots [ {annots} ]"); } sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); + return sb.ToString(); } + + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs index d19f24841..cb0a7e4fa 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs @@ -28,7 +28,7 @@ public PdfPages(int objectNumber, List pageObjectNumbers, int version = 0) this.pageObjectNumbers = pageObjectNumbers.ToList(); } - internal override string RenderDictionary() + private string Body() { var kids = string.Join(" ", pageObjectNumbers.Select(n => $"{n.ToPdfStringF0()} 0 R").ToArray()); return $"<< /Type /Pages\n" + @@ -36,13 +36,7 @@ internal override string RenderDictionary() $" /Count {pageObjectNumbers.Count.ToPdfStringF0()} >>"; } - internal override void RenderDictionary(BinaryWriter bw) - { - var kids = string.Join(" ", pageObjectNumbers.Select(n => $"{n.ToPdfStringF0()} 0 R").ToArray()); - StringBuilder sb = new StringBuilder(); - WriteAscii(bw, $"<< /Type /Pages\n" + - $" /Kids [ {kids} ]\n" + - $" /Count {pageObjectNumbers.Count.ToPdfStringF0()} >>"); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs new file mode 100644 index 000000000..dfa4e74f8 --- /dev/null +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs @@ -0,0 +1,26 @@ +using EPPlus.Export.Pdf.Helpers; +using System.IO; + +namespace EPPlus.Export.Pdf.DocumentObjects +{ + internal abstract class PdfStreamObject : PdfObject + { + protected PdfStreamObject(int objectNumber, int version = 0) : base(objectNumber, version) { } + + protected abstract (string dictionary, byte[] bytes) BuildStream(); + + internal sealed override void RenderDictionary(BinaryWriter bw) + { + var (dictionary, bytes) = BuildStream(); + WriteAscii(bw, dictionary + "\nstream\n"); + bw.Write(bytes); + WriteAscii(bw, "\nendstream"); + } + + internal override string RenderDictionary() + { + var (dictionary, bytes) = BuildStream(); + return dictionary + $"\nstream\n|{bytes.Length.ToPdfStringF0()} bytes binary data|\nendstream"; + } + } +} diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs index dbcbfee2d..cd246422d 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs @@ -66,7 +66,7 @@ public PdfAxialShading(int objectNumber, PdfCellGradientFillData GradientFillDat Extend = [true, true]; } - internal override string RenderDictionary() + private string Body() { var coordsStr = string.Join(" ", Coords.Select(w => w.ToPdfString()).ToArray()); var sb = new StringBuilder(); @@ -94,32 +94,8 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var coordsStr = string.Join(" ", Coords.Select(w => w.ToPdfString()).ToArray()); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Shading\n" + - $" /ShadingType 2\n" + - $" /ColorSpace /{ColorSpace.ToString()}\n" + - $" /Coords [ {coordsStr} ]\n"); - sb.AppendFormat($" /Function {Function.RenderDictionary()}"); - if (Domain != null) - { - var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); - sb.AppendFormat($"\n /Domain [ {domainStr} ]"); - } - //if (Matrix != null) - //{ - // var matrixStr = string.Join(" ", Matrix.Select(w => w.ToPdfString()).ToArray()); - // sb.AppendFormat($"\n /matrix [ {matrixStr} ]"); - //} - if (Extend != null) - { - var extendStr = string.Join(" ", Extend.Select(w => w.ToString().ToLower()).ToArray()); - sb.AppendFormat($"\n /Extend [ {extendStr} ]"); - } - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs index 30b05e399..db5caf1d3 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs @@ -29,7 +29,7 @@ public PdfFunctionBasedShading(int objectNumber, PdfCellGradientFillData gradien ColorSpace = DeviceColorSpace.DeviceRGB; } - private string Build() + private string Body() { var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); var sb = new StringBuilder(); @@ -41,8 +41,8 @@ private string Build() return sb.ToString(); } - internal override string RenderDictionary() => Build(); + internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Build()); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs index e36848b90..a1f38d71d 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs @@ -14,8 +14,10 @@ Date Author Change using EPPlus.Export.Pdf.Layout; using System; using System.Collections.Generic; +using System.ComponentModel.Design; using System.Drawing; using System.IO; +using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Shadings { @@ -133,14 +135,34 @@ private string DictHeader() => " /Decode [0 1 0 1 0 1 0 1 0 1]\n" + " /Length " + _mesh.Length + " >>\n"; - internal override string RenderDictionary() - => DictHeader() + "stream\n|BINARY DATA|\nendstream"; + //internal override string RenderDictionary() + // => DictHeader() + "stream\n|BINARY DATA|\nendstream"; - internal override void RenderDictionary(BinaryWriter bw) + //internal override void RenderDictionary(BinaryWriter bw) + //{ + // WriteAscii(bw, DictHeader() + "stream\n"); + // bw.Write(_mesh); + // WriteAscii(bw, "\nendstream"); + //} + + private string Body(bool debug) { - WriteAscii(bw, DictHeader() + "stream\n"); - bw.Write(_mesh); - WriteAscii(bw, "\nendstream"); + StringBuilder sb = new StringBuilder(); + sb.Append(DictHeader()); + sb.Append("stream\n"); + if (debug) + { + sb.Append("|BINARY DATA|"); + } + else + { + sb.AppendFormat($"{_mesh}"); + } + sb.Append("\nendstream"); + return sb.ToString(); } + + internal override string RenderDictionary() => Body(true); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body(false)); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs index 6760f686b..011374e9c 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs @@ -41,7 +41,7 @@ public PdfRadialShading(int objectNumber, PdfCellGradientFillData GradientFillDa Extend = [true, true]; } - internal override string RenderDictionary() + private string Body() { var coordsStr = string.Join(" ", Coords.Select(w => w.ToPdfString()).ToArray()); var functionsStr = string.Join("\n", Functions.Select(w => w.RenderDictionary()).ToArray()); @@ -65,28 +65,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var coordsStr = string.Join(" ", Coords.Select(w => w.ToPdfString()).ToArray()); - var functionsStr = string.Join("\n", Functions.Select(w => w.RenderDictionary()).ToArray()); - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Shading\n" + - $" /ShadingType 3\n" + - $" /ColorSpace /{ColorSpace.ToString()}\n" + - $" /Coords [ {coordsStr} ]\n"); - sb.AppendFormat($" /Function {functionsStr}"); - if (Domain != null) - { - var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); - sb.AppendFormat($"\n /Domain [ {domainStr} ]"); - } - if (Extend != null) - { - var extendStr = string.Join(" ", Extend.Select(w => w.ToString().ToLower()).ToArray()); - sb.AppendFormat($"\n /Extend [ {extendStr} ]"); - } - sb.Append(" >>"); - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs index ba3754247..1a6fac0cf 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs @@ -41,7 +41,7 @@ internal class PdfShading : PdfObject public PdfShading(int objectNumber, int version = 0) : base(objectNumber, version) { } - internal override string RenderDictionary() + private string Body() { var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Shading\n" + @@ -62,25 +62,7 @@ internal override string RenderDictionary() return sb.ToString(); } - internal override void RenderDictionary(BinaryWriter bw) - { - var sb = new StringBuilder(); - sb.AppendFormat($"<< /Type /Shading\n" + - $" /ShadingType 0\n" + - $" /ColorSpace {ColorSpace.ToString()}"); - if (Background != null) - { - //add background - } - if (BBox != null) - { - //add bbox - } - if (AntiAlias != null) - { - sb.AppendFormat($"\n /AntiAlias {AntiAlias.ToString()}"); - } - WriteAscii(bw, sb.ToString()); - } + internal override string RenderDictionary() => Body(); + internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } diff --git a/src/EPPlus.Export.Pdf/Enums/EPPlusEnums.cs b/src/EPPlus.Export.Pdf/Enums/EPPlusEnums.cs index 16fd7987a..ccf2b5e64 100644 --- a/src/EPPlus.Export.Pdf/Enums/EPPlusEnums.cs +++ b/src/EPPlus.Export.Pdf/Enums/EPPlusEnums.cs @@ -9,7 +9,7 @@ namespace EPPlus.Export.Pdf.Enums /// /// Horizontal text alignment /// - public enum ExcelHorizontalAlignment + internal enum ExcelHorizontalAlignment { /// /// General aligned @@ -47,7 +47,7 @@ public enum ExcelHorizontalAlignment /// /// Vertical text alignment /// - public enum ExcelVerticalAlignment + internal enum ExcelVerticalAlignment { /// /// Top aligned @@ -73,7 +73,7 @@ public enum ExcelVerticalAlignment /// /// The reading order /// - public enum ExcelReadingOrder + internal enum ExcelReadingOrder { /// /// Reading order is determined by the first non-whitespace character @@ -91,7 +91,7 @@ public enum ExcelReadingOrder /// /// Fill pattern /// - public enum ExcelFillStyle + internal enum ExcelFillStyle { /// /// No fill @@ -190,7 +190,7 @@ public enum ExcelFillStyle /// /// BulletType of gradient fill /// - public enum ExcelFillGradientType + internal enum ExcelFillGradientType { /// /// No gradient fill. @@ -208,7 +208,7 @@ public enum ExcelFillGradientType /// /// Border line style /// - public enum ExcelBorderStyle + internal enum ExcelBorderStyle { /// /// No border style diff --git a/src/EPPlus.Export.Pdf/ExcelPdf.cs b/src/EPPlus.Export.Pdf/ExcelPdf.cs index 2a38df168..5459028e2 100644 --- a/src/EPPlus.Export.Pdf/ExcelPdf.cs +++ b/src/EPPlus.Export.Pdf/ExcelPdf.cs @@ -357,7 +357,7 @@ private void AddOutline(PdfCatalog catalog, List<(PdfPageLayout Layout, int Page var pageOrder = new Dictionary(); for (int i = 0; i < destIndex.Count; i++) pageOrder[destIndex[i].PageObj] = i; - var sheets = new List<(string Name, int PageObj, double TopY)>(); + var sheets = new List<(string Name, int PageObj, double TopY, string BookmarkPrefix)>(); var seenSheets = new HashSet(StringComparer.OrdinalIgnoreCase); var commentsBySheet = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var (L, obj) in destIndex) @@ -365,7 +365,7 @@ private void AddOutline(PdfCatalog catalog, List<(PdfPageLayout Layout, int Page if (!L.isCommentsPage && L.SheetName != null) { if (seenSheets.Add(L.SheetName)) - sheets.Add((L.SheetName, obj, L.Settings.PageSize.HeightPu)); + sheets.Add((L.SheetName, obj, L.Settings.PageSize.HeightPu, L.Settings.BookmarkNamePrefix)); } else if (L.isCommentsPage && L.CommentsSourceSheet != null) { @@ -392,7 +392,7 @@ private void AddOutline(PdfCatalog catalog, List<(PdfPageLayout Layout, int Page sheetItems.Add(sheetItem); totalVisible++; var childItems = new List(); - foreach (var k in BuildOutlineChildren(sh.Name, _documentSettings.BookmarkNamePrefix, catLayout, commentsBySheet, destIndex, pageOrder)) + foreach (var k in BuildOutlineChildren(sh.Name, sh.BookmarkPrefix, catLayout, commentsBySheet, destIndex, pageOrder)) { var childItem = new PdfOutlineItem(_document.Count + 1) { @@ -620,7 +620,7 @@ private void WriteCrossRefAndTrailer(BinaryWriter bw, PdfCrossRefTable crossRefT PdfTrailer.Write(bw, _document.Count, catalog.objectNumber, info.objectNumber, crossRefTable.StartPosition); if (_debugText != null) { - _debugText.Append(crossRefTable.WriteString(_document.Count)); + _debugText.Append(crossRefTable.Write(offset, _document.Count)); _debugText.Append(PdfTrailer.WriteString(_document.Count, catalog.objectNumber, info.objectNumber, crossRefTable.StartPosition)); } } diff --git a/src/EPPlus.Export.Pdf/Layout/PdfDataBarLayout .cs b/src/EPPlus.Export.Pdf/Layout/PdfDataBarLayout.cs similarity index 100% rename from src/EPPlus.Export.Pdf/Layout/PdfDataBarLayout .cs rename to src/EPPlus.Export.Pdf/Layout/PdfDataBarLayout.cs diff --git a/src/EPPlus.Export.Pdf/Layout/PdfIconLayout .cs b/src/EPPlus.Export.Pdf/Layout/PdfIconLayout.cs similarity index 100% rename from src/EPPlus.Export.Pdf/Layout/PdfIconLayout .cs rename to src/EPPlus.Export.Pdf/Layout/PdfIconLayout.cs diff --git a/src/EPPlus.Export.Pdf/Resources/PdfImageResource .cs b/src/EPPlus.Export.Pdf/Resources/PdfImageResource.cs similarity index 100% rename from src/EPPlus.Export.Pdf/Resources/PdfImageResource .cs rename to src/EPPlus.Export.Pdf/Resources/PdfImageResource.cs diff --git a/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfMargins.cs b/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfMargins.cs index 65a29f1bf..6ac19f855 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfMargins.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfMargins.cs @@ -14,7 +14,7 @@ Date Author Change namespace EPPlus.Export.Pdf.Settings.PdfPageSizes { - public class PdfMargins + internal class PdfMargins { //Suffix Pu is short hand for PdfUnits. diff --git a/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfPageSize.cs b/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfPageSize.cs index 18fb30bb5..ab3ae110a 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfPageSize.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfPageSize.cs @@ -14,7 +14,7 @@ Date Author Change namespace EPPlus.Export.Pdf.Settings.PdfPageSizes { - public class PdfPageSize + internal class PdfPageSize { public double Width { get; } public double Height { get; } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfScaling.cs b/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfScaling.cs index 5d48db05c..16cee7192 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfScaling.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfPageSizes/PdfScaling.cs @@ -12,7 +12,7 @@ Date Author Change *************************************************************************************************/ namespace EPPlus.Export.Pdf.Settings.PdfPageSizes { - public enum ScalingMode + internal enum ScalingMode { /// /// Adjust size based on the normal size @@ -24,7 +24,7 @@ public enum ScalingMode FitToPages } - public class PdfScaling + internal class PdfScaling { public ScalingMode ScalingMode { get; set; } diff --git a/src/EPPlus/ExcelRangeBase.cs b/src/EPPlus/ExcelRangeBase.cs index 652ba8f20..612a23f41 100644 --- a/src/EPPlus/ExcelRangeBase.cs +++ b/src/EPPlus/ExcelRangeBase.cs @@ -1148,11 +1148,21 @@ public IExcelHtmlRangeExporter CreateHtmlExporter() /// Additional EPPlus specific PDF Export settings. public void SaveAsPdf(string fileName, PdfExportSettings settings = null) { - var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - pdfWriter.Save(fileName); + var rs = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + new EPPlusToPdfWriter(rs, this).Save(fileName); } + /// + /// Save range to PDF asynchronously. + /// + /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Token to cancel the operation. + /// A task representing the asynchronous operation. + /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. + /// In UI applications, wrap the call in Task.Run to keep the UI responsive. + public Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(fileName, (PdfExportSettings)null, cancellationToken); + /// /// Save range to PDF asynchronously. /// @@ -1162,12 +1172,11 @@ public void SaveAsPdf(string fileName, PdfExportSettings settings = null) /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); + var rs = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, this).SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } /// @@ -1177,11 +1186,21 @@ public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = n /// Additional EPPlus specific PDF Export settings. public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) { - var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - pdfWriter.Save(stream); + var rs = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + new EPPlusToPdfWriter(rs, this).Save(stream); } + /// + /// Save range to PDF asynchronously, writing to a stream. + /// + /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Token to cancel the operation. + /// A task representing the asynchronous operation. + /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. + /// In UI applications, wrap the call in Task.Run to keep the UI responsive. + public Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(stream, (PdfExportSettings)null, cancellationToken); + /// /// Save range to PDF asynchronously, writing to a stream. /// @@ -1191,12 +1210,11 @@ public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); + var rs = GetPdfSettings.BuildBase(this.Worksheet.Workbook, this.Worksheet.PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, this).SaveAsync(stream, cancellationToken).ConfigureAwait(false); } diff --git a/src/EPPlus/ExcelWorkbook.cs b/src/EPPlus/ExcelWorkbook.cs index ea7b0ba95..a49e11b84 100644 --- a/src/EPPlus/ExcelWorkbook.cs +++ b/src/EPPlus/ExcelWorkbook.cs @@ -741,9 +741,8 @@ public IExcelHtmlRangeExporter CreateHtmlExporter(params ExcelRangeBase[] ranges /// Additional EPPlus specific PDF Export settings. public void SaveAsPdf(string fileName, PdfExportSettings settings = null) { - var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - pdfWriter.Save(fileName); + var rs = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + new EPPlusToPdfWriter(rs, this).Save(fileName); } /// @@ -753,12 +752,12 @@ public void SaveAsPdf(string fileName, PdfExportSettings settings = null) /// Additional EPPlus specific PDF Export settings. /// Worksheets to export. /// No worksheets are supplied. - public void SaveAsPdf(string fileName, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) + public void SaveAsPdf(string fileName, IEnumerable worksheets, PdfExportSettings settings = null) { - ValidatePdfWorksheets(worksheets); - var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); - pdfWriter.Save(fileName); + var ws = worksheets as ExcelWorksheet[] ?? worksheets?.ToArray(); + ValidatePdfWorksheets(ws); + var rs = GetPdfSettings.BuildBase(this, ws[0].PrinterSettings, settings); + new EPPlusToPdfWriter(rs, ws).Save(fileName); } /// @@ -768,12 +767,12 @@ public void SaveAsPdf(string fileName, PdfExportSettings settings = null, params /// Additional EPPlus specific PDF Export settings. /// Ranges to export. /// No ranges are supplied. - public void SaveAsPdf(string fileName, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) + public void SaveAsPdf(string fileName, IEnumerable ranges, PdfExportSettings settings = null) { - ValidatePdfRanges(ranges); - var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); - pdfWriter.Save(fileName); + var r = ranges as ExcelRangeBase[] ?? ranges?.ToArray(); + ValidatePdfRanges(r); + var rs = GetPdfSettings.BuildBase(this, r[0].Worksheet.PrinterSettings, settings); + new EPPlusToPdfWriter(rs, r).Save(fileName); } /// @@ -784,25 +783,37 @@ public void SaveAsPdf(string fileName, PdfExportSettings settings = null, params /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default, PdfExportSettings settings = null) + public Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(fileName, (PdfExportSettings)null, cancellationToken); + + /// + /// Export workbook to PDF asynchronously. + /// + /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Additional EPPlus specific PDF Export settings. + /// Token to cancel the operation. + /// A task representing the asynchronous operation. + /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. + /// In UI applications, wrap the call in Task.Run to keep the UI responsive. + public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); + var rs = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, this).SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } /// /// Export selected worksheets to PDF asynchronously. /// - /// Name of file. If the export fails, the file is deleted. - /// Additional EPPlus specific PDF Export settings. + /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Token to cancel the operation. /// Worksheets to export. /// A task representing the asynchronous operation. + /// No worksheets are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) - => SaveAsPdfAsync(fileName, CancellationToken.None, settings, worksheets); + public Task SaveAsPdfAsync(string fileName, IEnumerable worksheets, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(fileName, worksheets, null, cancellationToken); /// /// Export selected worksheets to PDF asynchronously. @@ -815,26 +826,27 @@ public Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, p /// No worksheets are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) + public async Task SaveAsPdfAsync(string fileName, IEnumerable worksheets, PdfExportSettings settings, CancellationToken cancellationToken = default) { - ValidatePdfWorksheets(worksheets); cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); - await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); + var ws = worksheets as ExcelWorksheet[] ?? worksheets?.ToArray(); + ValidatePdfWorksheets(ws); + var rs = GetPdfSettings.BuildBase(this, ws[0].PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, ws).SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } /// /// Export selected ranges to PDF asynchronously. /// - /// Name of file. If the export fails, the file is deleted. - /// Additional EPPlus specific PDF Export settings. + /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Token to cancel the operation. /// Ranges to export. /// A task representing the asynchronous operation. + /// No ranges are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) - => SaveAsPdfAsync(fileName, CancellationToken.None, settings, ranges); + public Task SaveAsPdfAsync(string fileName, IEnumerable ranges, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(fileName, ranges, null, cancellationToken); /// /// Export selected ranges to PDF asynchronously. @@ -847,15 +859,17 @@ public Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, p /// No ranges are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) + public async Task SaveAsPdfAsync(string fileName, IEnumerable ranges, PdfExportSettings settings, CancellationToken cancellationToken = default) { - ValidatePdfRanges(ranges); cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); - await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); + var r = ranges as ExcelRangeBase[] ?? ranges?.ToArray(); + ValidatePdfRanges(r); + var rs = GetPdfSettings.BuildBase(this, r[0].Worksheet.PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, r).SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } + + /// /// Export workbook to PDF, writing to a stream. /// @@ -863,9 +877,8 @@ public async Task SaveAsPdfAsync(string fileName, CancellationToken cancellation /// Additional EPPlus specific PDF Export settings. public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) { - var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - pdfWriter.Save(stream); + var rs = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + new EPPlusToPdfWriter(rs, this).Save(stream); } /// @@ -875,12 +888,12 @@ public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) /// Additional EPPlus specific PDF Export settings. /// Worksheets to export. /// No worksheets are supplied. - public void SaveAsPdf(Stream stream, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) + public void SaveAsPdf(Stream stream, IEnumerable worksheets, PdfExportSettings settings = null) { - ValidatePdfWorksheets(worksheets); - var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); - pdfWriter.Save(stream); + var ws = worksheets as ExcelWorksheet[] ?? worksheets?.ToArray(); + ValidatePdfWorksheets(ws); + var rs = GetPdfSettings.BuildBase(this, ws[0].PrinterSettings, settings); + new EPPlusToPdfWriter(rs, ws).Save(stream); } /// @@ -890,14 +903,25 @@ public void SaveAsPdf(Stream stream, PdfExportSettings settings = null, params E /// Additional EPPlus specific PDF Export settings. /// Ranges to export. /// No ranges are supplied. - public void SaveAsPdf(Stream stream, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) + public void SaveAsPdf(Stream stream, IEnumerable ranges, PdfExportSettings settings = null) { - ValidatePdfRanges(ranges); - var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); - pdfWriter.Save(stream); + var r = ranges as ExcelRangeBase[] ?? ranges?.ToArray(); + ValidatePdfRanges(r); + var rs = GetPdfSettings.BuildBase(this, r[0].Worksheet.PrinterSettings, settings); + new EPPlusToPdfWriter(rs, r).Save(stream); } + /// + /// Export workbook to PDF asynchronously, writing to a stream. + /// + /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Token to cancel the operation. + /// A task representing the asynchronous operation. + /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. + /// In UI applications, wrap the call in Task.Run to keep the UI responsive. + public Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(stream, (PdfExportSettings)null, cancellationToken); + /// /// Export workbook to PDF asynchronously, writing to a stream. /// @@ -907,25 +931,25 @@ public void SaveAsPdf(Stream stream, PdfExportSettings settings = null, params E /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default, PdfExportSettings settings = null) + public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); + var rs = GetPdfSettings.BuildBase(this, Worksheets[View.ActiveTab].PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, this).SaveAsync(stream, cancellationToken).ConfigureAwait(false); } /// /// Export selected worksheets to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. - /// Additional EPPlus specific PDF Export settings. + /// Token to cancel the operation. /// Worksheets to export. /// A task representing the asynchronous operation. + /// No worksheets are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) - => SaveAsPdfAsync(stream, CancellationToken.None, settings, worksheets); + public Task SaveAsPdfAsync(Stream stream, IEnumerable worksheets, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(stream, worksheets, null, cancellationToken); /// /// Export selected worksheets to PDF asynchronously, writing to a stream. @@ -938,26 +962,27 @@ public Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, par /// No worksheets are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelWorksheet[] worksheets) + public async Task SaveAsPdfAsync(Stream stream, IEnumerable worksheets, PdfExportSettings settings, CancellationToken cancellationToken = default) { - ValidatePdfWorksheets(worksheets); cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this, worksheets[0].PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, worksheets); - await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); + var ws = worksheets as ExcelWorksheet[] ?? worksheets?.ToArray(); + ValidatePdfWorksheets(ws); + var rs = GetPdfSettings.BuildBase(this, ws[0].PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, ws).SaveAsync(stream, cancellationToken).ConfigureAwait(false); } /// /// Export selected ranges to PDF asynchronously, writing to a stream. /// /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. - /// Additional EPPlus specific PDF Export settings. + /// Token to cancel the operation. /// Ranges to export. /// A task representing the asynchronous operation. + /// No ranges are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) - => SaveAsPdfAsync(stream, CancellationToken.None, settings, ranges); + public Task SaveAsPdfAsync(Stream stream, IEnumerable ranges, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(stream, ranges, null, cancellationToken); /// /// Export selected ranges to PDF asynchronously, writing to a stream. @@ -970,13 +995,13 @@ public Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, par /// No ranges are supplied. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken, PdfExportSettings settings = null, params ExcelRangeBase[] ranges) + public async Task SaveAsPdfAsync(Stream stream, IEnumerable ranges, PdfExportSettings settings, CancellationToken cancellationToken = default) { - ValidatePdfRanges(ranges); cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this, ranges[0].Worksheet.PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, ranges); - await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); + var r = ranges as ExcelRangeBase[] ?? ranges?.ToArray(); + ValidatePdfRanges(r); + var rs = GetPdfSettings.BuildBase(this, r[0].Worksheet.PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, r).SaveAsync(stream, cancellationToken).ConfigureAwait(false); } private static void ValidatePdfWorksheets(ExcelWorksheet[] worksheets) diff --git a/src/EPPlus/ExcelWorksheet.cs b/src/EPPlus/ExcelWorksheet.cs index 3b900af83..b70cbdfb5 100644 --- a/src/EPPlus/ExcelWorksheet.cs +++ b/src/EPPlus/ExcelWorksheet.cs @@ -3736,7 +3736,7 @@ internal bool IsDisposed /// /// Worksheet specific overrides for PDF export. /// - public PdfExportSettingsOverrides PdfExportOverrides { get; } = new PdfExportSettingsOverrides(); + public PdfExportSettingsWorksheetOverrides PdfExportOverrides { get; } = new PdfExportSettingsWorksheetOverrides(); /// /// Export worksheet to PDF. @@ -3745,11 +3745,21 @@ internal bool IsDisposed /// Additional EPPlus specific PDF Export settings. public void SaveAsPdf(string fileName, PdfExportSettings settings = null) { - var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - pdfWriter.Save(fileName); + var rs = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + new EPPlusToPdfWriter(rs, this).Save(fileName); } + /// + /// Export worksheet to PDF asynchronously. + /// + /// Name of file. If the export fails or is cancelled, the file is deleted. + /// Token to cancel the operation. + /// A task representing the asynchronous operation. + /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. + /// In UI applications, wrap the call in Task.Run to keep the UI responsive. + public Task SaveAsPdfAsync(string fileName, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(fileName, (PdfExportSettings)null, cancellationToken); + /// /// Export worksheet to PDF asynchronously. /// @@ -3759,12 +3769,11 @@ public void SaveAsPdf(string fileName, PdfExportSettings settings = null) /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = null, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - await pdfWriter.SaveAsync(fileName, cancellationToken).ConfigureAwait(false); + var rs = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, this).SaveAsync(fileName, cancellationToken).ConfigureAwait(false); } /// @@ -3774,11 +3783,21 @@ public async Task SaveAsPdfAsync(string fileName, PdfExportSettings settings = n /// Additional EPPlus specific PDF Export settings. public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) { - var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - pdfWriter.Save(stream); + var rs = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + new EPPlusToPdfWriter(rs, this).Save(stream); } + /// + /// Export worksheet to PDF asynchronously, writing to a stream. + /// + /// Stream to write the PDF to. The stream does not need to be seekable. The stream is not closed; the caller owns it. + /// Token to cancel the operation. + /// A task representing the asynchronous operation. + /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. + /// In UI applications, wrap the call in Task.Run to keep the UI responsive. + public Task SaveAsPdfAsync(Stream stream, CancellationToken cancellationToken = default) + => SaveAsPdfAsync(stream, (PdfExportSettings)null, cancellationToken); + /// /// Export worksheet to PDF asynchronously, writing to a stream. /// @@ -3788,12 +3807,11 @@ public void SaveAsPdf(Stream stream, PdfExportSettings settings = null) /// A task representing the asynchronous operation. /// The PDF layout is built synchronously on the calling thread; only writing is asynchronous. /// In UI applications, wrap the call in Task.Run to keep the UI responsive. - public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings = null, CancellationToken cancellationToken = default) + public async Task SaveAsPdfAsync(Stream stream, PdfExportSettings settings, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var renderSettings = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); - var pdfWriter = new EPPlusToPdfWriter(renderSettings, this); - await pdfWriter.SaveAsync(stream, cancellationToken).ConfigureAwait(false); + var rs = GetPdfSettings.BuildBase(this.Workbook, PrinterSettings, settings); + await new EPPlusToPdfWriter(rs, this).SaveAsync(stream, cancellationToken).ConfigureAwait(false); } ExcelPackage IPictureRelationDocument.Package { get { return _package; } } diff --git a/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs b/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs index 3e926c4fe..124afb835 100644 --- a/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs +++ b/src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs @@ -313,7 +313,10 @@ private Transform GetLayout(PdfRenderSettings pageSettings, PdfWorksheet[] pdfSh private Transform GetLayout(PdfRenderSettings pageSettings, PdfWorksheet pdfSheet) { PdfWorksheet[] pdfSheets = new PdfWorksheet[1] { pdfSheet }; - var sheetSettings = new PdfRenderSettings[1] { pageSettings }; + var sheetSettings = new PdfRenderSettings[1] + { + GetPdfSettings.GetPdfSettingsForSheet(pageSettings, pdfSheet.Worksheet.PrinterSettings, pdfSheet.Worksheet.PdfExportOverrides) + }; var Layout = PdfLayout.GetLayout(sheetSettings, _dictionaries, pdfSheets); return Layout; } diff --git a/src/EPPlus/Export/PdfExport/PdfExportSettings.cs b/src/EPPlus/Export/PdfExport/PdfExportSettings.cs index d9406d648..69f78fd73 100644 --- a/src/EPPlus/Export/PdfExport/PdfExportSettings.cs +++ b/src/EPPlus/Export/PdfExport/PdfExportSettings.cs @@ -1,7 +1,15 @@ -using EPPlus.Fonts.OpenType; -using OfficeOpenXml.Interfaces.Fonts; -using System.Collections.Generic; - +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ namespace OfficeOpenXml.Export.PdfExport { /// @@ -18,26 +26,11 @@ namespace OfficeOpenXml.Export.PdfExport public class PdfExportSettings { /// + /// THIS FEATURE IS NOT SUPPORTED. /// If true, the subsetted fonts used in the document are embedded into the PDF. /// Embedding produces a self-contained, portable file at the cost of size. Default is true. /// - public bool EmbeddFonts { get; set; } = true; - - /// - /// If true, EPPlus also looks for fonts in the operating system's font directories - /// (for example c:\windows\fonts). Default is true. - /// - public bool SearchSystemDirectories { get; set; } = true; - - /// - /// Additional folders to search for fonts, beyond the system directories. - /// - public List FontDirectories { get; } = new List(); - - /// - /// Font family used when a cell's font cannot be resolved. Empty means EPPlus picks a default. - /// - public string DefaultFontName { get; set; } = ""; + private bool EmbeddFonts { get; set; } = true; /// /// Prefix that marks a defined name as a PDF bookmark. The prefix is stripped from the @@ -54,20 +47,6 @@ public class PdfExportSettings /// public bool SuppressFormFieldDetection { get; set; } = true; - /// - /// GSUB (glyph substitution) features requested when shaping text, e.g. ligatures and - /// contextual alternates. Applies to the whole export. Whether a feature has a visible effect - /// still depends on the font defining it. - /// - public GsubFeature GsubFeatures { get; set; } = GsubFeature.Liga | GsubFeature.Clig | GsubFeature.Calt | GsubFeature.Ccmp; - - /// - /// GPOS (glyph positioning) features requested when shaping text, e.g. kerning and mark - /// attachment. Applies to the whole export. Whether a feature has a visible effect still - /// depends on the font defining it. - /// - public GposFeature GposFeatures { get; set; } = GposFeature.Kern | GposFeature.Mark; - /// /// Value written to the PDF's /Author metadata. When null or empty, the workbook's /// document properties are used. diff --git a/src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs b/src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs deleted file mode 100644 index 21f706388..000000000 --- a/src/EPPlus/Export/PdfExport/PdfExportSettingsOverrides.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OfficeOpenXml.Export.PdfExport -{ - public class PdfExportSettingsOverrides - { - /// - /// Prefix that marks a defined name as a PDF bookmark. The prefix is stripped from the - /// bookmark title. The bookmark text is taken from the target cell's content, or the defined - /// name (minus the prefix) when the cell is empty. Default is "bm_". - /// This is the document-wide default; it can be overridden per worksheet. - /// - public string BookmarkNamePrefix { get; set; } - } -} diff --git a/src/EPPlus/Export/PdfExport/PdfExportSettingsWorksheetOverrides.cs b/src/EPPlus/Export/PdfExport/PdfExportSettingsWorksheetOverrides.cs new file mode 100644 index 000000000..e015ba4ae --- /dev/null +++ b/src/EPPlus/Export/PdfExport/PdfExportSettingsWorksheetOverrides.cs @@ -0,0 +1,27 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +namespace OfficeOpenXml.Export.PdfExport +{ + /// + /// Per-worksheet overrides for . A property left null inherits the + /// document-level value; a non-null value overrides it for that worksheet only. + /// + public class PdfExportSettingsWorksheetOverrides + { + /// + /// Per-worksheet bookmark prefix. When null (the default), the worksheet inherits + /// . Set it to override the prefix for this worksheet. + /// + public string BookmarkNamePrefix { get; set; } + } +} diff --git a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs index cf8c248a9..261c47e46 100644 --- a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs +++ b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs @@ -68,19 +68,19 @@ private static void ApplyPrinterSettings(PdfRenderSettings settings, ExcelPrinte private static void ApplyExportSettings(PdfRenderSettings s, PdfExportSettings e) { if (e == null) return; - s.EmbeddFonts = e.EmbeddFonts; - s.SearchSystemDirectories = e.SearchSystemDirectories; - s.FontDirectories = e.FontDirectories; - s.defaultFontName = e.DefaultFontName; + s.EmbeddFonts = true;// e.EmbeddFonts; + //s.SearchSystemDirectories = e.SearchSystemDirectories; + //s.FontDirectories = e.FontDirectories; + //s.defaultFontName = e.DefaultFontName; s.BookmarkNamePrefix = e.BookmarkNamePrefix; s.SuppressFormFieldDetection = e.SuppressFormFieldDetection; - s.GsubFeatures = e.GsubFeatures; - s.GposFeatures = e.GposFeatures; + //s.GsubFeatures = e.GsubFeatures; + //s.GposFeatures = e.GposFeatures; s.Author = e.Author; s.Title = e.Title; } - internal static PdfRenderSettings GetPdfSettingsForSheet(PdfRenderSettings baseSettings, ExcelPrinterSettings eps, PdfExportSettingsOverrides overrides) + internal static PdfRenderSettings GetPdfSettingsForSheet(PdfRenderSettings baseSettings, ExcelPrinterSettings eps, PdfExportSettingsWorksheetOverrides overrides) { var s = baseSettings.CloneForSheet(); ApplyPrinterSettings(s, eps); From 353f2746c55a5572aba5bb11b4b20e0c71021851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Wed, 25 Nov 2026 15:15:20 +0100 Subject: [PATCH 6/7] Fixed all public entry points. Cleaned up PdfObjects to eliminate repeating code. Added CompressionLevel to PdfExporterSettings. --- src/EPPlus.Export.Pdf.Tests/FontTests.cs | 6 +-- src/EPPlus.Export.Pdf.Tests/PdfTests.cs | 4 +- .../DocumentObjects/Fonts/PdfCIDFont.cs | 4 +- .../DocumentObjects/Fonts/PdfCidSet.cs | 22 +++++--- .../DocumentObjects/Fonts/PdfFont.cs | 4 +- .../Fonts/PdfFontDescriptor.cs | 4 +- .../DocumentObjects/Fonts/PdfFontStream.cs | 12 ++--- .../DocumentObjects/Fonts/PdfFontWidths.cs | 4 +- .../DocumentObjects/Fonts/PdfToUnicodeCMap.cs | 51 ++++-------------- .../DocumentObjects/Fonts/PdfType0FontDict.cs | 4 +- .../PdfExponentialInterpolationFunction.cs | 4 +- .../PdfPostScriptCalculatorFunction.cs | 32 ++---------- .../Functions/PdfStichingFunction.cs | 6 +-- .../Patterns/PdfShadingPattern.cs | 5 +- .../Patterns/PdfTilingPattern.cs | 5 +- .../DocumentObjects/PdfAcroForm.cs | 4 +- .../DocumentObjects/PdfCatalog.cs | 4 +- .../DocumentObjects/PdfContentStream.cs | 21 ++++---- .../DocumentObjects/PdfCrossRefTable.cs | 43 ++------------- .../DocumentObjects/PdfFormFieldObject.cs | 4 +- .../DocumentObjects/PdfImageXObject.cs | 42 ++++++--------- .../DocumentObjects/PdfInfoObject.cs | 17 ++++-- .../PdfLinkAnnotationObject.cs | 24 +++++---- .../DocumentObjects/PdfNamedDestinations.cs | 4 +- .../DocumentObjects/PdfObject.cs | 30 ++++------- .../DocumentObjects/PdfOutlineItem.cs | 4 +- .../DocumentObjects/PdfOutlines.cs | 4 +- .../DocumentObjects/PdfPage.cs | 4 +- .../DocumentObjects/PdfPages.cs | 5 +- .../DocumentObjects/PdfStreamObject.cs | 26 ---------- .../DocumentObjects/PdfTrailer.cs | 31 +++-------- .../DocumentObjects/PdfWriter.cs | 52 +++++++++++++++++++ .../Shadings/PdfAxialShading.cs | 7 +-- .../Shadings/PdfFunctionBasedShading.cs | 5 +- .../Shadings/PdfMeshShading.cs | 34 ++---------- .../Shadings/PdfRadialShading.cs | 6 +-- .../DocumentObjects/Shadings/PdfShading.cs | 4 +- src/EPPlus.Export.Pdf/ExcelPdf.Async.cs | 8 +-- src/EPPlus.Export.Pdf/ExcelPdf.cs | 41 ++++++++------- src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs | 19 +++++-- .../Resources/PdfImageResource.cs | 5 +- .../Settings/PdfCompressionLevel.cs | 21 ++++++++ .../Settings/PdfDocumentSettings.cs | 2 + .../Settings/PdfRenderSettings.cs | 2 + .../Export/PdfExport/PdfCompressionLevel.cs | 28 ++++++++++ .../Export/PdfExport/PdfExportSettings.cs | 6 +++ .../PdfExport/Settings/GetPdfSettings.cs | 1 + 47 files changed, 303 insertions(+), 372 deletions(-) delete mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs create mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfWriter.cs create mode 100644 src/EPPlus.Export.Pdf/Settings/PdfCompressionLevel.cs create mode 100644 src/EPPlus/Export/PdfExport/PdfCompressionLevel.cs diff --git a/src/EPPlus.Export.Pdf.Tests/FontTests.cs b/src/EPPlus.Export.Pdf.Tests/FontTests.cs index 5fe4c90ef..afb231acd 100644 --- a/src/EPPlus.Export.Pdf.Tests/FontTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/FontTests.cs @@ -186,9 +186,9 @@ public void FontObjects_ForSubsetFont_ShareIdenticalTaggedName() resource.fontData = subset; // Object numbers are arbitrary; they only need to be set in dependency order. - var descriptor = resource.GetFontDescriptorObject(10).RenderDictionary(); - var cid = resource.GetCIDFontObject(11).RenderDictionary(); - var type0 = resource.GetType0FontDictObject(12).RenderDictionary(); + var descriptor = resource.GetFontDescriptorObject(10).RenderBody(); + var cid = resource.GetCIDFontObject(11).RenderBody(); + var type0 = resource.GetType0FontDictObject(12).RenderBody(); var rx = new Regex(@"/(?:BaseFont|FontName)\s+/(\S+)"); var names = new[] { descriptor, cid, type0 } diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs index 1cf8b3c0c..062b7495d 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs @@ -111,8 +111,10 @@ public void SaveWorksheetsAsPdfTest2() var ws0 = wb.Worksheets[0]; var ws1 = wb.Worksheets[1]; var ws2 = wb.Worksheets[2]; + PdfExportSettings settings = new PdfExportSettings(); + settings.CompressionLevel = OfficeOpenXml.Export.PdfExport.PdfCompressionLevel.Fastest; string path = _pdfPath + "WorksheetsTest2.pdf"; - wb.SaveAsPdf(path, new[] { ws0, ws1, ws2 }); + wb.SaveAsPdf(path, new[] { ws0, ws1, ws2 }, settings); Assert.IsTrue(File.Exists(path), "PDF file was not created."); AssertLooksLikePdf(File.ReadAllBytes(path)); } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs index 1e588f94c..73a11122f 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCIDFont.cs @@ -14,7 +14,6 @@ Date Author Change using EPPlus.Fonts.OpenType; using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Text; @@ -117,7 +116,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs index fdc8e09e0..71e23103a 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfCidSet.cs @@ -11,12 +11,10 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Fonts { - internal class PdfCidSet : PdfStreamObject + internal class PdfCidSet : PdfObject { byte[] CidSet; @@ -25,12 +23,20 @@ public PdfCidSet(int objectNumber, byte[] cidSet , int version = 0) : base(objec CidSet = cidSet; } - protected override (string dictionary, byte[] bytes) BuildStream() + protected override void WriteBody(PdfWriter w) { - var body = PdfFlate.Compress(CidSet); - return body.Length < CidSet.Length - ? ($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>", body) - : ($"<< /Length {CidSet.Length.ToPdfStringF0()} >>", CidSet); + var body = PdfFlate.Compress(CidSet, w.CompressionLevel); + if (body.Length < CidSet.Length) + { + w.Text($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); + } + else + { + body = CidSet; + w.Text($"<< /Length {CidSet.Length.ToPdfStringF0()} >>\nstream\n"); + } + w.Bytes(body); + w.Text("\nendstream"); } } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs index 260aae3d0..b6905c316 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFont.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Fonts @@ -91,7 +90,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs index 91320a557..e19396f5e 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontDescriptor.cs @@ -13,7 +13,6 @@ Date Author Change using EPPlus.Export.Pdf.Helpers; using EPPlus.Graphics; using System; -using System.IO; using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Fonts @@ -88,7 +87,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs index 1e7aca2d4..f63b7ed98 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontStream.cs @@ -12,12 +12,10 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using EPPlus.Fonts.OpenType; -using System.IO; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Fonts { - internal class PdfFontStream : PdfStreamObject + internal class PdfFontStream : PdfObject { private readonly OpenTypeFont FontData; @@ -26,11 +24,13 @@ public PdfFontStream(int objectNumber, OpenTypeFont fontData, int version = 0) : FontData = fontData; } - protected override (string dictionary, byte[] bytes) BuildStream() + protected override void WriteBody(PdfWriter w) { var raw = FontData.Serialize(); - var body = PdfFlate.Compress(raw); - return ($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} /Length1 {raw.Length.ToPdfStringF0()} >>", body); + var body = PdfFlate.Compress(raw, w.CompressionLevel); + w.Text($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} /Length1 {raw.Length.ToPdfStringF0()} >>\nstream\n"); + w.Bytes(body); + w.Text("\nendstream"); } } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs index b9ee4fa26..3ddeeec7e 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfFontWidths.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using System.Collections.Generic; -using System.IO; using System.Linq; namespace EPPlus.Export.Pdf.DocumentObjects.Fonts @@ -32,7 +31,6 @@ private string Body() return $" [ {widthsStr} ]"; } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs index 075451006..d40c6b00f 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfToUnicodeCMap.cs @@ -12,7 +12,6 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Text; @@ -232,50 +231,18 @@ public CharacterMapping(int code, string unicode) } } - //private string Body(bool compress) - //{ - // var cmapContent = GenerateCMapContent(); - // var length = Encoding.UTF8.GetByteCount(cmapContent); - // var sb = new StringBuilder(); - // sb.AppendLine(string.Format("<< /Length {0} >>", length.ToPdfStringF0())); - // sb.AppendLine("stream"); - // sb.Append(cmapContent); - // sb.Append("\nendstream"); - // return sb.ToString(); - //} - - //internal override void RenderDictionary() - //{ - // var cmapContent = GenerateCMapContent(); - // var cmapBytes = Encoding.ASCII.GetBytes(cmapContent); - // var body = PdfFlate.Compress(cmapBytes); - // WriteAscii(bw, $"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); - // bw.Write(body); - // WriteAscii(bw, "\nendstream"); - //} - - private string Body(bool compress) + protected override void WriteBody(PdfWriter w) { - var cmapContent = GenerateCMapContent(); - var cmapBytes = Encoding.ASCII.GetBytes(cmapContent); - var cmapBytesCompressed = compress ? PdfFlate.Compress(cmapBytes) : null; - - var sb = new StringBuilder(); - if (compress) + var content = GenerateCMapContent(); + if (w.IsDebug) { - sb.AppendFormat($"<< /Filter /FlateDecode /Length {cmapBytesCompressed.Length.ToPdfStringF0()} >>\nstream\n"); - sb.AppendFormat($"{cmapBytesCompressed}"); + w.Text($"<< /Length {Encoding.ASCII.GetByteCount(content).ToPdfStringF0()} >>\nstream\n{content}\nendstream"); + return; } - else - { - sb.AppendFormat($"<< /Length {cmapBytes.Length.ToPdfStringF0()} \nstream>>"); - sb.Append(cmapContent); - } - sb.Append("\nendstream"); - return sb.ToString(); + var body = PdfFlate.Compress(Encoding.ASCII.GetBytes(content), w.CompressionLevel); + w.Text($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); + w.Bytes(body); + w.Text("\nendstream"); } - - internal override string RenderDictionary() => Body(false); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body(true)); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs index 9ca5ab415..485ac2f18 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Fonts/PdfType0FontDict.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; using System.Linq; using System.Text; @@ -50,7 +49,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs index ff8842b16..db7915e54 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfExponentialInterpolationFunction.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; using System.Linq; using System.Text; @@ -39,7 +38,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs index e79e857a5..9a0763301 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfPostScriptCalculatorFunction.cs @@ -13,7 +13,6 @@ Date Author Change using EPPlus.Export.Pdf.Helpers; using EPPlus.Export.Pdf.Layout; using System.Drawing; -using System.IO; using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Functions @@ -79,33 +78,12 @@ private static void GetFocus(PdfCellGradientFillData g, out double fx, out doubl } } - //internal override string RenderDictionary() - //{ - // return "<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + - // $"/Length {Encoding.ASCII.GetByteCount(_code)} >>\nstream\n{_code}\nendstream"; - //} - - //internal override void RenderDictionary(BinaryWriter bw) - //{ - // var bytes = Encoding.ASCII.GetBytes(_code); - // WriteAscii(bw, "<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + - // $"/Length {bytes.Length.ToPdfStringF0()} >>\nstream\n"); - // bw.Write(bytes); - // WriteAscii(bw, "\nendstream"); - //} - - private string Body() + protected override void WriteBody(PdfWriter w) { - var bytes = Encoding.ASCII.GetBytes(_code); - StringBuilder sb = new StringBuilder(); - sb.AppendFormat($"<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] " + - $"/Length {bytes.Length.ToPdfStringF0()} >>\nstream\n"); - sb.AppendFormat($"{bytes}"); - sb.Append("\nendstream"); - return sb.ToString(); + var length = Encoding.ASCII.GetByteCount(_code); + w.Text($"<< /FunctionType 4 /Domain [ 0 1 0 1 ] /Range [ 0 1 0 1 0 1 ] /Length {length.ToPdfStringF0()} >>\nstream\n"); + w.Text(_code); + w.Text("\nendstream"); } - - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs index a36926fe9..747e3549f 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Functions/PdfStichingFunction.cs @@ -12,7 +12,6 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Text; @@ -29,7 +28,7 @@ public PdfStichingFunction(int objectNumber, int version = 0) : base(objectNumbe private string Body() { var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); - var functionsStr = string.Join("\n", Functions.Select(w => w.RenderDictionary()).ToArray()); + var functionsStr = string.Join("\n", Functions.Select(w => w.RenderBody()).ToArray()); var boundsStr = string.Join(" ", Bounds.Select(w => w.ToPdfString()).ToArray()); var encodeStr = string.Join(" ", Encode.Select(w => w.ToPdfString()).ToArray()); var sb = new StringBuilder(); @@ -41,7 +40,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs index 0756ae3a0..b062dc060 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfShadingPattern.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; using System.Linq; using System.Text; @@ -44,8 +43,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs index fdbd60914..12d23c829 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Patterns/PdfTilingPattern.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; using System.Linq; using System.Text; @@ -65,8 +64,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm.cs index c2cfd7ebf..52bf0cc27 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm.cs @@ -12,7 +12,6 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.Collections.Generic; -using System.IO; using System.Linq; namespace EPPlus.Export.Pdf.DocumentObjects @@ -36,7 +35,6 @@ private string Body() return $"<< /Fields [ {fields} ]\n /NeedAppearances false >>"; } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs index 5daa886ae..3450b3323 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCatalog.cs @@ -11,7 +11,6 @@ Date Author Change 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -50,7 +49,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs index 9c7e1d270..a6f3123a7 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfContentStream.cs @@ -17,7 +17,6 @@ Date Author Change using System; using System.Collections.Generic; using System.Drawing; -using System.IO; using System.Linq; using System.Text; using EPPlus.Fonts.OpenType.Integration; @@ -29,7 +28,7 @@ Date Author Change namespace EPPlus.Export.Pdf.DocumentObjects { - internal class PdfContentStream : PdfStreamObject + internal class PdfContentStream : PdfObject { private readonly List commands = new List(); private readonly Stack<(int index, string header)> _artifactMarks = new Stack<(int, string)>(); @@ -641,17 +640,19 @@ public void AddIconLayout(PdfIconLayout icon) EndArtifact(); } - protected override (string dictionary, byte[] bytes) BuildStream() + protected override void WriteBody(PdfWriter w) { var content = string.Join("\n", commands.ToArray()) + "\n"; - var body = PdfFlate.Compress(Encoding.ASCII.GetBytes(content)); - return ($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>", body); + if (w.IsDebug) + { + w.Text($"<< /Length {Encoding.ASCII.GetByteCount(content).ToPdfStringF0()} >>\nstream\n{content}endstream"); + return; + } + var body = PdfFlate.Compress(Encoding.ASCII.GetBytes(content), w.CompressionLevel); + w.Text($"<< /Filter /FlateDecode /Length {body.Length.ToPdfStringF0()} >>\nstream\n"); + w.Bytes(body); + w.Text("\nendstream"); } - internal override string RenderDictionary() - { - var content = string.Join("\n", commands.ToArray()) + "\n"; - return $"<< /Length {Encoding.ASCII.GetByteCount(content).ToPdfStringF0()} >>\nstream\n{content}endstream"; - } } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs index e1bff0d29..a229e7164 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfCrossRefTable.cs @@ -13,9 +13,6 @@ Date Author Change using EPPlus.Export.Pdf.Helpers; using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Reflection; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -29,46 +26,16 @@ internal void AddPosition(long position) positions.Add(position); } - //internal string WriteString(int bodyCount) - //{ - // StringBuilder sb = new StringBuilder(); - // sb.Append("xref\n"); - // sb.AppendFormat($"0 {(bodyCount + 1).ToPdfStringF0()}\n"); - // sb.Append("0000000000 65535 f \n"); - // foreach (long pos in positions) - // { - // sb.AppendFormat(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n"); - // } - // return sb.ToString(); - //} - - //internal void Write(BinaryWriter bw, long startPosition, int bodyCount) - //{ - // StartPosition = startPosition; - // bw.Write(Encoding.ASCII.GetBytes("xref\n")); - // bw.Write(Encoding.ASCII.GetBytes($"0 {(bodyCount + 1).ToPdfStringF0()}\n")); - // bw.Write(Encoding.ASCII.GetBytes("0000000000 65535 f \n")); - // foreach (long pos in positions) - // { - // bw.Write(Encoding.ASCII.GetBytes(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n")); - // } - //} - - private string Body(long startPosition, int bodyCount) + internal void Write(PdfWriter w, long startPosition, int bodyCount) { StartPosition = startPosition; - StringBuilder sb = new StringBuilder(); - sb.Append("xref\n"); - sb.AppendFormat($"0 {(bodyCount + 1).ToPdfStringF0()}\n"); - sb.Append("0000000000 65535 f \n"); + w.Text("xref\n"); + w.Text($"0 {(bodyCount + 1).ToPdfStringF0()}\n"); + w.Text("0000000000 65535 f \n"); foreach (long pos in positions) { - sb.AppendFormat(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n"); + w.Text(pos.ToString("D10", CultureInfo.InvariantCulture) + " 00000 n \n"); } - return sb.ToString(); } - - internal string Write(long startPosition, int bodyCount) => Body(startPosition, bodyCount); - internal void Write(BinaryWriter bw, long startPosition, int bodyCount) => bw.Write(Encoding.ASCII.GetBytes(Body(startPosition, bodyCount))); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject.cs index f7884f74d..7b7d41358 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject.cs @@ -11,7 +11,6 @@ Date Author Change 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -42,7 +41,6 @@ private string Body() $" /P {pageObjectNumber.ToPdfStringF0()} 0 R >>"; } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs index 10fa92c90..9709da096 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfImageXObject.cs @@ -11,12 +11,11 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; -using System.Text; +using EPPlus.Export.Pdf.Settings; namespace EPPlus.Export.Pdf.DocumentObjects { - internal class PdfImageXObject : PdfStreamObject + internal class PdfImageXObject : PdfObject { private readonly byte[] _bytes; internal int Width { get; } @@ -31,7 +30,7 @@ internal class PdfImageXObject : PdfStreamObject internal byte[] SoftMaskData { get; } internal int SoftMaskObjectNumber { get; set; } - public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, int version = 0) + public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, PdfCompressionLevel compressionLevel, int version = 0) : base(objectNumber, version) { byte[] icoDib = null; @@ -48,10 +47,10 @@ public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, ColorSpace = "/DeviceRGB"; Filter = "FlateDecode"; if (blackAndWhite) GrayscaleRgb(icoRgb); - _bytes = PdfFlate.CompressLeaveOpen(icoRgb); + _bytes = PdfFlate.CompressLeaveOpen(icoRgb, compressionLevel); if (icoAlpha != null) { - SoftMaskData = PdfFlate.CompressLeaveOpen(icoAlpha); + SoftMaskData = PdfFlate.CompressLeaveOpen(icoAlpha, compressionLevel); HasSoftMask = true; } } @@ -64,7 +63,7 @@ public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, BitsPerComponent = 8; ColorSpace = "/DeviceGray"; Filter = "FlateDecode"; - _bytes = PdfFlate.CompressLeaveOpen(grayPixels); + _bytes = PdfFlate.CompressLeaveOpen(grayPixels, compressionLevel); } else { @@ -148,7 +147,7 @@ public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, ColorSpace = "/DeviceRGB"; Filter = "FlateDecode"; if (blackAndWhite) GrayscaleRgb(bmpRgb); - _bytes = PdfFlate.CompressLeaveOpen(bmpRgb); + _bytes = PdfFlate.CompressLeaveOpen(bmpRgb, compressionLevel); } else if (GifDecoder.TryDecode(imageBytes, out int gifW, out int gifH, out byte[] gifRgb, out byte[] gifAlpha)) { @@ -157,8 +156,8 @@ public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, ColorSpace = "/DeviceRGB"; Filter = "FlateDecode"; if (blackAndWhite) GrayscaleRgb(gifRgb); - _bytes = PdfFlate.CompressLeaveOpen(gifRgb); - if (gifAlpha != null) { SoftMaskData = PdfFlate.CompressLeaveOpen(gifAlpha); HasSoftMask = true; } + _bytes = PdfFlate.CompressLeaveOpen(gifRgb, compressionLevel); + if (gifAlpha != null) { SoftMaskData = PdfFlate.CompressLeaveOpen(gifAlpha, compressionLevel); HasSoftMask = true; } } else if (TiffDecoder.TryDecode(imageBytes, out int tifW, out int tifH, out byte[] tifRgb, out byte[] tifAlpha)) { @@ -168,10 +167,10 @@ public PdfImageXObject(int objectNumber, byte[] imageBytes, bool blackAndWhite, ColorSpace = "/DeviceRGB"; Filter = "FlateDecode"; if (blackAndWhite) GrayscaleRgb(tifRgb); - _bytes = PdfFlate.CompressLeaveOpen(tifRgb); + _bytes = PdfFlate.CompressLeaveOpen(tifRgb, compressionLevel); if (tifAlpha != null) { - SoftMaskData = PdfFlate.CompressLeaveOpen(tifAlpha); + SoftMaskData = PdfFlate.CompressLeaveOpen(tifAlpha, compressionLevel); HasSoftMask = true; } } @@ -288,18 +287,11 @@ private string DictHeader() $" /Length {_bytes.Length.ToPdfStringF0()} >>"; } - //internal override string RenderDictionary() - //{ - // return DictHeader() + $"\nstream\n<{_bytes.Length.ToPdfStringF0()} bytes of image data>\nendstream"; - //} - - //internal override void RenderDictionary(BinaryWriter bw) - //{ - // WriteAscii(bw, DictHeader() + "\nstream\n"); - // bw.Write(_bytes); - // WriteAscii(bw, "\nendstream"); - //} - - protected override (string dictionary, byte[] bytes) BuildStream() => (DictHeader(), _bytes); + protected override void WriteBody(PdfWriter w) + { + w.Text(DictHeader() + "\nstream\n"); + w.Bytes(_bytes); + w.Text("\nendstream"); + } } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs index 4a9996ffd..aa6528ec8 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs @@ -10,10 +10,20 @@ Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ using EPPlus.Export.Pdf.Settings; using System; -using System.IO; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -50,7 +60,6 @@ private string Body() $" /Trapped /False >>"; } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs index 70ce9d8e2..3b0b1bcd8 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfLinkAnnotationObject.cs @@ -1,10 +1,16 @@ -using EPPlus.Export.Pdf.Helpers; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.Export.Pdf.Helpers; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -49,8 +55,6 @@ private string Body() $" /F 4{contents}\n" + $" {action} >>"; } - - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfNamedDestinations.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfNamedDestinations.cs index d91da4960..d7f632b18 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfNamedDestinations.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfNamedDestinations.cs @@ -12,7 +12,6 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Text; @@ -45,7 +44,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfObject.cs index 677e1f2d9..4294bbaae 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfObject.cs @@ -11,8 +11,6 @@ Date Author Change 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -27,30 +25,20 @@ public PdfObject(int objectNumber, int version = 0) this.version = version; } - public virtual string ToPdfString() + internal string RenderBody() { - var sb = new StringBuilder(); - sb.AppendFormat("{0} {1} obj\n", objectNumber.ToPdfStringF0(), version.ToPdfStringF0()); - sb.Append(RenderDictionary()); - sb.Append("\nendobj\n"); - return sb.ToString(); + var w = new PdfWriter(null, captureDebug: true); + WriteBody(w); + return w.DebugText; } - public virtual void ToPdfBytes(BinaryWriter bw) + public void Write(PdfWriter w) { - var sb = new StringBuilder(); - WriteAscii(bw, $"{objectNumber.ToPdfStringF0()} {version.ToPdfStringF0()} obj\n"); - RenderDictionary(bw); - WriteAscii(bw, $"\nendobj\n"); + w.Text($"{objectNumber.ToPdfStringF0()} {version.ToPdfStringF0()} obj\n"); + WriteBody(w); + w.Text("\nendobj\n"); } - protected static void WriteAscii(BinaryWriter bw, string s) - { - bw.Write(Encoding.ASCII.GetBytes(s)); - } - - internal abstract string RenderDictionary(); - - internal abstract void RenderDictionary(BinaryWriter bw); + protected abstract void WriteBody(PdfWriter w); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlineItem.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlineItem.cs index 14b5ded72..78e58d353 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlineItem.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlineItem.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects @@ -42,7 +41,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlines.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlines.cs index 569611587..55ef319ef 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlines.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfOutlines.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -28,7 +27,6 @@ private string Body() => $" /Last {Last.ToPdfStringF0()} 0 R" + $" /Count {Count.ToPdfStringF0()} >>"; - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs index ee53cf488..56df976f4 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPage.cs @@ -14,7 +14,6 @@ Date Author Change using EPPlus.Export.Pdf.Resources; using EPPlus.Export.Pdf.Settings.PdfPageSizes; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Text; @@ -78,7 +77,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs index cb0a7e4fa..68185b669 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfPages.cs @@ -12,9 +12,7 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects { @@ -36,7 +34,6 @@ private string Body() $" /Count {pageObjectNumbers.Count.ToPdfStringF0()} >>"; } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs deleted file mode 100644 index dfa4e74f8..000000000 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfStreamObject.cs +++ /dev/null @@ -1,26 +0,0 @@ -using EPPlus.Export.Pdf.Helpers; -using System.IO; - -namespace EPPlus.Export.Pdf.DocumentObjects -{ - internal abstract class PdfStreamObject : PdfObject - { - protected PdfStreamObject(int objectNumber, int version = 0) : base(objectNumber, version) { } - - protected abstract (string dictionary, byte[] bytes) BuildStream(); - - internal sealed override void RenderDictionary(BinaryWriter bw) - { - var (dictionary, bytes) = BuildStream(); - WriteAscii(bw, dictionary + "\nstream\n"); - bw.Write(bytes); - WriteAscii(bw, "\nendstream"); - } - - internal override string RenderDictionary() - { - var (dictionary, bytes) = BuildStream(); - return dictionary + $"\nstream\n|{bytes.Length.ToPdfStringF0()} bytes binary data|\nendstream"; - } - } -} diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfTrailer.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfTrailer.cs index a79dc9102..8c3eec487 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfTrailer.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfTrailer.cs @@ -11,35 +11,20 @@ Date Author Change 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; -using System.IO; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects { internal static class PdfTrailer { - internal static string WriteString(int bodyCount, int catalogObjectNumber, int infoObjectNumber, long crossRefStartPosition) + internal static void Write(PdfWriter w, int bodyCount, int catalogObjectNumber, int infoObjectNumber, long crossRefStartPosition) { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("trailer\n"); - sb.AppendFormat($"<< /Size {(bodyCount + 1).ToPdfStringF0()}\n" + - $" /Root {catalogObjectNumber.ToPdfStringF0()} 0 R\n" + - $" /Info {infoObjectNumber.ToPdfStringF0()} 0 R >>\n"); - sb.AppendFormat("startxref\n"); - sb.AppendFormat($"{crossRefStartPosition.ToPdfStringF0()}\n"); - sb.AppendFormat("%%EOF\n"); - return sb.ToString(); - } - - internal static void Write(BinaryWriter bw, int bodyCount, int catalogObjectNumber, int infoObjectNumber, long crossRefStartPosition) - { - bw.Write(Encoding.ASCII.GetBytes($"trailer\n" + - $"<< /Size {(bodyCount + 1).ToPdfStringF0()}\n" + - $" /Root {catalogObjectNumber.ToPdfStringF0()} 0 R\n" + - $" /Info {infoObjectNumber.ToPdfStringF0()} 0 R >>\n" + - $"startxref\n" + - $"{crossRefStartPosition.ToPdfStringF0()}\n" + - $"%%EOF\n")); + w.Text("trailer\n"); + w.Text($"<< /Size {(bodyCount + 1).ToPdfStringF0()}\n" + + $" /Root {catalogObjectNumber.ToPdfStringF0()} 0 R\n" + + $" /Info {infoObjectNumber.ToPdfStringF0()} 0 R >>\n"); + w.Text("startxref\n"); + w.Text($"{crossRefStartPosition.ToPdfStringF0()}\n"); + w.Text("%%EOF\n"); } } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfWriter.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfWriter.cs new file mode 100644 index 000000000..6b2aba720 --- /dev/null +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfWriter.cs @@ -0,0 +1,52 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.Export.Pdf.Settings; +using System.IO; +using System.Text; + +internal sealed class PdfWriter +{ + private readonly BinaryWriter _bw; + private readonly StringBuilder _debug; + internal readonly bool IsDebug; + private byte[] _buf = new byte[512]; + internal readonly PdfCompressionLevel CompressionLevel; + + public PdfWriter(BinaryWriter bw, bool captureDebug = false, PdfCompressionLevel compressionLevel = PdfCompressionLevel.Smallest) + { + _bw = bw; + IsDebug = captureDebug; + CompressionLevel = compressionLevel; + if (captureDebug) _debug = new StringBuilder(); + } + + public string DebugText => _debug?.ToString(); + + public void Text(string s) + { + if (_bw != null) + { + int n = s.Length; + if (_buf.Length < n) _buf = new byte[n]; + Encoding.ASCII.GetBytes(s, 0, n, _buf, 0); + _bw.Write(_buf, 0, n); + } + _debug?.Append(s); + } + + public void Bytes(byte[] b) + { + _bw?.Write(b); + _debug?.Append($"|{b.Length} bytes binary|"); + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs index cd246422d..8f18e00ae 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfAxialShading.cs @@ -13,7 +13,6 @@ Date Author Change using System.Drawing; using System.Linq; using System.Text; -using System.IO; using EPPlus.Export.Pdf.Layout; using EPPlus.Export.Pdf.DocumentObjects.Functions; using EPPlus.Export.Pdf.Helpers; @@ -74,7 +73,7 @@ private string Body() $" /ShadingType 2\n" + $" /ColorSpace /{ColorSpace.ToString()}\n" + $" /Coords [ {coordsStr} ]\n"); - sb.AppendFormat($" /Function {Function.RenderDictionary()}"); + sb.AppendFormat($" /Function {Function.RenderBody()}"); if (Domain != null) { var domainStr = string.Join(" ", Domain.Select(w => w.ToPdfString()).ToArray()); @@ -94,8 +93,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs index db5caf1d3..a6df2601a 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfFunctionBasedShading.cs @@ -12,7 +12,6 @@ Date Author Change *************************************************************************************************/ using EPPlus.Export.Pdf.Helpers; using EPPlus.Export.Pdf.Layout; -using System.IO; using System.Linq; using System.Text; @@ -41,8 +40,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs index a1f38d71d..2340b441d 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfMeshShading.cs @@ -14,10 +14,7 @@ Date Author Change using EPPlus.Export.Pdf.Layout; using System; using System.Collections.Generic; -using System.ComponentModel.Design; using System.Drawing; -using System.IO; -using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Shadings { @@ -135,34 +132,11 @@ private string DictHeader() => " /Decode [0 1 0 1 0 1 0 1 0 1]\n" + " /Length " + _mesh.Length + " >>\n"; - //internal override string RenderDictionary() - // => DictHeader() + "stream\n|BINARY DATA|\nendstream"; - - //internal override void RenderDictionary(BinaryWriter bw) - //{ - // WriteAscii(bw, DictHeader() + "stream\n"); - // bw.Write(_mesh); - // WriteAscii(bw, "\nendstream"); - //} - - private string Body(bool debug) + protected override void WriteBody(PdfWriter w) { - StringBuilder sb = new StringBuilder(); - sb.Append(DictHeader()); - sb.Append("stream\n"); - if (debug) - { - sb.Append("|BINARY DATA|"); - } - else - { - sb.AppendFormat($"{_mesh}"); - } - sb.Append("\nendstream"); - return sb.ToString(); + w.Text(DictHeader() + "stream\n"); + w.Bytes(_mesh); + w.Text("\nendstream"); } - - internal override string RenderDictionary() => Body(true); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body(false)); } } \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs index 011374e9c..501b6de5c 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfRadialShading.cs @@ -14,7 +14,6 @@ Date Author Change using EPPlus.Export.Pdf.Helpers; using EPPlus.Export.Pdf.Layout; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Text; @@ -44,7 +43,7 @@ public PdfRadialShading(int objectNumber, PdfCellGradientFillData GradientFillDa private string Body() { var coordsStr = string.Join(" ", Coords.Select(w => w.ToPdfString()).ToArray()); - var functionsStr = string.Join("\n", Functions.Select(w => w.RenderDictionary()).ToArray()); + var functionsStr = string.Join("\n", Functions.Select(w => w.RenderBody()).ToArray()); var sb = new StringBuilder(); sb.AppendFormat($"<< /Type /Shading\n" + $" /ShadingType 3\n" + @@ -65,7 +64,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs index 1a6fac0cf..022f45430 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/Shadings/PdfShading.cs @@ -11,7 +11,6 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Graphics; -using System.IO; using System.Text; namespace EPPlus.Export.Pdf.DocumentObjects.Shadings @@ -62,7 +61,6 @@ private string Body() return sb.ToString(); } - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); + protected override void WriteBody(PdfWriter w) => w.Text(Body()); } } diff --git a/src/EPPlus.Export.Pdf/ExcelPdf.Async.cs b/src/EPPlus.Export.Pdf/ExcelPdf.Async.cs index 28732b093..305085045 100644 --- a/src/EPPlus.Export.Pdf/ExcelPdf.Async.cs +++ b/src/EPPlus.Export.Pdf/ExcelPdf.Async.cs @@ -60,19 +60,21 @@ internal async Task CreatePdfAsync(PdfDocumentSettings documentSettings, PdfDict using (var buffer = new MemoryStream()) using (var bw = new BinaryWriter(buffer, Encoding.ASCII)) { - WriteHeader(bw); + var writer = new PdfWriter(bw, _debugText != null, documentSettings.CompressionLevel); + WriteHeader(writer); offset += await FlushBufferAsync(bw, buffer, stream, cancellationToken).ConfigureAwait(false); foreach (var pdfObj in _document) { cancellationToken.ThrowIfCancellationRequested(); crossRefTable.AddPosition(offset); - WriteObject(bw, pdfObj); + WriteObject(writer, pdfObj); offset += await FlushBufferAsync(bw, buffer, stream, cancellationToken).ConfigureAwait(false); } - WriteCrossRefAndTrailer(bw, crossRefTable, offset, catalog, info); + WriteCrossRefAndTrailer(writer, crossRefTable, offset, catalog, info); await FlushBufferAsync(bw, buffer, stream, cancellationToken).ConfigureAwait(false); + _debugText?.Append(writer.DebugText); } await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/EPPlus.Export.Pdf/ExcelPdf.cs b/src/EPPlus.Export.Pdf/ExcelPdf.cs index 5459028e2..2962d0693 100644 --- a/src/EPPlus.Export.Pdf/ExcelPdf.cs +++ b/src/EPPlus.Export.Pdf/ExcelPdf.cs @@ -139,7 +139,7 @@ private void AddImageData() { foreach (var image in _dictionaries.Images) { - var img = image.Value.GetImageObject(_document.Count + 1, _documentSettings.BlackAndWhite); + var img = image.Value.GetImageObject(_document.Count + 1, _documentSettings.BlackAndWhite, _documentSettings.CompressionLevel); if (img.HasSoftMask) { var mask = PdfImageXObject.CreateSoftMask(_document.Count + 1, img.SoftMaskData, img.Width, img.Height); @@ -530,7 +530,15 @@ internal void CreatePdf(PdfDocumentSettings documentSettings, PdfDictionaries di ValidateStream(stream); PdfCatalog catalog; PdfInfoObject info; + + var sw = System.Diagnostics.Stopwatch.StartNew(); + BuildDocument(documentSettings, dictionaries, layout, out catalog, out info); + + + System.Diagnostics.Debug.WriteLine($"BuildDocument: {sw.ElapsedMilliseconds} ms"); + sw.Restart(); + // Each object is serialized to a reusable buffer and then copied to the target stream. // Cross-reference offsets are counted from the bytes written, so the target stream @@ -540,20 +548,24 @@ internal void CreatePdf(PdfDocumentSettings documentSettings, PdfDictionaries di using (var buffer = new MemoryStream()) using (var bw = new BinaryWriter(buffer, Encoding.ASCII)) { - WriteHeader(bw); + var writer = new PdfWriter(bw, _debugText != null, _documentSettings.CompressionLevel); + WriteHeader(writer); offset += FlushBuffer(bw, buffer, stream); foreach (var pdfObj in _document) { crossRefTable.AddPosition(offset); - WriteObject(bw, pdfObj); + WriteObject(writer, pdfObj); offset += FlushBuffer(bw, buffer, stream); } - WriteCrossRefAndTrailer(bw, crossRefTable, offset, catalog, info); + WriteCrossRefAndTrailer(writer, crossRefTable, offset, catalog, info); FlushBuffer(bw, buffer, stream); + _debugText?.Append(writer.DebugText); } stream.Flush(); + + System.Diagnostics.Debug.WriteLine($"Write: {sw.ElapsedMilliseconds} ms"); } // Phase 1: builds all PDF objects in memory. Pure CPU work, shared by the sync and async paths. @@ -602,27 +614,20 @@ private static void ValidateStream(Stream stream) if (!stream.CanWrite) throw new ArgumentException("The stream must be writable.", nameof(stream)); } - private void WriteHeader(BinaryWriter bw) + private void WriteHeader(PdfWriter w) { - bw.Write(Encoding.ASCII.GetBytes(Header)); - if (_debugText != null) _debugText.Append(Header); + w.Text(Header); } - private void WriteObject(BinaryWriter bw, PdfObject pdfObj) + private void WriteObject(PdfWriter w, PdfObject pdfObj) { - pdfObj.ToPdfBytes(bw); - if (_debugText != null) _debugText.Append(pdfObj.ToPdfString()); + pdfObj.Write(w); } - private void WriteCrossRefAndTrailer(BinaryWriter bw, PdfCrossRefTable crossRefTable, long offset, PdfCatalog catalog, PdfInfoObject info) + private void WriteCrossRefAndTrailer(PdfWriter w, PdfCrossRefTable crossRefTable, long offset, PdfCatalog catalog, PdfInfoObject info) { - crossRefTable.Write(bw, offset, _document.Count); - PdfTrailer.Write(bw, _document.Count, catalog.objectNumber, info.objectNumber, crossRefTable.StartPosition); - if (_debugText != null) - { - _debugText.Append(crossRefTable.Write(offset, _document.Count)); - _debugText.Append(PdfTrailer.WriteString(_document.Count, catalog.objectNumber, info.objectNumber, crossRefTable.StartPosition)); - } + crossRefTable.Write(w, offset, _document.Count); + PdfTrailer.Write(w, _document.Count, catalog.objectNumber, info.objectNumber, crossRefTable.StartPosition); } // Copies the buffered bytes to the target, resets the buffer and returns the number of bytes written. diff --git a/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs b/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs index bc155b8f4..651dca603 100644 --- a/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs +++ b/src/EPPlus.Export.Pdf/Helpers/PdfFlate.cs @@ -11,17 +11,28 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using OfficeOpenXml.Packaging.Ionic.Zlib; +using EPPlus.Export.Pdf.Settings; using System.IO; namespace EPPlus.Export.Pdf.Helpers { internal static class PdfFlate { - internal static byte[] Compress(byte[] data) + private static CompressionLevel GetCompressionLevel(PdfCompressionLevel level) + { + switch (level) + { + case PdfCompressionLevel.Fastest: return CompressionLevel.BestSpeed; + case PdfCompressionLevel.Balanced: return CompressionLevel.Default; + default: return CompressionLevel.BestCompression; + } + } + + internal static byte[] Compress(byte[] data, PdfCompressionLevel level = PdfCompressionLevel.Smallest) { using (var ms = new MemoryStream()) { - using (var zs = new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression)) + using (var zs = new ZlibStream(ms, CompressionMode.Compress, GetCompressionLevel(level))) { zs.Write(data, 0, data.Length); } @@ -29,11 +40,11 @@ internal static byte[] Compress(byte[] data) } } - internal static byte[] CompressLeaveOpen(byte[] data) + internal static byte[] CompressLeaveOpen(byte[] data, PdfCompressionLevel level = PdfCompressionLevel.Smallest) { using (var output = new MemoryStream()) { - using (var z = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) + using (var z = new ZlibStream(output, CompressionMode.Compress, GetCompressionLevel(level), true)) { z.Write(data, 0, data.Length); } diff --git a/src/EPPlus.Export.Pdf/Resources/PdfImageResource.cs b/src/EPPlus.Export.Pdf/Resources/PdfImageResource.cs index 7e7a96b8a..c0394a3e1 100644 --- a/src/EPPlus.Export.Pdf/Resources/PdfImageResource.cs +++ b/src/EPPlus.Export.Pdf/Resources/PdfImageResource.cs @@ -11,6 +11,7 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Export.Pdf.DocumentObjects; +using EPPlus.Export.Pdf.Settings; namespace EPPlus.Export.Pdf.Resources { @@ -25,10 +26,10 @@ public PdfImageResource(int labelNumber, byte[] imageBytes) ImageBytes = imageBytes; } - public PdfImageXObject GetImageObject(int objectNumber, bool blackAndWhite, int version = 0) + public PdfImageXObject GetImageObject(int objectNumber, bool blackAndWhite, PdfCompressionLevel compressionLevel, int version = 0) { this.objectNumber = objectNumber; - return new PdfImageXObject(objectNumber, ImageBytes, blackAndWhite, version); + return new PdfImageXObject(objectNumber, ImageBytes, blackAndWhite, compressionLevel, version); } } } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfCompressionLevel.cs b/src/EPPlus.Export.Pdf/Settings/PdfCompressionLevel.cs new file mode 100644 index 000000000..405158722 --- /dev/null +++ b/src/EPPlus.Export.Pdf/Settings/PdfCompressionLevel.cs @@ -0,0 +1,21 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +namespace EPPlus.Export.Pdf.Settings +{ + internal enum PdfCompressionLevel + { + Fastest, + Balanced, + Smallest + } +} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs index c44cb9ea2..0e4218856 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs @@ -32,6 +32,7 @@ internal class PdfDocumentSettings internal bool BlackAndWhite; internal string BookmarkNamePrefix; internal bool SuppressFormFieldDetection; + internal PdfCompressionLevel CompressionLevel; internal static PdfDocumentSettings From(PdfRenderSettings s) { @@ -52,6 +53,7 @@ internal static PdfDocumentSettings From(PdfRenderSettings s) BlackAndWhite = s.BlackAndWhite, BookmarkNamePrefix = s.BookmarkNamePrefix, SuppressFormFieldDetection = s.SuppressFormFieldDetection, + CompressionLevel = s.CompressionLevel, }; } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs index 7e4ce034a..cfe9c574d 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs @@ -260,6 +260,8 @@ internal double ContentScale internal string AdditionalContent; + internal PdfCompressionLevel CompressionLevel = PdfCompressionLevel.Smallest; + //DEBUG internal bool Debug = false; internal bool PrintAsText = false; diff --git a/src/EPPlus/Export/PdfExport/PdfCompressionLevel.cs b/src/EPPlus/Export/PdfExport/PdfCompressionLevel.cs new file mode 100644 index 000000000..46ffe7dc1 --- /dev/null +++ b/src/EPPlus/Export/PdfExport/PdfCompressionLevel.cs @@ -0,0 +1,28 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 27/11/2025 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +namespace OfficeOpenXml.Export.PdfExport +{ + /// + /// Controls the compression applied to PDF content streams and images. + /// More compression means a smaller file but a slower export. + /// + public enum PdfCompressionLevel + { + /// Fastest export, largest file. + Fastest, + /// A balance between export speed and file size. + Balanced, + /// Smallest file, slowest export. This is the default. + Smallest + } +} diff --git a/src/EPPlus/Export/PdfExport/PdfExportSettings.cs b/src/EPPlus/Export/PdfExport/PdfExportSettings.cs index 69f78fd73..ba4ea014c 100644 --- a/src/EPPlus/Export/PdfExport/PdfExportSettings.cs +++ b/src/EPPlus/Export/PdfExport/PdfExportSettings.cs @@ -58,5 +58,11 @@ public class PdfExportSettings /// document properties are used. /// public string Title { get; set; } + + /// + /// The compression level applied to PDF content streams and images. Trades export + /// speed against file size. Default is . + /// + public PdfCompressionLevel CompressionLevel { get; set; } = PdfCompressionLevel.Smallest; } } \ No newline at end of file diff --git a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs index 261c47e46..c307fc66c 100644 --- a/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs +++ b/src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs @@ -78,6 +78,7 @@ private static void ApplyExportSettings(PdfRenderSettings s, PdfExportSettings e //s.GposFeatures = e.GposFeatures; s.Author = e.Author; s.Title = e.Title; + s.CompressionLevel = (EPPlus.Export.Pdf.Settings.PdfCompressionLevel)e.CompressionLevel; } internal static PdfRenderSettings GetPdfSettingsForSheet(PdfRenderSettings baseSettings, ExcelPrinterSettings eps, PdfExportSettingsWorksheetOverrides overrides) From d0755b238a2bba3f322d382f4937f0d13bdadfac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AdrianParn=C3=A9us?= Date: Wed, 25 Nov 2026 15:24:37 +0100 Subject: [PATCH 7/7] Fixed conflicts and minior errors. --- .../DocumentObjects/PdfAcroForm .cs | 42 ---------------- .../DocumentObjects/PdfFormFieldObject .cs | 48 ------------------- .../Settings/PdfDocumentSettings.cs | 3 -- .../Settings/PdfRenderSettings.cs | 5 -- 4 files changed, 98 deletions(-) delete mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs delete mode 100644 src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs deleted file mode 100644 index c2cfd7ebf..000000000 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfAcroForm .cs +++ /dev/null @@ -1,42 +0,0 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - https://polyformproject.org/licenses/noncommercial/1.0.0/ - - A commercial license to use this software can be purchased at https://epplussoftware.com - ************************************************************************************************* - Date Author Change - ************************************************************************************************* - 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 - *************************************************************************************************/ -using EPPlus.Export.Pdf.Helpers; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace EPPlus.Export.Pdf.DocumentObjects -{ - // Minimal AcroForm whose only job is to declare that the document already - // has form fields (see PdfFormFieldObject). NeedAppearances is false so no - // viewer tries to regenerate appearances for the invisible field. - internal class PdfAcroForm : PdfObject - { - private readonly List fieldObjectNumbers; - - public PdfAcroForm(int objectNumber, List fieldObjectNumbers, int version = 0) - : base(objectNumber, version) - { - this.fieldObjectNumbers = fieldObjectNumbers; - } - - private string Body() - { - var fields = string.Join(" ", fieldObjectNumbers.Select(n => $"{n.ToPdfStringF0()} 0 R")); - return $"<< /Fields [ {fields} ]\n /NeedAppearances false >>"; - } - - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); - } -} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs deleted file mode 100644 index f7884f74d..000000000 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfFormFieldObject .cs +++ /dev/null @@ -1,48 +0,0 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - https://polyformproject.org/licenses/noncommercial/1.0.0/ - - A commercial license to use this software can be purchased at https://epplussoftware.com - ************************************************************************************************* - Date Author Change - ************************************************************************************************* - 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 - *************************************************************************************************/ -using EPPlus.Export.Pdf.Helpers; -using System.IO; - -namespace EPPlus.Export.Pdf.DocumentObjects -{ - // A single hidden, read-only widget/field. Its only purpose is to make the - // document count as an already-prepared AcroForm, so Acrobat's Fill & Sign - // auto-detection stands down instead of offering fillable areas over our - // gridline tables. It never renders and cannot be interacted with. - internal class PdfFormFieldObject : PdfObject - { - private readonly int pageObjectNumber; - private readonly string fieldName; - - public PdfFormFieldObject(int objectNumber, int pageObjectNumber, string fieldName = "epplus_noautofield", int version = 0) - : base(objectNumber, version) - { - this.pageObjectNumber = pageObjectNumber; - this.fieldName = fieldName; - } - - private string Body() - { - return $"<< /Type /Annot /Subtype /Widget\n" + - $" /FT /Tx\n" + - $" /T {fieldName.ToPdfTextString()}\n" + - $" /Ff 1\n" + - $" /F 2\n" + - $" /Rect [ 0 0 1 1 ]\n" + - $" /P {pageObjectNumber.ToPdfStringF0()} 0 R >>"; - } - - internal override string RenderDictionary() => Body(); - internal override void RenderDictionary(BinaryWriter bw) => WriteAscii(bw, Body()); - } -} \ No newline at end of file diff --git a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs index 6877c25e8..0e4218856 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs @@ -53,10 +53,7 @@ internal static PdfDocumentSettings From(PdfRenderSettings s) BlackAndWhite = s.BlackAndWhite, BookmarkNamePrefix = s.BookmarkNamePrefix, SuppressFormFieldDetection = s.SuppressFormFieldDetection, -<<<<<<< HEAD CompressionLevel = s.CompressionLevel, -======= ->>>>>>> develop9 }; } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs index fc32a183b..cfe9c574d 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs @@ -65,11 +65,6 @@ internal OpenTypeFontEngine FontEngine /// public bool SuppressFormFieldDetection = true; - /// - /// Set true to supress Acrobat Readers auto detecting of form fillable areas. - /// - public bool SuppressFormFieldDetection = true; - /// /// The order in how to create pages. ///