From 235734cfa1154253a5e1c95846eafcff13e24459 Mon Sep 17 00:00:00 2001 From: menes97 <38889017+menes97@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:49:30 +0300 Subject: [PATCH 1/5] Resolve PAGE and NUMPAGES fields in header/footer tables RenderHeaderFooterElementsOnPage resolved the {PAGE}/{NUMPAGES} placeholders only for header/footer paragraphs. Paragraphs inside a header/footer table were drawn with the raw placeholders (and wrapped as such in narrow cells), so the footer showed "Page {PAGE} of {NUMPAGES}". Resolve the placeholders in a copy of the table before it is measured and drawn, and measure the reserved footer height with the same page 1 of 1 convention as paragraphs. Refs #158 Co-Authored-By: Claude Opus 5.5 --- src/MiniPdf/DocxToPdfConverter.cs | 46 +++++++- .../MiniPdf.Tests/DocxToPdfConverterTests.cs | 108 ++++++++++++++++++ 2 files changed, 152 insertions(+), 2 deletions(-) diff --git a/src/MiniPdf/DocxToPdfConverter.cs b/src/MiniPdf/DocxToPdfConverter.cs index 5994684c..c25ea8b7 100644 --- a/src/MiniPdf/DocxToPdfConverter.cs +++ b/src/MiniPdf/DocxToPdfConverter.cs @@ -3782,9 +3782,11 @@ private static float EstimateElementsHeight(List elements, Conversi var colWidths = CalculateTableColumnWidths(table, effectiveTableWidth); var cellPaddingH = (table.CellMarginLeft + table.CellMarginRight) / 2; var cellPaddingV = Math.Max(0f, Math.Max(table.CellMarginTop, table.CellMarginBottom)); + // Page numbers are unknown here, so placeholders resolve as page 1 of 1. + var measuredTable = ResolveTablePagePlaceholders(table, 1, 1); for (var rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { - var row = table.Rows[rowIndex]; + var row = measuredTable.Rows[rowIndex]; var rowH = CalculateRowHeight(row, colWidths, cellPaddingH, cellPaddingV, options, table.StyleLineSpacing, table.StyleSpacingAfter) + GetRowBorderHeight(table, rowIndex); if (row.Height > 0) @@ -3966,7 +3968,8 @@ private static void RenderHeaderFooterElementsOnPage(PdfPage page, ConversionOpt } case DocxTable table: { - y = RenderHeaderFooterTable(page, options, table, y); + var effectivePageNum = sectionPageNum > 0 ? sectionPageNum : (pageIndex + 1); + y = RenderHeaderFooterTable(page, options, ResolveTablePagePlaceholders(table, effectivePageNum, totalPages), y); lastSpacingAfter = 0; isFirst = false; break; @@ -5831,6 +5834,45 @@ private static int GetWrapCharWidth(char ch, bool useCalibriWidths = true) return useCalibriWidths ? GetCalibrCharWidth(ch) : GetHelveticaCharWidth(ch); } + /// + /// Returns with {PAGE}, {PAGE:roman}, {PAGE:ROMAN} and {NUMPAGES} + /// placeholders in its cell text resolved, so that the row heights and the line wrapping of a + /// header/footer table are computed from the text that is drawn. The table itself is returned + /// when no cell carries a placeholder. + /// + private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageNum, int totalPages) + { + var hasPlaceholder = false; + foreach (var row in table.Rows) + foreach (var cell in row.Cells) + foreach (var para in cell.Paragraphs) + foreach (var run in para.Runs) + if (run.Text.Contains("{PAGE") || run.Text.Contains("{NUMPAGES}")) + hasPlaceholder = true; + if (!hasPlaceholder) + return table; + + var rows = new List(table.Rows.Count); + foreach (var row in table.Rows) + { + var cells = new List(row.Cells.Count); + foreach (var cell in row.Cells) + { + var paragraphs = new List(cell.Paragraphs.Count); + foreach (var para in cell.Paragraphs) + { + var runs = new List(para.Runs.Count); + foreach (var run in para.Runs) + runs.Add(run with { Text = ResolvePagePlaceholders(run.Text, pageNum, totalPages) }); + paragraphs.Add(para with { Runs = runs }); + } + cells.Add(cell with { Paragraphs = paragraphs }); + } + rows.Add(row with { Cells = cells }); + } + return table with { Rows = rows }; + } + /// /// Resolves {PAGE}, {PAGE:roman}, {PAGE:ROMAN}, {NUMPAGES} placeholders. /// diff --git a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs index 67b638e5..17793092 100644 --- a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs +++ b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs @@ -827,6 +827,23 @@ public void Convert_FooterPageFieldWithSwitch_RendersPageNumber() Assert.Contains("1", texts, StringComparer.Ordinal); } + [Fact] + public void Convert_FooterPageFieldsInTable_RendersPageNumbers() + { + using var docxStream = CreateDocxWithFooterPageFieldsInTable(); + + var doc = DocxToPdfConverter.Convert(docxStream); + + Assert.Equal(2, doc.Pages.Count); + for (var i = 0; i < doc.Pages.Count; i++) + { + var text = string.Concat(doc.Pages[i].TextBlocks.Select(b => b.Text)); + Assert.DoesNotContain("{PAGE}", text, StringComparison.Ordinal); + Assert.DoesNotContain("{NUMPAGES}", text, StringComparison.Ordinal); + Assert.Contains($"Page {i + 1} of 2", text, StringComparison.Ordinal); + } + } + [Fact] public void Convert_EmptyTocField_GeneratesHeadingEntries() { @@ -2036,6 +2053,97 @@ private static MemoryStream CreateDocxWithFooterPageField(string fieldInstructio return ms; } + private static MemoryStream CreateDocxWithFooterPageFieldsInTable() + { + var ms = new MemoryStream(); + + using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) + { + AddEntry(archive, "[Content_Types].xml", + """ + + + + + + + + """); + + AddEntry(archive, "_rels/.rels", + """ + + + + + """); + + AddEntry(archive, "word/_rels/document.xml.rels", + """ + + + + + """); + + AddEntry(archive, "word/document.xml", + """ + + + + First page + + Second page + + + + + + """); + + AddEntry(archive, "word/footer1.xml", + """ + + + + + + + + + + + + Document no: 1 + + + + + Page + + PAGE + + 1 + + of + + NUMPAGES + + 1 + + + + + + + + """); + } + + ms.Position = 0; + return ms; + } + private static MemoryStream CreateDocxWithEmptyTocField() { return CreateDocxFromBodyXml( From 1cb972b7ebebcfc436a3c4653921b5a216a1f4f5 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Wed, 25 Nov 2026 09:09:03 +0800 Subject: [PATCH 2/5] Fix DOCX page fields in header/footer tables --- src/MiniPdf/DocxReader.cs | 5 +- src/MiniPdf/DocxToPdfConverter.cs | 130 +++++++++++------- .../MiniPdf.Tests/DocxToPdfConverterTests.cs | 39 +++++- 3 files changed, 117 insertions(+), 57 deletions(-) diff --git a/src/MiniPdf/DocxReader.cs b/src/MiniPdf/DocxReader.cs index f095ab21..2722d973 100644 --- a/src/MiniPdf/DocxReader.cs +++ b/src/MiniPdf/DocxReader.cs @@ -1531,7 +1531,7 @@ private static void EmitPageFieldPlaceholder(string instruction, List r placeholder = instr.Contains("\\* ROMAN") ? "{PAGE:ROMAN}" : "{PAGE:roman}"; } - runs.Add(new DocxRun(placeholder, bold, italic, fontSize, color)); + runs.Add(new DocxRun(placeholder, bold, italic, fontSize, color, IsPageNumberField: true)); } private static void ExpandTocPlaceholders(List elements, DocxPageLayout? pageLayout) @@ -5338,7 +5338,8 @@ internal sealed record DocxRun( float VerticalPosition = 0, string? FootnoteId = null, PdfColor? Shading = null, - string? Link = null + string? Link = null, + bool IsPageNumberField = false ); /// Represents a footnote definition parsed from word/footnotes.xml. diff --git a/src/MiniPdf/DocxToPdfConverter.cs b/src/MiniPdf/DocxToPdfConverter.cs index c25ea8b7..526b060c 100644 --- a/src/MiniPdf/DocxToPdfConverter.cs +++ b/src/MiniPdf/DocxToPdfConverter.cs @@ -268,7 +268,8 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option // Adjust top margin when header content is taller than the default header area if (!options.MarginTopOverride.HasValue && docxDoc.HeaderElements is { Count: > 0 }) { - var headerContentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(docxDoc.HeaderElements), options, headerFooter: true); + var headerContentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(docxDoc.HeaderElements), options, + headerFooter: true, pageNum: int.MaxValue, totalPages: int.MaxValue); var headerAreaHeight = options.MarginTop - options.HeaderMargin; if (headerAreaHeight < 0) headerAreaHeight = 0; // header starts below marginTop if (headerContentHeight > headerAreaHeight) @@ -283,7 +284,8 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option // Adjust bottom margin when footer content is taller than the default footer area if (!options.MarginBottomOverride.HasValue && docxDoc.FooterElements is { Count: > 0 }) { - var footerContentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(docxDoc.FooterElements), options, headerFooter: true); + var footerContentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(docxDoc.FooterElements), options, + headerFooter: true, pageNum: int.MaxValue, totalPages: int.MaxValue); var footerTopFromBottom = options.FooterMargin + footerContentHeight; if (footerTopFromBottom > options.MarginBottom) options.MarginBottom = footerTopFromBottom; @@ -484,6 +486,28 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option var hasSectionFooters = docxDoc.SectionFooterElements is { Count: > 0 } && docxDoc.SectionFooterElements.Any(f => f is { Count: > 0 }); + var sectionPageNumbers = Enumerable.Repeat(-1, pdfDoc.Pages.Count).ToArray(); + for (int pi = 0; pi < sectionPageNumbers.Length; pi++) + { + int pageSectionIdx = 0; + for (int si = state.SectionStartPages.Count - 1; si >= 0; si--) + { + if (pi >= state.SectionStartPages[si]) + { + pageSectionIdx = si; + break; + } + } + int ancestorIdx = pageSectionIdx; + while (ancestorIdx > 0 && (ancestorIdx >= sectionLayouts.Count || sectionLayouts[ancestorIdx].PageNumStart < 0)) + ancestorIdx--; + if (ancestorIdx >= 0 && ancestorIdx < sectionLayouts.Count && sectionLayouts[ancestorIdx].PageNumStart >= 0) + { + int pagesFromAncestor = pi - state.SectionStartPages[ancestorIdx]; + sectionPageNumbers[pi] = sectionLayouts[ancestorIdx].PageNumStart + pagesFromAncestor; + } + } + if (hasHeaderElements || hasFooterElements || hasSectionFooters) { var totalPages = pdfDoc.Pages.Count; @@ -498,45 +522,33 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option bool isFirstPageOfDoc = (pi == 0); bool suppressDefaultHeader = isFirstPageOfDoc && firstPageTitlePg; bool suppressDefaultFooter = isFirstPageOfDoc && firstPageTitlePg; + int pageSectionIdx = 0; + for (int si = state.SectionStartPages.Count - 1; si >= 0; si--) + { + if (pi >= state.SectionStartPages[si]) + { + pageSectionIdx = si; + break; + } + } + var sectionPageNum = sectionPageNumbers[pi]; if (!suppressDefaultHeader && hasHeaderElements) { var headerStartY = page.Height - options.HeaderMargin; - RenderHeaderFooterElementsOnPage(page, options, docxDoc.HeaderElements!, headerStartY, pi, totalPages); + RenderHeaderFooterElementsOnPage(page, options, docxDoc.HeaderElements!, headerStartY, pi, totalPages, sectionPageNum); } else if (suppressDefaultHeader && firstPageHeaderOverride is { Count: > 0 }) { var headerStartY = page.Height - options.HeaderMargin; - RenderHeaderFooterElementsOnPage(page, options, firstPageHeaderOverride, headerStartY, pi, totalPages); + RenderHeaderFooterElementsOnPage(page, options, firstPageHeaderOverride, headerStartY, pi, totalPages, sectionPageNum); } // Determine footer elements for this page: prefer per-section, fall back to global List? pageFooterElements = null; - int sectionPageNum = -1; if (hasSectionFooters) { - // Find which section this page belongs to - int pageSectionIdx = 0; - for (int si = state.SectionStartPages.Count - 1; si >= 0; si--) - { - if (pi >= state.SectionStartPages[si]) - { - pageSectionIdx = si; - break; - } - } if (pageSectionIdx < docxDoc.SectionFooterElements!.Count) pageFooterElements = docxDoc.SectionFooterElements[pageSectionIdx]; - - // Calculate section-relative page number using PageNumStart - // Walk backward to find nearest ancestor section with PageNumStart - int ancestorIdx = pageSectionIdx; - while (ancestorIdx > 0 && (ancestorIdx >= sectionLayouts.Count || sectionLayouts[ancestorIdx].PageNumStart < 0)) - ancestorIdx--; - if (ancestorIdx >= 0 && ancestorIdx < sectionLayouts.Count && sectionLayouts[ancestorIdx].PageNumStart >= 0) - { - int pagesFromAncestor = pi - state.SectionStartPages[ancestorIdx]; - sectionPageNum = sectionLayouts[ancestorIdx].PageNumStart + pagesFromAncestor; - } } // Fall back to global footer if no section-specific footer if (pageFooterElements == null && hasFooterElements) @@ -553,7 +565,9 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option || (e is DocxParagraph pp && (pp.Runs.Any(r => !string.IsNullOrWhiteSpace(r.Text)) || pp.Images.Count > 0)))) { var trimmedFooter = TrimTrailingEmptyParagraphs(pageFooterElements); - var footerContentHeight = EstimateElementsHeight(trimmedFooter, options, headerFooter: true); + var effectivePageNum = sectionPageNum >= 0 ? sectionPageNum : pi + 1; + var footerContentHeight = EstimateElementsHeight(trimmedFooter, options, headerFooter: true, + pageNum: effectivePageNum, totalPages: totalPages); var footerStartY = options.FooterMargin + footerContentHeight; RenderHeaderFooterElementsOnPage(page, options, trimmedFooter, footerStartY, pi, totalPages, sectionPageNum); } @@ -567,18 +581,19 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option for (int pi = 0; pi < totalPages; pi++) { var page = pdfDoc.Pages[pi]; + var sectionPageNum = sectionPageNumbers[pi]; var usableW = page.Width - options.MarginLeft - options.MarginRight; if (!hasHeaderElements && docxDoc.HeaderText != null) { RenderHeaderFooterRuns(page, options, docxDoc.HeaderRuns, docxDoc.HeaderText, pi, totalPages, headerFooterFontSize, headerColor, usableW, - page.Height - options.HeaderMargin); + page.Height - options.HeaderMargin, sectionPageNum); } if (!hasFooterElements && docxDoc.FooterText != null) { RenderHeaderFooterRuns(page, options, docxDoc.FooterRuns, docxDoc.FooterText, pi, totalPages, headerFooterFontSize, headerColor, usableW, - options.FooterMargin); + options.FooterMargin, sectionPageNum); } } } @@ -592,7 +607,7 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option /// private static void RenderHeaderFooterRuns(PdfPage page, ConversionOptions options, List? runs, string plainText, - int pageIndex, int totalPages, float fontSize, PdfColor color, float usableW, float y) + int pageIndex, int totalPages, float fontSize, PdfColor color, float usableW, float y, int sectionPageNum = -1) { if (runs != null && runs.Count > 0) { @@ -600,7 +615,8 @@ private static void RenderHeaderFooterRuns(PdfPage page, ConversionOptions optio var resolvedRuns = new List<(string Text, bool Bold, bool Italic, string? FontName)>(); foreach (var run in runs) { - var text = ResolvePagePlaceholders(run.Text, pageIndex + 1, totalPages); + var pageNum = sectionPageNum >= 0 ? sectionPageNum : pageIndex + 1; + var text = ResolvePageNumberField(run, pageNum, totalPages); if (text == "\n") continue; // skip paragraph breaks for width calc resolvedRuns.Add((text, run.Bold, run.Italic, run.FontName)); } @@ -620,12 +636,9 @@ private static void RenderHeaderFooterRuns(PdfPage page, ConversionOptions optio else { // Fallback: plain text without formatting - var resolved = plainText - .Replace("{PAGE}", (pageIndex + 1).ToString()) - .Replace("{NUMPAGES}", totalPages.ToString()); - var textWidth = EstimateTextWidth(resolved, fontSize); + var textWidth = EstimateTextWidth(plainText, fontSize); var x = options.MarginLeft + (usableW - textWidth) / 2; - page.AddText(resolved, x, y, fontSize, color); + page.AddText(plainText, x, y, fontSize, color); } } @@ -2587,6 +2600,7 @@ private static List MergeConsecutiveRuns(List runs, float defa && !current.IsPageBreak && !next.IsPageBreak && !current.IsColumnBreak && !next.IsColumnBreak && current.FootnoteId == null && next.FootnoteId == null + && !current.IsPageNumberField && !next.IsPageNumberField && !current.Text.Contains('\t') && !next.Text.Contains('\t')) { // When the current run is whitespace-only, adopt the next run's @@ -3718,7 +3732,8 @@ private static List TrimTrailingEmptyParagraphs(List e /// Estimates the total height of a list of elements (paragraphs + tables) /// for header/footer sizing calculations. /// - private static float EstimateElementsHeight(List elements, ConversionOptions options, bool headerFooter = false) + private static float EstimateElementsHeight(List elements, ConversionOptions options, bool headerFooter = false, + int pageNum = 1, int totalPages = 1) { const float emuPerPt = 914400f / 72f; float totalHeight = 0; @@ -3755,15 +3770,16 @@ private static float EstimateElementsHeight(List elements, Conversi if (imgW > usableW) imgH *= usableW / imgW; totalHeight += imgH + 1f; } - var text = string.Concat(para.Runs.Select(r => r.Text)); + var text = headerFooter + ? ResolvePageNumberFields(para.Runs, pageNum, totalPages, forHeightEstimate: true) + : string.Concat(para.Runs.Select(r => r.Text)); if (!string.IsNullOrEmpty(text)) { // Header/footer paragraphs wrap at render time; reserve every line. // Floating text-box paragraphs (TextBoxWidth > 0) overlay the page and // must not grow the reserved area, so they keep the one-line estimate. - // Page numbers are unknown here, so placeholders resolve as page 1 of 1. var lineCount = headerFooter && para.TextBoxWidth <= 0 - ? WrapHeaderFooterText(para, ResolvePagePlaceholders(text, 1, 1), options, usableW).Count + ? WrapHeaderFooterText(para, text, options, usableW).Count : 1; totalHeight += lineHeight * lineCount; } @@ -3782,8 +3798,7 @@ private static float EstimateElementsHeight(List elements, Conversi var colWidths = CalculateTableColumnWidths(table, effectiveTableWidth); var cellPaddingH = (table.CellMarginLeft + table.CellMarginRight) / 2; var cellPaddingV = Math.Max(0f, Math.Max(table.CellMarginTop, table.CellMarginBottom)); - // Page numbers are unknown here, so placeholders resolve as page 1 of 1. - var measuredTable = ResolveTablePagePlaceholders(table, 1, 1); + var measuredTable = ResolveTablePagePlaceholders(table, pageNum, totalPages, forHeightEstimate: headerFooter); for (var rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { var row = measuredTable.Rows[rowIndex]; @@ -3930,9 +3945,8 @@ private static void RenderHeaderFooterElementsOnPage(PdfPage page, ConversionOpt y -= imgH + 1f; } // Render text runs (resolve page-number placeholders) - var effectivePageNum = sectionPageNum > 0 ? sectionPageNum : (pageIndex + 1); - var text = string.Concat(para.Runs.Select(r => r.Text)); - text = ResolvePagePlaceholders(text, effectivePageNum, totalPages); + var effectivePageNum = sectionPageNum >= 0 ? sectionPageNum : (pageIndex + 1); + var text = ResolvePageNumberFields(para.Runs, effectivePageNum, totalPages); if (!string.IsNullOrEmpty(text)) { var fontSize = para.FontSize > 0 ? para.FontSize : options.FontSize; @@ -3968,7 +3982,7 @@ private static void RenderHeaderFooterElementsOnPage(PdfPage page, ConversionOpt } case DocxTable table: { - var effectivePageNum = sectionPageNum > 0 ? sectionPageNum : (pageIndex + 1); + var effectivePageNum = sectionPageNum >= 0 ? sectionPageNum : (pageIndex + 1); y = RenderHeaderFooterTable(page, options, ResolveTablePagePlaceholders(table, effectivePageNum, totalPages), y); lastSpacingAfter = 0; isFirst = false; @@ -5840,14 +5854,15 @@ private static int GetWrapCharWidth(char ch, bool useCalibriWidths = true) /// header/footer table are computed from the text that is drawn. The table itself is returned /// when no cell carries a placeholder. /// - private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageNum, int totalPages) + private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageNum, int totalPages, + bool forHeightEstimate = false) { var hasPlaceholder = false; foreach (var row in table.Rows) foreach (var cell in row.Cells) foreach (var para in cell.Paragraphs) foreach (var run in para.Runs) - if (run.Text.Contains("{PAGE") || run.Text.Contains("{NUMPAGES}")) + if (run.IsPageNumberField) hasPlaceholder = true; if (!hasPlaceholder) return table; @@ -5863,7 +5878,7 @@ private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageN { var runs = new List(para.Runs.Count); foreach (var run in para.Runs) - runs.Add(run with { Text = ResolvePagePlaceholders(run.Text, pageNum, totalPages) }); + runs.Add(run with { Text = ResolvePageNumberField(run, pageNum, totalPages, forHeightEstimate) }); paragraphs.Add(para with { Runs = runs }); } cells.Add(cell with { Paragraphs = paragraphs }); @@ -5873,6 +5888,23 @@ private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageN return table with { Rows = rows }; } + private static string ResolvePageNumberFields(IEnumerable runs, int pageNum, int totalPages, + bool forHeightEstimate = false) + { + return string.Concat(runs.Select(run => ResolvePageNumberField(run, pageNum, totalPages, forHeightEstimate))); + } + + private static string ResolvePageNumberField(DocxRun run, int pageNum, int totalPages, bool forHeightEstimate = false) + { + if (!run.IsPageNumberField) + return run.Text; + + if (forHeightEstimate && (run.Text.Contains("{PAGE:roman}") || run.Text.Contains("{PAGE:ROMAN}"))) + pageNum = Math.Min(pageNum, 9999); + + return ResolvePagePlaceholders(run.Text, pageNum, totalPages); + } + /// /// Resolves {PAGE}, {PAGE:roman}, {PAGE:ROMAN}, {NUMPAGES} placeholders. /// diff --git a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs index 17793092..968b352c 100644 --- a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs +++ b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs @@ -837,10 +837,26 @@ public void Convert_FooterPageFieldsInTable_RendersPageNumbers() Assert.Equal(2, doc.Pages.Count); for (var i = 0; i < doc.Pages.Count; i++) { - var text = string.Concat(doc.Pages[i].TextBlocks.Select(b => b.Text)); - Assert.DoesNotContain("{PAGE}", text, StringComparison.Ordinal); - Assert.DoesNotContain("{NUMPAGES}", text, StringComparison.Ordinal); - Assert.Contains($"Page {i + 1} of 2", text, StringComparison.Ordinal); + var textBlocks = doc.Pages[i].TextBlocks.Select(b => b.Text).ToList(); + var text = string.Concat(textBlocks); + Assert.DoesNotContain("Page {PAGE} of {NUMPAGES}", text, StringComparison.Ordinal); + Assert.Contains($"Page {i + 1} of 2", textBlocks, StringComparer.Ordinal); + Assert.Contains("Use {PAGE} in the template", textBlocks, StringComparer.Ordinal); + } + } + + [Fact] + public void Convert_FooterPageFieldsInTable_UsesSectionStartWithoutSectionFooter() + { + using var docxStream = CreateDocxWithFooterPageFieldsInTable(pageNumStart: 0); + + var doc = DocxToPdfConverter.Convert(docxStream); + + Assert.Equal(2, doc.Pages.Count); + for (var i = 0; i < doc.Pages.Count; i++) + { + var textBlocks = doc.Pages[i].TextBlocks.Select(b => b.Text).ToList(); + Assert.Contains($"Page {i} of 2", textBlocks, StringComparer.Ordinal); } } @@ -2053,7 +2069,7 @@ private static MemoryStream CreateDocxWithFooterPageField(string fieldInstructio return ms; } - private static MemoryStream CreateDocxWithFooterPageFieldsInTable() + private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumStart = null) { var ms = new MemoryStream(); @@ -2087,7 +2103,7 @@ private static MemoryStream CreateDocxWithFooterPageFieldsInTable() """); AddEntry(archive, "word/document.xml", - """ + $""" @@ -2096,6 +2112,7 @@ private static MemoryStream CreateDocxWithFooterPageFieldsInTable() Second page + {(pageNumStart is int start ? $"" : string.Empty)} @@ -2134,6 +2151,16 @@ private static MemoryStream CreateDocxWithFooterPageFieldsInTable() + + + + Use {PAGE} in the template + + + + + + From 3059d15ace689b8476c6625a79bd6508a66dc559 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Wed, 25 Nov 2026 09:30:24 +0800 Subject: [PATCH 3/5] Measure header/footer margins after pagination --- src/MiniPdf/DocxToPdfConverter.cs | 197 +++++++++++++----- .../MiniPdf.Tests/DocxToPdfConverterTests.cs | 19 +- 2 files changed, 159 insertions(+), 57 deletions(-) diff --git a/src/MiniPdf/DocxToPdfConverter.cs b/src/MiniPdf/DocxToPdfConverter.cs index 526b060c..d0a1bc34 100644 --- a/src/MiniPdf/DocxToPdfConverter.cs +++ b/src/MiniPdf/DocxToPdfConverter.cs @@ -150,6 +150,8 @@ internal sealed class ConversionOptions public bool CollapseParagraphSpacing { get; set; } = true; internal bool LegacyTableIndent { get; set; } + + internal ConversionOptions Clone() => (ConversionOptions)MemberwiseClone(); } /// @@ -221,6 +223,13 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option options.CollapseParagraphSpacing = docxDoc.CompatibilityMode > 12; options.LegacyTableIndent = docxDoc.CompatibilityMode <= 14; + return Convert(docxDoc, options); + } + + private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions options, + float[]? minimumTopMargins = null, float[]? minimumBottomMargins = null, + int? previousPageCount = null, int layoutPass = 0) + { var pdfDoc = new PdfDocument(); // Pass preferred CJK font from DOCX to PDF writer for correct font selection @@ -243,6 +252,7 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option // Apply first section's layout (or body layout as fallback) if (sectionLayouts.Count > 0) ApplyPageLayout(options, sectionLayouts[0]); + ApplyMinimumMargins(options, 0, minimumTopMargins, minimumBottomMargins); // Pre-process: apply contextualSpacing rules — suppress spacing between // same-style consecutive paragraphs when either has contextualSpacing set. @@ -265,32 +275,6 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option var state = new RenderState(pdfDoc, options); - // Adjust top margin when header content is taller than the default header area - if (!options.MarginTopOverride.HasValue && docxDoc.HeaderElements is { Count: > 0 }) - { - var headerContentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(docxDoc.HeaderElements), options, - headerFooter: true, pageNum: int.MaxValue, totalPages: int.MaxValue); - var headerAreaHeight = options.MarginTop - options.HeaderMargin; - if (headerAreaHeight < 0) headerAreaHeight = 0; // header starts below marginTop - if (headerContentHeight > headerAreaHeight) - { - // Preserve a reasonable gap between header area and body content. - // When headerMargin > marginTop (header below nominal body start), - // use half the original top margin as a gap, which approximates Word behavior. - var gap = headerAreaHeight > 0 ? headerAreaHeight : Math.Max(6f, options.MarginTop / 2f); - options.MarginTop = options.HeaderMargin + headerContentHeight + gap; - } - } - // Adjust bottom margin when footer content is taller than the default footer area - if (!options.MarginBottomOverride.HasValue && docxDoc.FooterElements is { Count: > 0 }) - { - var footerContentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(docxDoc.FooterElements), options, - headerFooter: true, pageNum: int.MaxValue, totalPages: int.MaxValue); - var footerTopFromBottom = options.FooterMargin + footerContentHeight; - if (footerTopFromBottom > options.MarginBottom) - options.MarginBottom = footerTopFromBottom; - } - state.EnsurePage(); // Record section 0 start page state.SectionStartPages.Add(0); @@ -350,6 +334,7 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option state.ExitMultiColumnSection(); ApplyPageLayout(state.Options, nextLayout); + ApplyMinimumMargins(state.Options, sectionIndex, minimumTopMargins, minimumBottomMargins); // Continuous sections don't force a new page if (nextLayout.SectionType == "continuous") @@ -475,18 +460,15 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option // Render headers and footers text on all pages // When full elements are available, use them; otherwise fall back to text-only rendering. // Footer/header elements that are all empty (e.g., content is in text boxes) are treated as absent. - var hasHeaderElements = docxDoc.HeaderElements is { Count: > 0 } - && docxDoc.HeaderElements.Any(e => e is DocxTable - || (e is DocxParagraph p && (p.Runs.Any(r => !string.IsNullOrWhiteSpace(r.Text)) || p.Images.Count > 0))); - var hasFooterElements = docxDoc.FooterElements is { Count: > 0 } - && docxDoc.FooterElements.Any(e => e is DocxTable - || (e is DocxParagraph p && (p.Runs.Any(r => !string.IsNullOrWhiteSpace(r.Text)) || p.Images.Count > 0))); + var hasHeaderElements = HasHeaderFooterContent(docxDoc.HeaderElements); + var hasFooterElements = HasHeaderFooterContent(docxDoc.FooterElements); // Check for per-section footer elements var hasSectionFooters = docxDoc.SectionFooterElements is { Count: > 0 } && docxDoc.SectionFooterElements.Any(f => f is { Count: > 0 }); var sectionPageNumbers = Enumerable.Repeat(-1, pdfDoc.Pages.Count).ToArray(); + var sectionPageIndexes = new int[pdfDoc.Pages.Count]; for (int pi = 0; pi < sectionPageNumbers.Length; pi++) { int pageSectionIdx = 0; @@ -498,6 +480,7 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option break; } } + sectionPageIndexes[pi] = pageSectionIdx; int ancestorIdx = pageSectionIdx; while (ancestorIdx > 0 && (ancestorIdx >= sectionLayouts.Count || sectionLayouts[ancestorIdx].PageNumStart < 0)) ancestorIdx--; @@ -508,6 +491,18 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option } } + var requiredMargins = EstimateHeaderFooterMargins(docxDoc, options, sectionLayouts, + sectionPageIndexes, sectionPageNumbers, pdfDoc.Pages.Count, + minimumTopMargins, minimumBottomMargins, hasHeaderElements, hasFooterElements, hasSectionFooters); + var pageCountChanged = previousPageCount.HasValue && previousPageCount.Value != pdfDoc.Pages.Count; + if (requiredMargins.Expanded || pageCountChanged) + { + if (layoutPass >= 16) + throw new InvalidOperationException("Header/footer margin and page-count layout did not stabilize."); + return Convert(docxDoc, options, requiredMargins.TopMargins, requiredMargins.BottomMargins, + pdfDoc.Pages.Count, layoutPass + 1); + } + if (hasHeaderElements || hasFooterElements || hasSectionFooters) { var totalPages = pdfDoc.Pages.Count; @@ -522,15 +517,7 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option bool isFirstPageOfDoc = (pi == 0); bool suppressDefaultHeader = isFirstPageOfDoc && firstPageTitlePg; bool suppressDefaultFooter = isFirstPageOfDoc && firstPageTitlePg; - int pageSectionIdx = 0; - for (int si = state.SectionStartPages.Count - 1; si >= 0; si--) - { - if (pi >= state.SectionStartPages[si]) - { - pageSectionIdx = si; - break; - } - } + var pageSectionIdx = sectionPageIndexes[pi]; var sectionPageNum = sectionPageNumbers[pi]; if (!suppressDefaultHeader && hasHeaderElements) { @@ -561,8 +548,7 @@ internal static PdfDocument Convert(Stream docxStream, ConversionOptions? option } if (pageFooterElements is { Count: > 0 } - && pageFooterElements.Any(e => e is DocxTable - || (e is DocxParagraph pp && (pp.Runs.Any(r => !string.IsNullOrWhiteSpace(r.Text)) || pp.Images.Count > 0)))) + && HasHeaderFooterContent(pageFooterElements)) { var trimmedFooter = TrimTrailingEmptyParagraphs(pageFooterElements); var effectivePageNum = sectionPageNum >= 0 ? sectionPageNum : pi + 1; @@ -3728,6 +3714,112 @@ private static List TrimTrailingEmptyParagraphs(List e return trimmed; } + private static bool HasHeaderFooterContent(List? elements) + { + return elements is { Count: > 0 } + && elements.Any(e => e is DocxTable + || (e is DocxParagraph p && (p.Runs.Any(r => !string.IsNullOrWhiteSpace(r.Text)) || p.Images.Count > 0))); + } + + private static void ApplyMinimumMargins(ConversionOptions options, int sectionIndex, + float[]? minimumTopMargins, float[]? minimumBottomMargins) + { + if (!options.MarginTopOverride.HasValue && minimumTopMargins is not null && sectionIndex < minimumTopMargins.Length) + options.MarginTop = Math.Max(options.MarginTop, minimumTopMargins[sectionIndex]); + if (!options.MarginBottomOverride.HasValue && minimumBottomMargins is not null && sectionIndex < minimumBottomMargins.Length) + options.MarginBottom = Math.Max(options.MarginBottom, minimumBottomMargins[sectionIndex]); + } + + private static ConversionOptions CloneConversionOptions(ConversionOptions options) + { + return options.Clone(); + } + + private static (float[] TopMargins, float[] BottomMargins, bool Expanded) EstimateHeaderFooterMargins( + DocxDocument docxDoc, ConversionOptions options, IReadOnlyList sectionLayouts, + int[] sectionPageIndexes, int[] sectionPageNumbers, int totalPages, + float[]? minimumTopMargins, float[]? minimumBottomMargins, + bool hasHeaderElements, bool hasFooterElements, bool hasSectionFooters) + { + var sectionCount = Math.Max(1, sectionLayouts.Count); + var sectionOptions = new ConversionOptions[sectionCount]; + var topMargins = new float[sectionCount]; + var bottomMargins = new float[sectionCount]; + for (var si = 0; si < sectionCount; si++) + { + var sectionOptionsForMeasure = CloneConversionOptions(options); + if (si < sectionLayouts.Count) + ApplyPageLayout(sectionOptionsForMeasure, sectionLayouts[si]); + ApplyMinimumMargins(sectionOptionsForMeasure, si, minimumTopMargins, minimumBottomMargins); + sectionOptions[si] = sectionOptionsForMeasure; + topMargins[si] = sectionOptionsForMeasure.MarginTop; + bottomMargins[si] = sectionOptionsForMeasure.MarginBottom; + } + + if (!hasHeaderElements && !hasFooterElements && !hasSectionFooters) + return (topMargins, bottomMargins, false); + + var expanded = false; + var firstPageTitlePg = docxDoc.PageLayout?.TitlePg == true; + for (var pi = 0; pi < totalPages; pi++) + { + var sectionIndex = sectionPageIndexes[pi]; + if (sectionIndex >= sectionCount) + sectionIndex = sectionCount - 1; + var sectionOptionsForMeasure = sectionOptions[sectionIndex]; + var pageNum = sectionPageNumbers[pi] >= 0 ? sectionPageNumbers[pi] : pi + 1; + var suppressDefault = pi == 0 && firstPageTitlePg; + + List? headerElements = null; + if (!suppressDefault && hasHeaderElements) + headerElements = docxDoc.HeaderElements; + else if (suppressDefault && docxDoc.FirstPageHeaderElements is { Count: > 0 }) + headerElements = docxDoc.FirstPageHeaderElements; + + if (HasHeaderFooterContent(headerElements)) + { + var contentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(headerElements!), + sectionOptionsForMeasure, headerFooter: true, pageNum: pageNum, totalPages: totalPages); + var headerAreaHeight = Math.Max(0f, sectionOptionsForMeasure.MarginTop - sectionOptionsForMeasure.HeaderMargin); + if (!options.MarginTopOverride.HasValue && contentHeight > headerAreaHeight) + { + var gap = headerAreaHeight > 0 + ? headerAreaHeight + : Math.Max(6f, sectionOptionsForMeasure.MarginTop / 2f); + var requiredTop = sectionOptionsForMeasure.HeaderMargin + contentHeight + gap; + if (requiredTop > topMargins[sectionIndex] + 0.01f) + { + topMargins[sectionIndex] = requiredTop; + expanded = true; + } + } + } + + List? footerElements = null; + if (hasSectionFooters && sectionIndex < docxDoc.SectionFooterElements!.Count) + footerElements = docxDoc.SectionFooterElements[sectionIndex]; + if (footerElements == null && hasFooterElements) + footerElements = docxDoc.FooterElements; + if (suppressDefault) + footerElements = docxDoc.FirstPageFooterElements is { Count: > 0 } + ? docxDoc.FirstPageFooterElements : null; + + if (HasHeaderFooterContent(footerElements)) + { + var contentHeight = EstimateElementsHeight(TrimTrailingEmptyParagraphs(footerElements!), + sectionOptionsForMeasure, headerFooter: true, pageNum: pageNum, totalPages: totalPages); + var requiredBottom = sectionOptionsForMeasure.FooterMargin + contentHeight; + if (!options.MarginBottomOverride.HasValue && requiredBottom > bottomMargins[sectionIndex] + 0.01f) + { + bottomMargins[sectionIndex] = requiredBottom; + expanded = true; + } + } + } + + return (topMargins, bottomMargins, expanded); + } + /// /// Estimates the total height of a list of elements (paragraphs + tables) /// for header/footer sizing calculations. @@ -3771,7 +3863,7 @@ private static float EstimateElementsHeight(List elements, Conversi totalHeight += imgH + 1f; } var text = headerFooter - ? ResolvePageNumberFields(para.Runs, pageNum, totalPages, forHeightEstimate: true) + ? ResolvePageNumberFields(para.Runs, pageNum, totalPages) : string.Concat(para.Runs.Select(r => r.Text)); if (!string.IsNullOrEmpty(text)) { @@ -3798,7 +3890,7 @@ private static float EstimateElementsHeight(List elements, Conversi var colWidths = CalculateTableColumnWidths(table, effectiveTableWidth); var cellPaddingH = (table.CellMarginLeft + table.CellMarginRight) / 2; var cellPaddingV = Math.Max(0f, Math.Max(table.CellMarginTop, table.CellMarginBottom)); - var measuredTable = ResolveTablePagePlaceholders(table, pageNum, totalPages, forHeightEstimate: headerFooter); + var measuredTable = ResolveTablePagePlaceholders(table, pageNum, totalPages); for (var rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { var row = measuredTable.Rows[rowIndex]; @@ -5854,8 +5946,7 @@ private static int GetWrapCharWidth(char ch, bool useCalibriWidths = true) /// header/footer table are computed from the text that is drawn. The table itself is returned /// when no cell carries a placeholder. /// - private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageNum, int totalPages, - bool forHeightEstimate = false) + private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageNum, int totalPages) { var hasPlaceholder = false; foreach (var row in table.Rows) @@ -5878,7 +5969,7 @@ private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageN { var runs = new List(para.Runs.Count); foreach (var run in para.Runs) - runs.Add(run with { Text = ResolvePageNumberField(run, pageNum, totalPages, forHeightEstimate) }); + runs.Add(run with { Text = ResolvePageNumberField(run, pageNum, totalPages) }); paragraphs.Add(para with { Runs = runs }); } cells.Add(cell with { Paragraphs = paragraphs }); @@ -5888,20 +5979,16 @@ private static DocxTable ResolveTablePagePlaceholders(DocxTable table, int pageN return table with { Rows = rows }; } - private static string ResolvePageNumberFields(IEnumerable runs, int pageNum, int totalPages, - bool forHeightEstimate = false) + private static string ResolvePageNumberFields(IEnumerable runs, int pageNum, int totalPages) { - return string.Concat(runs.Select(run => ResolvePageNumberField(run, pageNum, totalPages, forHeightEstimate))); + return string.Concat(runs.Select(run => ResolvePageNumberField(run, pageNum, totalPages))); } - private static string ResolvePageNumberField(DocxRun run, int pageNum, int totalPages, bool forHeightEstimate = false) + private static string ResolvePageNumberField(DocxRun run, int pageNum, int totalPages) { if (!run.IsPageNumberField) return run.Text; - if (forHeightEstimate && (run.Text.Contains("{PAGE:roman}") || run.Text.Contains("{PAGE:ROMAN}"))) - pageNum = Math.Min(pageNum, 9999); - return ResolvePagePlaceholders(run.Text, pageNum, totalPages); } diff --git a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs index 968b352c..fb084f9f 100644 --- a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs +++ b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs @@ -839,7 +839,8 @@ public void Convert_FooterPageFieldsInTable_RendersPageNumbers() { var textBlocks = doc.Pages[i].TextBlocks.Select(b => b.Text).ToList(); var text = string.Concat(textBlocks); - Assert.DoesNotContain("Page {PAGE} of {NUMPAGES}", text, StringComparison.Ordinal); + Assert.DoesNotContain("Page {PAGE}", text, StringComparison.Ordinal); + Assert.DoesNotContain("of {NUMPAGES}", text, StringComparison.Ordinal); Assert.Contains($"Page {i + 1} of 2", textBlocks, StringComparer.Ordinal); Assert.Contains("Use {PAGE} in the template", textBlocks, StringComparer.Ordinal); } @@ -860,6 +861,17 @@ public void Convert_FooterPageFieldsInTable_UsesSectionStartWithoutSectionFooter } } + [Fact] + public void Convert_FooterPageFieldsInTable_PreservesBodyWhenResolvedFooterFits() + { + using var docxStream = CreateDocxWithFooterPageFieldsInTable(bodyParagraphCount: 42); + + var doc = DocxToPdfConverter.Convert(docxStream); + + Assert.Equal(2, doc.Pages.Count); + Assert.Equal(42, doc.Pages[0].TextBlocks.Count(b => b.Text == "Body line.")); + } + [Fact] public void Convert_EmptyTocField_GeneratesHeadingEntries() { @@ -2069,9 +2081,11 @@ private static MemoryStream CreateDocxWithFooterPageField(string fieldInstructio return ms; } - private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumStart = null) + private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumStart = null, int bodyParagraphCount = 0) { var ms = new MemoryStream(); + var bodyParagraphs = string.Concat(Enumerable.Repeat( + "Body line.", bodyParagraphCount)); using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) { @@ -2108,6 +2122,7 @@ private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumSt First page + {bodyParagraphs} Second page From 8a9dac178e0929ca23751a7613aa454761c211fb Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Wed, 25 Nov 2026 09:43:49 +0800 Subject: [PATCH 4/5] Honor section layouts for header and footer rendering --- src/MiniPdf/DocxToPdfConverter.cs | 99 ++++++++++++++++++------------- 1 file changed, 58 insertions(+), 41 deletions(-) diff --git a/src/MiniPdf/DocxToPdfConverter.cs b/src/MiniPdf/DocxToPdfConverter.cs index d0a1bc34..5dbaa321 100644 --- a/src/MiniPdf/DocxToPdfConverter.cs +++ b/src/MiniPdf/DocxToPdfConverter.cs @@ -349,7 +349,7 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio // from the closing section so it does not shift the next section's // first content downward on the new page. state.PendingVerticalSpace = 0; - state.ForceNewPage(); + state.ForceNewPage(state.Options.MarginBottom); state.SectionStartSpacingAfter = sectionSpacingAfter; if (nextLayout.ColumnCount > 1) state.EnterMultiColumnSection(nextLayout.ColumnCount, nextLayout.ColumnSpacing, nextLayout.ColumnWidths, nextLayout.ColumnGaps); @@ -425,6 +425,8 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio } } + var sectionOptions = CreateSectionOptions(options, sectionLayouts, minimumTopMargins, minimumBottomMargins); + // Render header/footer background shapes on all pages. if (docxDoc.HeaderShapes is { Count: > 0 } || docxDoc.FooterShapes is { Count: > 0 } || docxDoc.HeaderFooterImages is { Count: > 0 }) @@ -433,23 +435,26 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio for (int pi = 0; pi < totalPages; pi++) { var page = pdfDoc.Pages[pi]; + var pageSectionIndex = GetPageSectionIndex(state.SectionStartPages, pi); + var renderSectionIndex = Math.Min(pageSectionIndex, sectionOptions.Length - 1); + var pageOptions = sectionOptions[renderSectionIndex]; if (docxDoc.HeaderShapes is { Count: > 0 }) { foreach (var shape in docxDoc.HeaderShapes) - RenderHeaderFooterShape(page, options, shape); + RenderHeaderFooterShape(page, pageOptions, shape); } if (docxDoc.FooterShapes is { Count: > 0 }) { foreach (var shape in docxDoc.FooterShapes) - RenderHeaderFooterShape(page, options, shape); + RenderHeaderFooterShape(page, pageOptions, shape); } if (docxDoc.HeaderFooterImages is { Count: > 0 }) { foreach (var img in docxDoc.HeaderFooterImages) - RenderHeaderFooterImage(page, options, img); + RenderHeaderFooterImage(page, pageOptions, img); } } } @@ -471,15 +476,7 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio var sectionPageIndexes = new int[pdfDoc.Pages.Count]; for (int pi = 0; pi < sectionPageNumbers.Length; pi++) { - int pageSectionIdx = 0; - for (int si = state.SectionStartPages.Count - 1; si >= 0; si--) - { - if (pi >= state.SectionStartPages[si]) - { - pageSectionIdx = si; - break; - } - } + var pageSectionIdx = GetPageSectionIndex(state.SectionStartPages, pi); sectionPageIndexes[pi] = pageSectionIdx; int ancestorIdx = pageSectionIdx; while (ancestorIdx > 0 && (ancestorIdx >= sectionLayouts.Count || sectionLayouts[ancestorIdx].PageNumStart < 0)) @@ -491,9 +488,9 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio } } - var requiredMargins = EstimateHeaderFooterMargins(docxDoc, options, sectionLayouts, + var requiredMargins = EstimateHeaderFooterMargins(docxDoc, options, sectionOptions, sectionPageIndexes, sectionPageNumbers, pdfDoc.Pages.Count, - minimumTopMargins, minimumBottomMargins, hasHeaderElements, hasFooterElements, hasSectionFooters); + hasHeaderElements, hasFooterElements, hasSectionFooters); var pageCountChanged = previousPageCount.HasValue && previousPageCount.Value != pdfDoc.Pages.Count; if (requiredMargins.Expanded || pageCountChanged) { @@ -518,16 +515,18 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio bool suppressDefaultHeader = isFirstPageOfDoc && firstPageTitlePg; bool suppressDefaultFooter = isFirstPageOfDoc && firstPageTitlePg; var pageSectionIdx = sectionPageIndexes[pi]; + var renderSectionIndex = Math.Min(pageSectionIdx, sectionOptions.Length - 1); + var pageOptions = sectionOptions[renderSectionIndex]; var sectionPageNum = sectionPageNumbers[pi]; if (!suppressDefaultHeader && hasHeaderElements) { - var headerStartY = page.Height - options.HeaderMargin; - RenderHeaderFooterElementsOnPage(page, options, docxDoc.HeaderElements!, headerStartY, pi, totalPages, sectionPageNum); + var headerStartY = page.Height - pageOptions.HeaderMargin; + RenderHeaderFooterElementsOnPage(page, pageOptions, docxDoc.HeaderElements!, headerStartY, pi, totalPages, sectionPageNum); } else if (suppressDefaultHeader && firstPageHeaderOverride is { Count: > 0 }) { - var headerStartY = page.Height - options.HeaderMargin; - RenderHeaderFooterElementsOnPage(page, options, firstPageHeaderOverride, headerStartY, pi, totalPages, sectionPageNum); + var headerStartY = page.Height - pageOptions.HeaderMargin; + RenderHeaderFooterElementsOnPage(page, pageOptions, firstPageHeaderOverride, headerStartY, pi, totalPages, sectionPageNum); } // Determine footer elements for this page: prefer per-section, fall back to global @@ -552,10 +551,10 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio { var trimmedFooter = TrimTrailingEmptyParagraphs(pageFooterElements); var effectivePageNum = sectionPageNum >= 0 ? sectionPageNum : pi + 1; - var footerContentHeight = EstimateElementsHeight(trimmedFooter, options, headerFooter: true, + var footerContentHeight = EstimateElementsHeight(trimmedFooter, pageOptions, headerFooter: true, pageNum: effectivePageNum, totalPages: totalPages); - var footerStartY = options.FooterMargin + footerContentHeight; - RenderHeaderFooterElementsOnPage(page, options, trimmedFooter, footerStartY, pi, totalPages, sectionPageNum); + var footerStartY = pageOptions.FooterMargin + footerContentHeight; + RenderHeaderFooterElementsOnPage(page, pageOptions, trimmedFooter, footerStartY, pi, totalPages, sectionPageNum); } } } @@ -567,19 +566,21 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio for (int pi = 0; pi < totalPages; pi++) { var page = pdfDoc.Pages[pi]; + var renderSectionIndex = Math.Min(sectionPageIndexes[pi], sectionOptions.Length - 1); + var pageOptions = sectionOptions[renderSectionIndex]; var sectionPageNum = sectionPageNumbers[pi]; - var usableW = page.Width - options.MarginLeft - options.MarginRight; + var usableW = page.Width - pageOptions.MarginLeft - pageOptions.MarginRight; if (!hasHeaderElements && docxDoc.HeaderText != null) { - RenderHeaderFooterRuns(page, options, docxDoc.HeaderRuns, docxDoc.HeaderText, + RenderHeaderFooterRuns(page, pageOptions, docxDoc.HeaderRuns, docxDoc.HeaderText, pi, totalPages, headerFooterFontSize, headerColor, usableW, - page.Height - options.HeaderMargin, sectionPageNum); + page.Height - pageOptions.HeaderMargin, sectionPageNum); } if (!hasFooterElements && docxDoc.FooterText != null) { - RenderHeaderFooterRuns(page, options, docxDoc.FooterRuns, docxDoc.FooterText, + RenderHeaderFooterRuns(page, pageOptions, docxDoc.FooterRuns, docxDoc.FooterText, pi, totalPages, headerFooterFontSize, headerColor, usableW, - options.FooterMargin, sectionPageNum); + pageOptions.FooterMargin, sectionPageNum); } } } @@ -925,10 +926,12 @@ public void AdvanceY(float amount) HasRenderedAnyContent = true; } - public void ForceNewPage() + public void ForceNewPage(float? nextBaseMarginBottom = null) { // Render footnotes before leaving the current page RenderPageFootnotes(); + if (nextBaseMarginBottom.HasValue) + BaseMarginBottom = nextBaseMarginBottom.Value; // Restore margins if in multi-column mode if (ColumnCount > 1) @@ -3730,31 +3733,45 @@ private static void ApplyMinimumMargins(ConversionOptions options, int sectionIn options.MarginBottom = Math.Max(options.MarginBottom, minimumBottomMargins[sectionIndex]); } + private static int GetPageSectionIndex(IReadOnlyList sectionStartPages, int pageIndex) + { + for (var si = sectionStartPages.Count - 1; si >= 0; si--) + { + if (pageIndex >= sectionStartPages[si]) + return si; + } + return 0; + } + private static ConversionOptions CloneConversionOptions(ConversionOptions options) { return options.Clone(); } - private static (float[] TopMargins, float[] BottomMargins, bool Expanded) EstimateHeaderFooterMargins( - DocxDocument docxDoc, ConversionOptions options, IReadOnlyList sectionLayouts, - int[] sectionPageIndexes, int[] sectionPageNumbers, int totalPages, - float[]? minimumTopMargins, float[]? minimumBottomMargins, - bool hasHeaderElements, bool hasFooterElements, bool hasSectionFooters) + private static ConversionOptions[] CreateSectionOptions(ConversionOptions options, + IReadOnlyList sectionLayouts, float[]? minimumTopMargins, float[]? minimumBottomMargins) { var sectionCount = Math.Max(1, sectionLayouts.Count); var sectionOptions = new ConversionOptions[sectionCount]; - var topMargins = new float[sectionCount]; - var bottomMargins = new float[sectionCount]; for (var si = 0; si < sectionCount; si++) { - var sectionOptionsForMeasure = CloneConversionOptions(options); + var sectionOptionsForPage = CloneConversionOptions(options); if (si < sectionLayouts.Count) - ApplyPageLayout(sectionOptionsForMeasure, sectionLayouts[si]); - ApplyMinimumMargins(sectionOptionsForMeasure, si, minimumTopMargins, minimumBottomMargins); - sectionOptions[si] = sectionOptionsForMeasure; - topMargins[si] = sectionOptionsForMeasure.MarginTop; - bottomMargins[si] = sectionOptionsForMeasure.MarginBottom; + ApplyPageLayout(sectionOptionsForPage, sectionLayouts[si]); + ApplyMinimumMargins(sectionOptionsForPage, si, minimumTopMargins, minimumBottomMargins); + sectionOptions[si] = sectionOptionsForPage; } + return sectionOptions; + } + + private static (float[] TopMargins, float[] BottomMargins, bool Expanded) EstimateHeaderFooterMargins( + DocxDocument docxDoc, ConversionOptions options, ConversionOptions[] sectionOptions, + int[] sectionPageIndexes, int[] sectionPageNumbers, int totalPages, + bool hasHeaderElements, bool hasFooterElements, bool hasSectionFooters) + { + var sectionCount = sectionOptions.Length; + var topMargins = sectionOptions.Select(o => o.MarginTop).ToArray(); + var bottomMargins = sectionOptions.Select(o => o.MarginBottom).ToArray(); if (!hasHeaderElements && !hasFooterElements && !hasSectionFooters) return (topMargins, bottomMargins, false); From d2f6e03b305b287e7e3d5b17acc84e14469d5489 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Wed, 25 Nov 2026 10:00:48 +0800 Subject: [PATCH 5/5] Keep continuous-section footer margins across pages --- src/MiniPdf/DocxToPdfConverter.cs | 3 ++ .../MiniPdf.Tests/DocxToPdfConverterTests.cs | 39 ++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/MiniPdf/DocxToPdfConverter.cs b/src/MiniPdf/DocxToPdfConverter.cs index 5dbaa321..32732eb3 100644 --- a/src/MiniPdf/DocxToPdfConverter.cs +++ b/src/MiniPdf/DocxToPdfConverter.cs @@ -339,6 +339,9 @@ private static PdfDocument Convert(DocxDocument docxDoc, ConversionOptions optio // Continuous sections don't force a new page if (nextLayout.SectionType == "continuous") { + state.BaseMarginBottom = state.Options.MarginBottom; + state.Options.MarginBottom = state.BaseMarginBottom + state.FootnoteReservedHeight; + // Enter multi-column if applicable if (nextLayout.ColumnCount > 1) state.EnterMultiColumnSection(nextLayout.ColumnCount, nextLayout.ColumnSpacing, nextLayout.ColumnWidths, nextLayout.ColumnGaps); diff --git a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs index fb084f9f..5992a731 100644 --- a/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs +++ b/tests/MiniPdf.Tests/DocxToPdfConverterTests.cs @@ -872,6 +872,31 @@ public void Convert_FooterPageFieldsInTable_PreservesBodyWhenResolvedFooterFits( Assert.Equal(42, doc.Pages[0].TextBlocks.Count(b => b.Text == "Body line.")); } + [Fact] + public void Convert_ContinuousSectionKeepsFooterMarginAfterPageBreaks() + { + using var docxStream = CreateDocxWithFooterPageFieldsInTable( + bodyParagraphCount: 8, continuousSection: true, secondPageParagraphCount: 55); + + var doc = DocxToPdfConverter.Convert(docxStream); + + Assert.True(doc.Pages.Count >= 3); + Assert.Contains(doc.Pages.Skip(1), page => page.TextBlocks.Any(b => b.Text == "After break line.")); + for (var pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++) + { + var page = doc.Pages[pageIndex]; + var footerBlocks = page.TextBlocks + .Where(b => b.Text.StartsWith("Page ", StringComparison.Ordinal)) + .ToList(); + Assert.NotEmpty(footerBlocks); + var footerTop = footerBlocks + .Select(b => b.Y + b.FontSize) + .Max(); + foreach (var bodyLine in page.TextBlocks.Where(b => b.Text is "Body line." or "After break line.")) + Assert.True(bodyLine.Y > footerTop + 4f, $"Body text overlaps the footer on page {pageIndex + 1}."); + } + } + [Fact] public void Convert_EmptyTocField_GeneratesHeadingEntries() { @@ -2081,11 +2106,20 @@ private static MemoryStream CreateDocxWithFooterPageField(string fieldInstructio return ms; } - private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumStart = null, int bodyParagraphCount = 0) + private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumStart = null, int bodyParagraphCount = 0, + bool continuousSection = false, int secondPageParagraphCount = 0) { var ms = new MemoryStream(); var bodyParagraphs = string.Concat(Enumerable.Repeat( "Body line.", bodyParagraphCount)); + var afterPageBreakParagraphs = string.Concat(Enumerable.Repeat( + "After break line.", secondPageParagraphCount)); + var continuousSectionBreak = continuousSection + ? "" + : string.Empty; + var continuousSectionLayout = continuousSection + ? "" + : string.Empty; using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) { @@ -2122,12 +2156,15 @@ private static MemoryStream CreateDocxWithFooterPageFieldsInTable(int? pageNumSt First page + {continuousSectionBreak} {bodyParagraphs} Second page + {afterPageBreakParagraphs} {(pageNumStart is int start ? $"" : string.Empty)} + {continuousSectionLayout}