Files
QWERTYkez.OpenXmlProcessors/QWERTYkez.WordProcessor/MultiReplace.cs
T

496 lines
21 KiB
C#
Raw Normal View History

2026-06-05 15:58:03 +07:00
namespace QWERTYkez.WordProcessor;
/// <summary>
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение
/// остаётся в текущем параграфе, а последующие создают новые.
/// Текст между вхождениями и после последнего сохраняется в соответствующих параграфах.
2026-07-21 16:43:59 +07:00
/// Поддерживает разрывы страниц и смену ориентации (альбомная/книжная) через <see cref="ReplaceItem.SplitValue"/>.
2026-06-05 15:58:03 +07:00
/// </summary>
internal static class MultiReplaceExt
{
2026-07-21 16:43:59 +07:00
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (для Body) ----------
2026-06-05 15:58:03 +07:00
#region Body.Replace с одним ключом
internal static void Replace(this Body body, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
{
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
2026-08-03 16:31:54 +07:00
body.Replace(new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } }, comparisonType);
2026-06-05 15:58:03 +07:00
}
internal static void Replace(this Body body, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
{
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
2026-08-03 16:31:54 +07:00
body.Replace(new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } }, comparisonType);
2026-06-05 15:58:03 +07:00
}
#endregion
#region Body.Replace со словарём массивов
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
{
if (body is null || replacements is null) return;
2026-08-03 16:31:54 +07:00
ReplaceInBody(body, replacements, null, comparisonType);
2026-06-05 15:58:03 +07:00
}
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType)
{
if (body is null || replacements is null) return;
2026-08-03 16:31:54 +07:00
ReplaceInBody(body, null, replacements, comparisonType);
}
private static void ReplaceInBody(
Body body,
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
StringComparison comparisonType)
{
2026-06-05 15:58:03 +07:00
var paragraphs = body.Elements<Paragraph>().ToList();
for (int i = paragraphs.Count - 1; i >= 0; i--)
{
var p = paragraphs[i];
if (p?.Parent is null) continue;
2026-08-03 16:31:54 +07:00
var newParas = ProcessMultiReplacements(p, stringReplacements, itemReplacements, comparisonType);
if (newParas is { Count: > 0 })
2026-06-05 15:58:03 +07:00
ParagraphReplacer.ReplaceParagraph(p, newParas);
}
}
#endregion
#region Paragraph.ReplaceWithMultiple (один ключ)
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
{
2026-08-03 16:31:54 +07:00
if (paragraph?.Parent is null || string.IsNullOrEmpty(oldValue) || newValues is null || !newValues.Any())
2026-06-05 15:58:03 +07:00
return false;
var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType);
2026-08-03 16:31:54 +07:00
if (newParas is { Count: > 0 })
2026-06-05 15:58:03 +07:00
{
ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true;
}
return false;
}
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
{
2026-08-03 16:31:54 +07:00
if (paragraph?.Parent is null || string.IsNullOrEmpty(oldValue) || newValues is null || !newValues.Any())
2026-06-05 15:58:03 +07:00
return false;
var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType);
2026-08-03 16:31:54 +07:00
if (newParas is { Count: > 0 })
2026-06-05 15:58:03 +07:00
{
ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true;
}
return false;
}
#endregion
#region ProcessParagraphWithAllReplacements (для обратной совместимости)
internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph,
IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements,
StringComparison comparisonType)
2026-08-03 16:31:54 +07:00
=> ProcessMultiReplacements(paragraph, replacements, null, comparisonType);
2026-06-05 15:58:03 +07:00
internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements,
StringComparison comparisonType)
2026-08-03 16:31:54 +07:00
=> ProcessMultiReplacements(paragraph, null, replacements, comparisonType);
2026-06-05 15:58:03 +07:00
internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph,
IEnumerable<KeyValuePair<string, string>> replacements,
StringComparison comparisonType)
{
2026-08-03 16:31:54 +07:00
var dict = replacements
2026-06-05 15:58:03 +07:00
.Where(kvp => !string.IsNullOrEmpty(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)[kvp.Value]);
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
return ProcessMultiReplacements(paragraph, dict, null, comparisonType);
}
#endregion
// ---------- ВНУТРЕННЯЯ РЕАЛИЗАЦИЯ ----------
private class MatchDefinition(string key, IEnumerable<ReplaceItem> values)
{
public string Key { get; } = key;
public IEnumerable<ReplaceItem> Values { get; } = values;
}
private class Match
{
2026-08-03 16:31:54 +07:00
public MatchDefinition Definition { get; init; } = null!;
public int Start { get; init; }
public int End { get; init; }
2026-06-05 15:58:03 +07:00
}
private class RunSegment(Run run, string text, int start, int end)
{
public Run Run { get; } = run;
public string Text { get; } = text;
public int Start { get; } = start;
public int End { get; } = end;
}
2026-07-21 16:43:59 +07:00
private class ParagraphStructure(string fullText, List<RunSegment> segments)
2026-06-05 15:58:03 +07:00
{
public string FullText { get; } = fullText;
public List<RunSegment> Segments { get; } = segments;
}
private static ParagraphStructure AnalyzeParagraphStructure(List<Run> runs)
{
2026-08-03 16:31:54 +07:00
var segments = new List<RunSegment>(runs.Count);
2026-06-05 15:58:03 +07:00
var sb = new StringBuilder();
int pos = 0;
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
foreach (var run in runs)
{
string text = GetRunText(run);
if (string.IsNullOrEmpty(text)) continue;
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
segments.Add(new RunSegment(run, text, pos, pos + text.Length));
sb.Append(text);
pos += text.Length;
}
return new ParagraphStructure(sb.ToString(), segments);
}
private static string GetRunText(Run run)
{
var sb = new StringBuilder();
foreach (var text in run.Elements<Text>())
sb.Append(text.Text);
return sb.ToString();
}
2026-08-03 16:11:54 +07:00
/// <summary>Клонирует параграф, удаляя все SectionProperties и PageBreakBefore.</summary>
2026-07-23 16:42:26 +07:00
private static Paragraph CloneParagraphWithoutSection(Paragraph original)
2026-06-05 15:58:03 +07:00
{
var newPara = new Paragraph();
2026-08-03 16:31:54 +07:00
if (original.ParagraphProperties is null) return newPara;
var newProps = new ParagraphProperties();
foreach (var child in original.ParagraphProperties.ChildElements)
2026-07-21 16:43:59 +07:00
{
2026-08-03 16:31:54 +07:00
if (child is not SectionProperties and not PageBreakBefore)
newProps.AppendChild(child.CloneNode(true));
2026-07-21 16:43:59 +07:00
}
2026-08-03 16:31:54 +07:00
if (newProps.HasChildren)
newPara.ParagraphProperties = newProps;
2026-06-05 15:58:03 +07:00
return newPara;
}
2026-08-03 16:11:54 +07:00
private static Paragraph? BuildRemainderParagraph(Paragraph original, ParagraphStructure structure, int position)
2026-06-05 15:58:03 +07:00
{
if (position >= structure.FullText.Length) return null;
2026-07-23 16:42:26 +07:00
var newPara = CloneParagraphWithoutSection(original);
2026-08-03 16:11:54 +07:00
foreach (var seg in structure.Segments)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:11:54 +07:00
if (seg.End <= position) continue;
2026-08-03 16:31:54 +07:00
2026-08-03 16:11:54 +07:00
if (seg.Start >= position)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:11:54 +07:00
newPara.AppendChild(seg.Run.CloneNode(true));
2026-06-05 15:58:03 +07:00
}
2026-08-03 16:31:54 +07:00
else
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:11:54 +07:00
var runClone = (Run)seg.Run.CloneNode(true);
2026-08-03 16:31:54 +07:00
runClone.RemoveAllChildren<Text>(); // Упрощенная очистка
2026-08-03 16:11:54 +07:00
int offset = position - seg.Start;
2026-08-03 16:31:54 +07:00
runClone.AppendChild(new Text(seg.Text.Substring(offset)));
2026-08-03 16:11:54 +07:00
newPara.AppendChild(runClone);
2026-06-05 15:58:03 +07:00
}
}
2026-08-03 16:31:54 +07:00
// Удаляем пустые Run-ы без вложений
newPara.Elements<Run>().Where(r => !r.HasChildren).ToList().ForEach(r => r.Remove());
return !newPara.Elements<Run>().Any() && newPara.ParagraphProperties is null ? null : newPara;
2026-06-05 15:58:03 +07:00
}
private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position)
{
var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End);
if (seg is null) return;
var textRun = new Run();
if (seg.Run.RunProperties is not null)
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
textRun.AppendChild(new Text(item.Text ?? string.Empty));
para.AppendChild(textRun);
2026-07-21 16:43:59 +07:00
}
2026-08-03 16:11:54 +07:00
/// <summary>
/// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа.
/// </summary>
2026-08-03 16:31:54 +07:00
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue, bool addPageSize, SectionProperties? sourceSection, SectionProperties? portraitSection)
2026-07-21 16:43:59 +07:00
{
if (para is null) return;
2026-06-05 15:58:03 +07:00
2026-08-03 16:31:54 +07:00
// Удаляем существующие секции и разрывы
2026-08-03 16:11:54 +07:00
if (para.ParagraphProperties is not null)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:31:54 +07:00
para.ParagraphProperties.RemoveAllChildren<SectionProperties>();
para.ParagraphProperties.RemoveAllChildren<PageBreakBefore>();
2026-06-05 15:58:03 +07:00
}
2026-08-03 16:11:54 +07:00
para.ParagraphProperties ??= new ParagraphProperties();
var sectionProps = new SectionProperties();
// Добавляем PageSize
2026-08-03 16:31:54 +07:00
var sizeSource = addPageSize ? sourceSection : portraitSection;
var sourcePageSize = sizeSource?.GetFirstChild<PageSize>()
?? portraitSection?.GetFirstChild<PageSize>()
?? sourceSection?.GetFirstChild<PageSize>();
2026-08-03 16:11:54 +07:00
if (sourcePageSize is not null)
2026-07-21 16:43:59 +07:00
{
2026-08-03 16:11:54 +07:00
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
bool sourceIsLandscape = pageSizeClone.Orient?.Value == PageOrientationValues.Landscape ||
2026-08-03 16:31:54 +07:00
pageSizeClone.Width?.Value > pageSizeClone.Height?.Value;
bool targetIsLandscape = addPageSize && splitValue == PageBreakType.NewLandscapeSection;
2026-08-03 16:11:54 +07:00
if (targetIsLandscape && !sourceIsLandscape)
{
pageSizeClone.SwapValues();
pageSizeClone.Orient = PageOrientationValues.Landscape;
}
else if (!targetIsLandscape && sourceIsLandscape)
{
pageSizeClone.SwapValues();
2026-08-03 16:31:54 +07:00
pageSizeClone.Orient = addPageSize ? PageOrientationValues.Portrait : null;
2026-08-03 16:11:54 +07:00
}
else
{
2026-08-03 16:31:54 +07:00
pageSizeClone.Orient = targetIsLandscape ? PageOrientationValues.Landscape : (addPageSize ? PageOrientationValues.Portrait : null);
2026-08-03 16:11:54 +07:00
}
sectionProps.AppendChild(pageSizeClone);
2026-07-21 16:43:59 +07:00
}
2026-08-03 16:11:54 +07:00
// Копируем PageMargin
PageMargin? marginToUse = null;
if (addPageSize)
{
2026-08-03 16:31:54 +07:00
var sourceMargin = sourceSection?.GetFirstChild<PageMargin>() ?? portraitSection?.GetFirstChild<PageMargin>();
2026-08-03 16:11:54 +07:00
if (sourceMargin is not null)
2026-07-21 16:43:59 +07:00
{
2026-08-03 16:11:54 +07:00
var marginClone = (PageMargin)sourceMargin.CloneNode(true);
2026-08-03 16:31:54 +07:00
var sourceIsLndscape = sourceSection?.GetFirstChild<PageSize>()?.Orient?.Value == PageOrientationValues.Landscape ||
sourceSection?.GetFirstChild<PageSize>()?.Width?.Value > sourceSection?.GetFirstChild<PageSize>()?.Height?.Value;
if ((splitValue == PageBreakType.NewLandscapeSection && !sourceIsLndscape) ||
(splitValue == PageBreakType.NewPortraitSection && sourceIsLndscape))
2026-08-03 16:11:54 +07:00
{
marginClone.SwapBottomRight();
}
marginToUse = marginClone;
}
}
2026-08-03 16:31:54 +07:00
else if (portraitSection?.GetFirstChild<PageMargin>() is { } portraitMargin)
2026-08-03 16:11:54 +07:00
{
2026-08-03 16:31:54 +07:00
marginToUse = (PageMargin)portraitMargin.CloneNode(true);
2026-08-03 16:11:54 +07:00
}
2026-07-21 16:43:59 +07:00
2026-08-03 16:11:54 +07:00
if (marginToUse is not null)
sectionProps.AppendChild(marginToUse);
2026-07-23 16:42:26 +07:00
2026-08-03 16:11:54 +07:00
sectionProps.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
para.ParagraphProperties.AppendChild(sectionProps);
2026-06-05 15:58:03 +07:00
}
2026-07-21 16:43:59 +07:00
/// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary>
2026-06-05 15:58:03 +07:00
private static List<Paragraph>? ProcessMultiReplacements(
Paragraph original,
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
StringComparison comparisonType)
{
var definitions = new List<MatchDefinition>();
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
if (stringReplacements is not null)
{
2026-08-03 16:31:54 +07:00
definitions.AddRange(stringReplacements
.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && kvp.Value != null && kvp.Value.Any())
.Select(kvp => new MatchDefinition(kvp.Key, kvp.Value.Select(v => new ReplaceItem(v, PageBreakType.None)))));
2026-06-05 15:58:03 +07:00
}
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
if (itemReplacements is not null)
{
2026-08-03 16:31:54 +07:00
definitions.AddRange(itemReplacements
.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && kvp.Value != null && kvp.Value.Any())
.Select(kvp => new MatchDefinition(kvp.Key, kvp.Value)));
2026-06-05 15:58:03 +07:00
}
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
if (definitions.Count == 0) return null;
2026-08-03 16:31:54 +07:00
var runs = original.Elements<Run>().ToList();
2026-06-05 15:58:03 +07:00
if (runs.Count == 0) return null;
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
var structure = AnalyzeParagraphStructure(runs);
string fullText = structure.FullText;
if (fullText.Length == 0) return null;
var matches = new List<Match>();
foreach (var def in definitions)
{
int pos = 0;
while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1)
{
2026-08-03 16:31:54 +07:00
matches.Add(new Match { Definition = def, Start = pos, End = pos + def.Key.Length });
2026-06-05 15:58:03 +07:00
pos += def.Key.Length;
}
}
2026-08-03 16:31:54 +07:00
2026-06-05 15:58:03 +07:00
if (matches.Count == 0) return null;
2026-08-03 16:11:54 +07:00
matches.Sort((a, b) => a.Start.CompareTo(b.Start));
2026-06-05 15:58:03 +07:00
2026-08-03 16:31:54 +07:00
var body = original.Ancestors<Body>().FirstOrDefault();
var sourceSection = original.ParagraphProperties?.GetFirstChild<SectionProperties>()?.CloneNode(true) as SectionProperties
?? body?.Elements<SectionProperties>().LastOrDefault()?.CloneNode(true) as SectionProperties
?? new SectionProperties();
2026-07-23 16:42:26 +07:00
2026-08-03 16:31:54 +07:00
var portraitSection = body?.Elements<SectionProperties>().FirstOrDefault()?.CloneNode(true) as SectionProperties
?? new SectionProperties();
2026-07-23 16:42:26 +07:00
2026-06-05 15:58:03 +07:00
var resultParas = new List<Paragraph>();
Paragraph? currentPara = null;
int currentPos = 0;
2026-07-23 16:42:26 +07:00
bool sectionChangeInsideGroup = false;
2026-08-03 16:11:54 +07:00
PageBreakType? lastOrientation = null;
2026-06-05 15:58:03 +07:00
2026-08-03 16:31:54 +07:00
foreach (var match in matches)
2026-06-05 15:58:03 +07:00
{
if (currentPos < match.Start)
{
2026-08-03 16:11:54 +07:00
var beforePara = CloneParagraphWithoutSection(original);
foreach (var seg in structure.Segments)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:11:54 +07:00
if (seg.End <= currentPos) continue;
if (seg.Start >= match.Start) break;
2026-08-03 16:31:54 +07:00
2026-08-03 16:11:54 +07:00
if (seg.Start >= currentPos && seg.End <= match.Start)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:11:54 +07:00
beforePara.AppendChild(seg.Run.CloneNode(true));
2026-06-05 15:58:03 +07:00
}
2026-08-03 16:11:54 +07:00
else if (seg.Start < match.Start && seg.End > currentPos)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:11:54 +07:00
int startOffset = Math.Max(0, currentPos - seg.Start);
int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start);
2026-08-03 16:31:54 +07:00
2026-08-03 16:11:54 +07:00
var runClone = (Run)seg.Run.CloneNode(true);
2026-08-03 16:31:54 +07:00
runClone.RemoveAllChildren<Text>();
runClone.AppendChild(new Text(seg.Text.Substring(startOffset, endOffset - startOffset)));
2026-08-03 16:11:54 +07:00
beforePara.AppendChild(runClone);
2026-06-05 15:58:03 +07:00
}
}
2026-08-03 16:31:54 +07:00
if (beforePara.Elements<Run>().Any())
2026-08-03 16:11:54 +07:00
{
resultParas.Add(beforePara);
currentPara = beforePara;
}
2026-06-05 15:58:03 +07:00
}
2026-07-21 16:43:59 +07:00
var values = match.Definition.Values.ToList();
if (values.Count == 0) continue;
2026-06-05 15:58:03 +07:00
2026-07-21 16:43:59 +07:00
for (int vIdx = 0; vIdx < values.Count; vIdx++)
2026-06-05 15:58:03 +07:00
{
2026-07-21 16:43:59 +07:00
var item = values[vIdx];
2026-08-03 16:31:54 +07:00
currentPara = CloneParagraphWithoutSection(original);
resultParas.Add(currentPara);
2026-07-23 16:42:26 +07:00
2026-08-03 16:11:54 +07:00
InsertFormattedRun(currentPara, item, structure, match.Start);
2026-07-21 16:43:59 +07:00
2026-08-03 16:31:54 +07:00
if (item.SplitValue is PageBreakType.NewLandscapeSection or PageBreakType.NewPortraitSection)
2026-07-21 16:43:59 +07:00
{
2026-08-03 16:31:54 +07:00
bool addPageSize = vIdx != 0;
var orientation = vIdx != 0 ? PageBreakType.NewLandscapeSection : item.SplitValue;
2026-08-03 16:11:54 +07:00
AddSectionProperties(currentPara, orientation, addPageSize, sourceSection, portraitSection);
lastOrientation = item.SplitValue;
2026-07-23 16:42:26 +07:00
sectionChangeInsideGroup = true;
2026-07-21 16:43:59 +07:00
}
2026-08-03 16:11:54 +07:00
else if (item.SplitValue == PageBreakType.PageBreak)
2026-07-21 16:43:59 +07:00
{
var seg = structure.Segments.FirstOrDefault(s => match.Start >= s.Start && match.Start < s.End);
var breakRun = new Run(new Break { Type = BreakValues.Page });
2026-08-03 16:31:54 +07:00
if (seg?.Run.RunProperties is not null)
2026-07-21 16:43:59 +07:00
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
currentPara.AppendChild(breakRun);
}
}
2026-06-05 15:58:03 +07:00
2026-08-03 16:31:54 +07:00
if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara?.ParagraphProperties?.GetFirstChild<SectionProperties>() is null)
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:31:54 +07:00
AddSectionProperties(currentPara!, lastOrientation.Value, lastOrientation.Value == PageBreakType.NewLandscapeSection, sourceSection, portraitSection);
2026-08-03 16:11:54 +07:00
}
2026-08-03 16:31:54 +07:00
if (body is not null && sourceSection.GetFirstChild<PageSize>() is { } sourcePageSize)
2026-08-03 16:11:54 +07:00
{
2026-08-03 16:31:54 +07:00
bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape || sourcePageSize.Width?.Value > sourcePageSize.Height?.Value;
bool lastIsPortrait = lastOrientation == PageBreakType.NewPortraitSection;
if (sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait && !body.Elements<SectionProperties>().Any(s => s.GetFirstChild<PageSize>()?.Orient?.Value == PageOrientationValues.Landscape))
2026-06-05 15:58:03 +07:00
{
2026-08-03 16:31:54 +07:00
var bodySection = new SectionProperties();
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape)
2026-07-21 16:43:59 +07:00
{
2026-08-03 16:31:54 +07:00
pageSizeClone.SwapValues();
pageSizeClone.Orient = PageOrientationValues.Landscape;
}
bodySection.AppendChild(pageSizeClone);
if (sourceSection.GetFirstChild<PageMargin>() is { } sourceMargin)
{
var marginClone = (PageMargin)sourceMargin.CloneNode(true);
if (sourceSection.GetFirstChild<PageSize>()?.Orient?.Value != PageOrientationValues.Landscape)
2026-07-23 16:42:26 +07:00
{
2026-08-03 16:31:54 +07:00
marginClone.SwapBottomRight();
2026-07-23 16:42:26 +07:00
}
2026-08-03 16:31:54 +07:00
bodySection.AppendChild(marginClone);
2026-07-21 16:43:59 +07:00
}
2026-08-03 16:31:54 +07:00
bodySection.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
body.AppendChild(bodySection);
2026-06-05 15:58:03 +07:00
}
}
2026-08-03 16:11:54 +07:00
currentPos = match.End;
2026-07-23 16:42:26 +07:00
}
2026-08-03 16:31:54 +07:00
if (currentPos < fullText.Length && BuildRemainderParagraph(original, structure, currentPos) is { } remainderPara)
2026-07-23 16:42:26 +07:00
{
2026-08-03 16:31:54 +07:00
if (sectionChangeInsideGroup && lastOrientation.HasValue)
2026-08-03 16:11:54 +07:00
{
2026-08-03 16:31:54 +07:00
remainderPara.InsertAt(new Run(new Break { Type = BreakValues.Page }), 0);
AddSectionProperties(remainderPara, lastOrientation.Value, lastOrientation.Value == PageBreakType.NewLandscapeSection, sourceSection, portraitSection);
2026-08-03 16:11:54 +07:00
}
2026-08-03 16:31:54 +07:00
resultParas.Add(remainderPara);
2026-07-23 16:42:26 +07:00
}
2026-07-21 16:43:59 +07:00
2026-08-03 16:31:54 +07:00
resultParas.RemoveAll(p => !p.Elements<Run>().Any() && p.ParagraphProperties is null);
2026-08-03 16:11:54 +07:00
return resultParas.Count > 0 ? resultParas : null;
2026-07-23 16:42:26 +07:00
}
2026-06-05 15:58:03 +07:00
}