Compare commits
4
Commits
5302edfb8f
...
25207773f7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25207773f7 | ||
|
|
da188eaeab | ||
|
|
7f40ba664f | ||
|
|
1dcb22e1d5 |
@@ -21,16 +21,16 @@ internal sealed class ExcelBook : IBook
|
|||||||
public IReadOnlyList<ISheet> GetSheets() => Writer.GetSheets();
|
public IReadOnlyList<ISheet> GetSheets() => Writer.GetSheets();
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public ISheet? Sheet(string name) => Writer.Sheet(name);
|
public ISheet? Sheet(string name) => Writer.Sheet(name.EscapeSymbols());
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool TryGetSheet(string name, out ISheet sheet) => Writer.TryGetSheet(name, out sheet);
|
public bool TryGetSheet(string name, out ISheet sheet) => Writer.TryGetSheet(name.EscapeSymbols(), out sheet);
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool TryAddSheet(string name, Action<ISheet>? edit = null) => Writer.TryAddSheet(name, edit);
|
public bool TryAddSheet(string name, Action<ISheet>? edit = null) => Writer.TryAddSheet(name.EscapeSymbols(), edit);
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool TryRemoveSheet(string name) => Writer.TryRemoveSheet(name);
|
public bool TryRemoveSheet(string name) => Writer.TryRemoveSheet(name.EscapeSymbols());
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool TryRemoveSheet(ISheet sheet) => Writer.TryRemoveSheet(sheet);
|
public bool TryRemoveSheet(ISheet sheet) => Writer.TryRemoveSheet(sheet);
|
||||||
@@ -41,3 +41,21 @@ internal sealed class ExcelBook : IBook
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public NumberFormatPattern CreateNumberFormat(string format) => Writer.CreateNumberFormat(format);
|
public NumberFormatPattern CreateNumberFormat(string format) => Writer.CreateNumberFormat(format);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static class EscapeExt
|
||||||
|
{
|
||||||
|
public static string EscapeSymbols(this string source)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder(source);
|
||||||
|
|
||||||
|
sb.Replace('/', '∕');
|
||||||
|
sb.Replace('\\', '∖');
|
||||||
|
sb.Replace('*', '∗');
|
||||||
|
sb.Replace('?', '?');
|
||||||
|
sb.Replace(':', '˸');
|
||||||
|
sb.Replace('[', '[');
|
||||||
|
sb.Replace(']', ']');
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,7 +33,7 @@ internal sealed class ExcelSheet : ISheet
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(name)) return false;
|
if (string.IsNullOrEmpty(name)) return false;
|
||||||
Book.ThrowIfDisposed();
|
Book.ThrowIfDisposed();
|
||||||
SheetElement.Name = name;
|
SheetElement.Name = name.EscapeSymbols();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1095,6 +1095,8 @@ internal sealed class ExcelWriter : ExcelReader, IExcelReader, IExcelWriter
|
|||||||
if (string.IsNullOrEmpty(name))
|
if (string.IsNullOrEmpty(name))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
|
name = name.EscapeSymbols();
|
||||||
|
|
||||||
lock (_syncLock)
|
lock (_syncLock)
|
||||||
{
|
{
|
||||||
var workbookPart = _doc.WorkbookPart;
|
var workbookPart = _doc.WorkbookPart;
|
||||||
@@ -1113,7 +1115,7 @@ internal sealed class ExcelWriter : ExcelReader, IExcelReader, IExcelWriter
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool TryGetSheet(string name, out ISheet sheet)
|
public bool TryGetSheet(string name, out ISheet sheet)
|
||||||
{
|
{
|
||||||
sheet = Sheet(name)!;
|
sheet = Sheet(name.EscapeSymbols())!;
|
||||||
return sheet != null;
|
return sheet != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1130,6 +1132,8 @@ internal sealed class ExcelWriter : ExcelReader, IExcelReader, IExcelWriter
|
|||||||
if (workbookPart?.Workbook?.Sheets == null)
|
if (workbookPart?.Workbook?.Sheets == null)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
name = name.EscapeSymbols();
|
||||||
|
|
||||||
// Проверка уникальности имени
|
// Проверка уникальности имени
|
||||||
foreach (Sheet s in workbookPart.Workbook.Sheets.Elements<Sheet>())
|
foreach (Sheet s in workbookPart.Workbook.Sheets.Elements<Sheet>())
|
||||||
{
|
{
|
||||||
@@ -1168,7 +1172,7 @@ internal sealed class ExcelWriter : ExcelReader, IExcelReader, IExcelWriter
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public bool TryRemoveSheet(string name)
|
public bool TryRemoveSheet(string name)
|
||||||
{
|
{
|
||||||
var sheet = Sheet(name);
|
var sheet = Sheet(name.EscapeSymbols());
|
||||||
return sheet != null && TryRemoveSheet(sheet);
|
return sheet != null && TryRemoveSheet(sheet);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
namespace QWERTYkez.WordProcessor;
|
||||||
|
|
||||||
|
internal static class Extension
|
||||||
|
{
|
||||||
|
public static void SwapBottomRight(this PageMargin margin)
|
||||||
|
{
|
||||||
|
if (margin.Right is { } r)
|
||||||
|
{
|
||||||
|
margin.Right = margin.Bottom is not null ? new((uint)margin.Bottom.Value) : null;
|
||||||
|
margin.Bottom = new((int)r.Value);
|
||||||
|
}
|
||||||
|
else if(margin.Bottom is { } b)
|
||||||
|
{
|
||||||
|
margin.Bottom = null;
|
||||||
|
margin.Right = new((uint)b.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void SwapValues(this PageSize size)
|
||||||
|
{
|
||||||
|
if (size.Width is { } w)
|
||||||
|
{
|
||||||
|
size.Width = size.Height is not null ? new(size.Height.Value) : null;
|
||||||
|
size.Height = new(w.Value);
|
||||||
|
}
|
||||||
|
else if (size.Height is { } h)
|
||||||
|
{
|
||||||
|
size.Height = null;
|
||||||
|
size.Width = new(h.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,10 @@ public interface IWordReader
|
|||||||
string? FilePath { get; }
|
string? FilePath { get; }
|
||||||
bool IsValid { get; }
|
bool IsValid { get; }
|
||||||
|
|
||||||
|
#if DEBUG
|
||||||
|
Body Body { get; }
|
||||||
|
#endif
|
||||||
|
|
||||||
ISet<string> FindPlaceholders();
|
ISet<string> FindPlaceholders();
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,106 +0,0 @@
|
|||||||
namespace QWERTYkez.WordProcessor;
|
|
||||||
|
|
||||||
internal static class IeExtension
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Выполняет указанные действия для первого и последующих элементов последовательности.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="T">Тип элементов последовательности.</typeparam>
|
|
||||||
/// <param name="items">Последовательность элементов.</param>
|
|
||||||
/// <param name="first">Действие над первым элементом (если есть).</param>
|
|
||||||
/// <param name="next">Действие над каждым последующим элементом, начиная со второго.</param>
|
|
||||||
/// <exception cref="ArgumentNullException">Возникает, если items или любой из делегатов равен null.</exception>
|
|
||||||
public static void ForFirstNext<T>(this IEnumerable<T> items, Action<T> first, Action<T> next)
|
|
||||||
{
|
|
||||||
if (items is null) throw new ArgumentNullException(nameof(items));
|
|
||||||
if (first is null) throw new ArgumentNullException(nameof(first));
|
|
||||||
if (next is null) throw new ArgumentNullException(nameof(next));
|
|
||||||
|
|
||||||
using var enumerator = items.GetEnumerator();
|
|
||||||
|
|
||||||
if (!enumerator.MoveNext())
|
|
||||||
return;
|
|
||||||
|
|
||||||
first(enumerator.Current);
|
|
||||||
|
|
||||||
while (enumerator.MoveNext())
|
|
||||||
{
|
|
||||||
next(enumerator.Current);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Выполняет указанные действия для первого, промежуточных и последнего элементов последовательности.
|
|
||||||
/// Если последовательность содержит только один элемент, то для него вызываются и first, и last.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="T">Тип элементов последовательности.</typeparam>
|
|
||||||
/// <param name="items">Последовательность элементов.</param>
|
|
||||||
/// <param name="first">Действие над первым элементом.</param>
|
|
||||||
/// <param name="next">Действие над элементами, которые не являются ни первыми, ни последними.</param>
|
|
||||||
/// <param name="last">Действие над последним элементом.</param>
|
|
||||||
/// <exception cref="ArgumentNullException">Возникает, если items или любой из делегатов равен null.</exception>
|
|
||||||
public static void ForFirstNextLast<T>(this IEnumerable<T> items, Action<T> first, Action<T> next, Action<T> last)
|
|
||||||
{
|
|
||||||
if (items is null) throw new ArgumentNullException(nameof(items));
|
|
||||||
if (first is null) throw new ArgumentNullException(nameof(first));
|
|
||||||
if (next is null) throw new ArgumentNullException(nameof(next));
|
|
||||||
if (last is null) throw new ArgumentNullException(nameof(last));
|
|
||||||
|
|
||||||
using var enumerator = items.GetEnumerator();
|
|
||||||
|
|
||||||
if (!enumerator.MoveNext())
|
|
||||||
return;
|
|
||||||
|
|
||||||
T firstItem = enumerator.Current;
|
|
||||||
|
|
||||||
// Если только один элемент
|
|
||||||
if (!enumerator.MoveNext())
|
|
||||||
{
|
|
||||||
first(firstItem);
|
|
||||||
last(firstItem);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Есть как минимум два элемента
|
|
||||||
first(firstItem);
|
|
||||||
|
|
||||||
T prev = enumerator.Current; // второй элемент
|
|
||||||
while (enumerator.MoveNext())
|
|
||||||
{
|
|
||||||
next(prev); // предыдущий элемент точно не последний
|
|
||||||
prev = enumerator.Current;
|
|
||||||
}
|
|
||||||
|
|
||||||
last(prev); // последний элемент
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Выполняет указанные действия для всех элементов, кроме последнего, и для последнего элемента.
|
|
||||||
/// Если последовательность содержит только один элемент, то вызывается только last.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="T">Тип элементов последовательности.</typeparam>
|
|
||||||
/// <param name="items">Последовательность элементов.</param>
|
|
||||||
/// <param name="next">Действие над элементами, не являющимися последними.</param>
|
|
||||||
/// <param name="last">Действие над последним элементом.</param>
|
|
||||||
/// <exception cref="ArgumentNullException">Возникает, если items или любой из делегатов равен null.</exception>
|
|
||||||
public static void ForNextLast<T>(this IEnumerable<T> items, Action<T> next, Action<T> last)
|
|
||||||
{
|
|
||||||
if (items is null) throw new ArgumentNullException(nameof(items));
|
|
||||||
if (next is null) throw new ArgumentNullException(nameof(next));
|
|
||||||
if (last is null) throw new ArgumentNullException(nameof(last));
|
|
||||||
|
|
||||||
using var enumerator = items.GetEnumerator();
|
|
||||||
|
|
||||||
if (!enumerator.MoveNext())
|
|
||||||
return;
|
|
||||||
|
|
||||||
T prev = enumerator.Current;
|
|
||||||
while (enumerator.MoveNext())
|
|
||||||
{
|
|
||||||
next(prev);
|
|
||||||
prev = enumerator.Current;
|
|
||||||
}
|
|
||||||
|
|
||||||
last(prev);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,22 @@
|
|||||||
namespace QWERTYkez.WordProcessor;
|
namespace QWERTYkez.WordProcessor;
|
||||||
|
|
||||||
|
#if DEBUG
|
||||||
|
public static class Debugger
|
||||||
|
{
|
||||||
|
public static StringBuilder Builder { get; } = new();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
|
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
|
||||||
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение
|
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение
|
||||||
/// остаётся в текущем параграфе, а последующие создают новые.
|
/// остаётся в текущем параграфе, а последующие создают новые.
|
||||||
/// Текст между вхождениями и после последнего сохраняется в соответствующих параграфах.
|
/// Текст между вхождениями и после последнего сохраняется в соответствующих параграфах.
|
||||||
|
/// Поддерживает разрывы страниц и смену ориентации (альбомная/книжная) через <see cref="ReplaceItem.SplitValue"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class MultiReplaceExt
|
internal static class MultiReplaceExt
|
||||||
{
|
{
|
||||||
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (СИГНАТУРЫ НЕИЗМЕННЫ) ----------
|
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (для Body) ----------
|
||||||
|
|
||||||
#region Body.Replace с одним ключом
|
#region Body.Replace с одним ключом
|
||||||
|
|
||||||
@@ -152,7 +160,7 @@ internal static class MultiReplaceExt
|
|||||||
public int End { get; } = end;
|
public int End { get; } = end;
|
||||||
}
|
}
|
||||||
|
|
||||||
private class ParagraphStructure(string fullText, List<MultiReplaceExt.RunSegment> segments)
|
private class ParagraphStructure(string fullText, List<RunSegment> segments)
|
||||||
{
|
{
|
||||||
public string FullText { get; } = fullText;
|
public string FullText { get; } = fullText;
|
||||||
public List<RunSegment> Segments { get; } = segments;
|
public List<RunSegment> Segments { get; } = segments;
|
||||||
@@ -182,147 +190,52 @@ internal static class MultiReplaceExt
|
|||||||
return sb.ToString();
|
return sb.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Paragraph CloneParagraphProperties(Paragraph original)
|
/// <summary>Клонирует параграф, удаляя все SectionProperties и PageBreakBefore.</summary>
|
||||||
|
private static Paragraph CloneParagraphWithoutSection(Paragraph original)
|
||||||
{
|
{
|
||||||
var newPara = new Paragraph();
|
var newPara = new Paragraph();
|
||||||
if (original.ParagraphProperties is not null)
|
if (original.ParagraphProperties is not null)
|
||||||
newPara.ParagraphProperties = (ParagraphProperties)original.ParagraphProperties.CloneNode(true);
|
{
|
||||||
|
var newProps = new ParagraphProperties();
|
||||||
|
foreach (var child in original.ParagraphProperties.ChildElements)
|
||||||
|
{
|
||||||
|
if (child is not SectionProperties && child is not PageBreakBefore)
|
||||||
|
newProps.AppendChild(child.CloneNode(true));
|
||||||
|
}
|
||||||
|
newPara.ParagraphProperties = newProps;
|
||||||
|
}
|
||||||
return newPara;
|
return newPara;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
private static Paragraph? BuildRemainderParagraph(Paragraph original, ParagraphStructure structure, int position)
|
||||||
/// Строит параграф, содержащий копии всех элементов исходного параграфа,
|
|
||||||
/// попадающих в текстовый диапазон [start, end).
|
|
||||||
/// </summary>
|
|
||||||
private static Paragraph? BuildRangeParagraph(Paragraph original, ParagraphStructure structure, int start, int end)
|
|
||||||
{
|
|
||||||
if (start >= end) return null;
|
|
||||||
|
|
||||||
var newPara = CloneParagraphProperties(original);
|
|
||||||
|
|
||||||
foreach (var child in original.ChildElements)
|
|
||||||
{
|
|
||||||
if (child is Run run)
|
|
||||||
{
|
|
||||||
var seg = structure.Segments.FirstOrDefault(s => s.Run == run);
|
|
||||||
if (seg is null)
|
|
||||||
{
|
|
||||||
// Run без текста (разрыв, поле) – копируем целиком, т.к. не можем привязать к позиции
|
|
||||||
newPara.AppendChild(run.CloneNode(true));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (seg.End <= start || seg.Start >= end)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (seg.Start >= start && seg.End <= end)
|
|
||||||
{
|
|
||||||
// Полностью внутри диапазона
|
|
||||||
newPara.AppendChild(run.CloneNode(true));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Частичное пересечение – обрезаем текст
|
|
||||||
var runClone = (Run)run.CloneNode(true);
|
|
||||||
foreach (var t in runClone.Elements<Text>().ToList())
|
|
||||||
t.Remove();
|
|
||||||
|
|
||||||
int cutStart = Math.Max(start, seg.Start) - seg.Start;
|
|
||||||
int cutEnd = Math.Min(end, seg.End) - seg.Start;
|
|
||||||
string newText = seg.Text.Substring(cutStart, cutEnd - cutStart);
|
|
||||||
runClone.AppendChild(new Text(newText));
|
|
||||||
newPara.AppendChild(runClone);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Не Run – копируем всегда (закладки, поля и т.п.), т.к. не можем определить позицию
|
|
||||||
newPara.AppendChild(child.CloneNode(true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Удаляем пустые Run
|
|
||||||
foreach (var run in newPara.Descendants<Run>().Where(r => !r.HasChildren).ToList())
|
|
||||||
run.Remove();
|
|
||||||
|
|
||||||
if (!newPara.ChildElements.OfType<Run>().Any() && newPara.ParagraphProperties is null)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
return newPara;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Строит параграф, содержащий все элементы исходного параграфа,
|
|
||||||
/// которые находятся строго после указанной текстовой позиции,
|
|
||||||
/// пропуская нетекстовые элементы до первого текстового сегмента.
|
|
||||||
/// </summary>
|
|
||||||
private static Paragraph? BuildAfterParagraph(Paragraph original, ParagraphStructure structure, int position)
|
|
||||||
{
|
{
|
||||||
if (position >= structure.FullText.Length) return null;
|
if (position >= structure.FullText.Length) return null;
|
||||||
|
|
||||||
var newPara = CloneParagraphProperties(original);
|
var newPara = CloneParagraphWithoutSection(original);
|
||||||
|
foreach (var seg in structure.Segments)
|
||||||
// Находим первый текстовый сегмент, который начинается на или после position
|
|
||||||
var firstTextSeg = structure.Segments.FirstOrDefault(s => s.Start >= position);
|
|
||||||
bool passedFirstText = false;
|
|
||||||
|
|
||||||
foreach (var child in original.ChildElements)
|
|
||||||
{
|
{
|
||||||
if (child is Run run)
|
if (seg.End <= position) continue;
|
||||||
{
|
|
||||||
var seg = structure.Segments.FirstOrDefault(s => s.Run == run);
|
|
||||||
if (seg is null)
|
|
||||||
{
|
|
||||||
// Run без текста – добавляем только если уже прошли первый текстовый сегмент
|
|
||||||
if (passedFirstText)
|
|
||||||
newPara.AppendChild(run.CloneNode(true));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (seg.Start >= position)
|
if (seg.Start >= position)
|
||||||
{
|
{
|
||||||
// Полностью после позиции
|
newPara.AppendChild(seg.Run.CloneNode(true));
|
||||||
newPara.AppendChild(run.CloneNode(true));
|
|
||||||
if (seg == firstTextSeg)
|
|
||||||
passedFirstText = true;
|
|
||||||
}
|
}
|
||||||
else if (seg.End > position)
|
else if (seg.End > position)
|
||||||
{
|
{
|
||||||
// Частично пересекает – обрезаем текст
|
var runClone = (Run)seg.Run.CloneNode(true);
|
||||||
var runClone = (Run)run.CloneNode(true);
|
foreach (var t in runClone.Elements<Text>().ToList()) t.Remove();
|
||||||
foreach (var t in runClone.Elements<Text>().ToList())
|
|
||||||
t.Remove();
|
|
||||||
|
|
||||||
int offset = position - seg.Start;
|
int offset = position - seg.Start;
|
||||||
string newText = seg.Text.Substring(offset);
|
string newText = seg.Text.Substring(offset);
|
||||||
runClone.AppendChild(new Text(newText));
|
runClone.AppendChild(new Text(newText));
|
||||||
newPara.AppendChild(runClone);
|
newPara.AppendChild(runClone);
|
||||||
passedFirstText = true;
|
|
||||||
}
|
|
||||||
// seg.End <= position – игнорируем
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Не Run – добавляем только если уже прошли первый текстовый сегмент
|
|
||||||
if (passedFirstText)
|
|
||||||
newPara.AppendChild(child.CloneNode(true));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var run in newPara.Descendants<Run>().Where(r => !r.HasChildren).ToList())
|
foreach (var run in newPara.Descendants<Run>().Where(r => !r.HasChildren).ToList())
|
||||||
run.Remove();
|
run.Remove();
|
||||||
|
|
||||||
if (!newPara.ChildElements.OfType<Run>().Any() && newPara.ParagraphProperties is null)
|
if (!newPara.ChildElements.OfType<Run>().Any() && newPara.ParagraphProperties is null)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
return newPara;
|
return newPara;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Вставляет в параграф новый Run с текстом из ReplaceItem,
|
|
||||||
/// копируя форматирование из сегмента, содержащего указанную позицию.
|
|
||||||
/// Если BreakPage == true, добавляет отдельный Run с разрывом страницы.
|
|
||||||
/// </summary>
|
|
||||||
private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position)
|
private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position)
|
||||||
{
|
{
|
||||||
var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End);
|
var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End);
|
||||||
@@ -333,42 +246,177 @@ internal static class MultiReplaceExt
|
|||||||
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
||||||
textRun.AppendChild(new Text(item.Text ?? string.Empty));
|
textRun.AppendChild(new Text(item.Text ?? string.Empty));
|
||||||
para.AppendChild(textRun);
|
para.AppendChild(textRun);
|
||||||
|
|
||||||
if (item.BreakPage)
|
|
||||||
{
|
|
||||||
var breakRun = new Run(new Break() { Type = BreakValues.Page });
|
|
||||||
if (seg.Run.RunProperties is not null)
|
|
||||||
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
|
||||||
para.AppendChild(breakRun);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавляет содержимое одного параграфа в другой (клонируя элементы).
|
/// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа.
|
||||||
|
/// Для книжных секций (addPageSize=false) Orient не устанавливается (not set).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue, bool addPageSize, SectionProperties sourceSection, SectionProperties portraitSection)
|
||||||
|
{
|
||||||
|
if (para is null) return;
|
||||||
|
|
||||||
|
// Удаляем существующие секции
|
||||||
|
if (para.ParagraphProperties is not null)
|
||||||
|
{
|
||||||
|
var sections = para.ParagraphProperties.Elements<SectionProperties>().ToList();
|
||||||
|
foreach (var sec in sections) sec.Remove();
|
||||||
|
var pageBreaks = para.ParagraphProperties.Elements<PageBreakBefore>().ToList();
|
||||||
|
foreach (var pb in pageBreaks) pb.Remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
para.ParagraphProperties ??= new ParagraphProperties();
|
||||||
|
var sectionProps = new SectionProperties();
|
||||||
|
|
||||||
|
// Добавляем PageSize
|
||||||
|
SectionProperties? sizeSource = addPageSize ? sourceSection : portraitSection;
|
||||||
|
var sourcePageSize = sizeSource?.GetFirstChild<PageSize>();
|
||||||
|
if (sourcePageSize is null && portraitSection is not null)
|
||||||
|
sourcePageSize = portraitSection.GetFirstChild<PageSize>();
|
||||||
|
if (sourcePageSize is null && sourceSection is not null)
|
||||||
|
sourcePageSize = sourceSection.GetFirstChild<PageSize>();
|
||||||
|
|
||||||
|
if (sourcePageSize is not null)
|
||||||
|
{
|
||||||
|
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
|
||||||
|
bool sourceIsLandscape = pageSizeClone.Orient?.Value == PageOrientationValues.Landscape ||
|
||||||
|
(pageSizeClone.Width?.Value > pageSizeClone.Height?.Value);
|
||||||
|
|
||||||
|
bool targetIsLandscape = (addPageSize && splitValue == PageBreakType.NewLandscapeSection);
|
||||||
|
|
||||||
|
if (targetIsLandscape && !sourceIsLandscape)
|
||||||
|
{
|
||||||
|
pageSizeClone.SwapValues();
|
||||||
|
pageSizeClone.Orient = PageOrientationValues.Landscape;
|
||||||
|
}
|
||||||
|
else if (!targetIsLandscape && sourceIsLandscape)
|
||||||
|
{
|
||||||
|
pageSizeClone.SwapValues();
|
||||||
|
if (addPageSize)
|
||||||
|
pageSizeClone.Orient = PageOrientationValues.Portrait;
|
||||||
|
else
|
||||||
|
pageSizeClone.Orient = null; // не задаём Orient (not set)
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (targetIsLandscape)
|
||||||
|
pageSizeClone.Orient = PageOrientationValues.Landscape;
|
||||||
|
else if (addPageSize)
|
||||||
|
pageSizeClone.Orient = PageOrientationValues.Portrait;
|
||||||
|
else
|
||||||
|
pageSizeClone.Orient = null; // not set
|
||||||
|
}
|
||||||
|
sectionProps.AppendChild(pageSizeClone);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Копируем PageMargin
|
||||||
|
PageMargin? marginToUse = null;
|
||||||
|
if (addPageSize)
|
||||||
|
{
|
||||||
|
var sourceMargin = sourceSection?.GetFirstChild<PageMargin>()
|
||||||
|
?? portraitSection?.GetFirstChild<PageMargin>();
|
||||||
|
if (sourceMargin is not null)
|
||||||
|
{
|
||||||
|
var marginClone = (PageMargin)sourceMargin.CloneNode(true);
|
||||||
|
var sourceOrient = sourceSection?.GetFirstChild<PageSize>()?.Orient;
|
||||||
|
bool sourceIsLandscape = sourceOrient?.Value == PageOrientationValues.Landscape ||
|
||||||
|
(sourceSection?.GetFirstChild<PageSize>()?.Width?.Value > sourceSection?.GetFirstChild<PageSize>()?.Height?.Value);
|
||||||
|
if ((splitValue == PageBreakType.NewLandscapeSection && !sourceIsLandscape) ||
|
||||||
|
(splitValue == PageBreakType.NewPortraitSection && sourceIsLandscape))
|
||||||
|
{
|
||||||
|
marginClone.SwapBottomRight();
|
||||||
|
}
|
||||||
|
marginToUse = marginClone;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var portraitMargin = portraitSection?.GetFirstChild<PageMargin>();
|
||||||
|
if (portraitMargin is not null)
|
||||||
|
marginToUse = (PageMargin)portraitMargin.CloneNode(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (marginToUse is not null)
|
||||||
|
sectionProps.AppendChild(marginToUse);
|
||||||
|
|
||||||
|
sectionProps.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
|
||||||
|
para.ParagraphProperties.AppendChild(sectionProps);
|
||||||
|
}
|
||||||
|
|
||||||
private static void MergeParagraph(Paragraph target, Paragraph source)
|
private static void MergeParagraph(Paragraph target, Paragraph source)
|
||||||
{
|
{
|
||||||
foreach (var child in source.ChildElements)
|
foreach (var child in source.ChildElements)
|
||||||
target.AppendChild(child.CloneNode(true));
|
target.AppendChild(child.CloneNode(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>Выводит структуру документа: для каждого параграфа показывает текст, наличие секции, ориентацию, размеры и поля.</summary>
|
||||||
/// Основной алгоритм: обрабатывает все вхождения всех ключей из предоставленных словарей.
|
private static void LogDocumentStructure(Body body, string title)
|
||||||
/// </summary>
|
{
|
||||||
|
#if DEBUG
|
||||||
|
Debugger.Builder.AppendLine($"=== {title} ===");
|
||||||
|
var paragraphs = body.Descendants<Paragraph>().ToList();
|
||||||
|
int index = 0;
|
||||||
|
foreach (var para in paragraphs)
|
||||||
|
{
|
||||||
|
var text = para.InnerText.Replace("\n", "\\n").Replace("\r", "\\r");
|
||||||
|
var section = para.ParagraphProperties?.GetFirstChild<SectionProperties>();
|
||||||
|
string sectionInfo = "None";
|
||||||
|
if (section is not null)
|
||||||
|
{
|
||||||
|
var pageSize = section.GetFirstChild<PageSize>();
|
||||||
|
string orient = pageSize?.Orient?.ToString() ?? "not set";
|
||||||
|
string sizeInfo = "";
|
||||||
|
if (pageSize is not null)
|
||||||
|
{
|
||||||
|
sizeInfo = $" Size: W={pageSize.Width?.Value}, H={pageSize.Height?.Value}";
|
||||||
|
}
|
||||||
|
var margins = section.GetFirstChild<PageMargin>();
|
||||||
|
string marginInfo = "";
|
||||||
|
if (margins is not null)
|
||||||
|
{
|
||||||
|
marginInfo = $" Margins: Top={margins.Top?.Value}, Bottom={margins.Bottom?.Value}, Left={margins.Left?.Value}, Right={margins.Right?.Value}";
|
||||||
|
}
|
||||||
|
sectionInfo = $"Orient={orient}{sizeInfo}{marginInfo}";
|
||||||
|
}
|
||||||
|
Debugger.Builder.AppendLine($" Para {index}: Text='{text}', Section={sectionInfo}");
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Логируем секции из Body (если есть)
|
||||||
|
var bodySections = body.Elements<SectionProperties>().ToList();
|
||||||
|
if (bodySections.Any())
|
||||||
|
{
|
||||||
|
Debugger.Builder.AppendLine(" Body SectionProperties:");
|
||||||
|
foreach (var sec in bodySections)
|
||||||
|
{
|
||||||
|
var ps = sec.GetFirstChild<PageSize>();
|
||||||
|
var pm = sec.GetFirstChild<PageMargin>();
|
||||||
|
Debugger.Builder.AppendLine($" PageSize: Width={ps?.Width}, Height={ps?.Height}, Orient={ps?.Orient}");
|
||||||
|
Debugger.Builder.AppendLine($" PageMargin: Top={pm?.Top}, Bottom={pm?.Bottom}, Left={pm?.Left}, Right={pm?.Right}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Debugger.Builder.AppendLine($"=== END {title} ===");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary>
|
||||||
private static List<Paragraph>? ProcessMultiReplacements(
|
private static List<Paragraph>? ProcessMultiReplacements(
|
||||||
Paragraph original,
|
Paragraph original,
|
||||||
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
|
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
|
||||||
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
|
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
|
||||||
StringComparison comparisonType)
|
StringComparison comparisonType)
|
||||||
{
|
{
|
||||||
// 1. Собираем определения замен
|
var body = original.Ancestors<Body>().FirstOrDefault();
|
||||||
|
|
||||||
|
// 1. Сбор определений
|
||||||
var definitions = new List<MatchDefinition>();
|
var definitions = new List<MatchDefinition>();
|
||||||
if (stringReplacements is not null)
|
if (stringReplacements is not null)
|
||||||
{
|
{
|
||||||
foreach (var kvp in stringReplacements)
|
foreach (var kvp in stringReplacements)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
|
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
|
||||||
definitions.Add(new MatchDefinition(kvp.Key, [.. kvp.Value.Select(v => new ReplaceItem(v, false))]));
|
var items = kvp.Value.Select(v => new ReplaceItem(v, PageBreakType.None));
|
||||||
|
definitions.Add(new MatchDefinition(kvp.Key, items));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (itemReplacements is not null)
|
if (itemReplacements is not null)
|
||||||
@@ -379,7 +427,6 @@ internal static class MultiReplaceExt
|
|||||||
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
|
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (definitions.Count == 0) return null;
|
if (definitions.Count == 0) return null;
|
||||||
|
|
||||||
// 2. Анализ структуры параграфа
|
// 2. Анализ структуры параграфа
|
||||||
@@ -389,7 +436,7 @@ internal static class MultiReplaceExt
|
|||||||
string fullText = structure.FullText;
|
string fullText = structure.FullText;
|
||||||
if (fullText.Length == 0) return null;
|
if (fullText.Length == 0) return null;
|
||||||
|
|
||||||
// 3. Находим все вхождения всех ключей
|
// 3. Поиск всех вхождений
|
||||||
var matches = new List<Match>();
|
var matches = new List<Match>();
|
||||||
foreach (var def in definitions)
|
foreach (var def in definitions)
|
||||||
{
|
{
|
||||||
@@ -405,90 +452,201 @@ internal static class MultiReplaceExt
|
|||||||
pos += def.Key.Length;
|
pos += def.Key.Length;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (matches.Count == 0) return null;
|
if (matches.Count == 0) return null;
|
||||||
|
|
||||||
// 4. Сортируем по позиции
|
|
||||||
matches.Sort((a, b) => a.Start.CompareTo(b.Start));
|
matches.Sort((a, b) => a.Start.CompareTo(b.Start));
|
||||||
|
|
||||||
// 5. Построение результирующих параграфов
|
// 4. Получаем исходную секцию для копирования (из original или из документа)
|
||||||
|
SectionProperties? sourceSection = original.ParagraphProperties?.GetFirstChild<SectionProperties>()?.CloneNode(true) as SectionProperties;
|
||||||
|
if (sourceSection is null && body is not null)
|
||||||
|
{
|
||||||
|
sourceSection = body.Elements<SectionProperties>().LastOrDefault()?.CloneNode(true) as SectionProperties;
|
||||||
|
}
|
||||||
|
sourceSection ??= new SectionProperties();
|
||||||
|
|
||||||
|
// Получаем книжную секцию для копирования полей (из документа)
|
||||||
|
SectionProperties? portraitSection = null;
|
||||||
|
if (body is not null)
|
||||||
|
{
|
||||||
|
portraitSection = body.Elements<SectionProperties>().FirstOrDefault()?.CloneNode(true) as SectionProperties;
|
||||||
|
}
|
||||||
|
portraitSection ??= new SectionProperties();
|
||||||
|
|
||||||
|
// 5. Построение результата
|
||||||
var resultParas = new List<Paragraph>();
|
var resultParas = new List<Paragraph>();
|
||||||
Paragraph? currentPara = null;
|
Paragraph? currentPara = null;
|
||||||
int currentPos = 0;
|
int currentPos = 0;
|
||||||
|
bool sectionChangeInsideGroup = false;
|
||||||
|
PageBreakType? lastOrientation = null;
|
||||||
|
|
||||||
for (int i = 0; i < matches.Count; i++)
|
for (int i = 0; i < matches.Count; i++)
|
||||||
{
|
{
|
||||||
var match = matches[i];
|
var match = matches[i];
|
||||||
|
|
||||||
// Текст перед текущим совпадением (от currentPos до match.Start)
|
// Текст перед совпадением (если есть)
|
||||||
if (currentPos < match.Start)
|
if (currentPos < match.Start)
|
||||||
{
|
{
|
||||||
var textPart = BuildRangeParagraph(original, structure, currentPos, match.Start);
|
var beforePara = CloneParagraphWithoutSection(original);
|
||||||
if (textPart is not null)
|
foreach (var seg in structure.Segments)
|
||||||
{
|
{
|
||||||
if (currentPara is null)
|
if (seg.End <= currentPos) continue;
|
||||||
|
if (seg.Start >= match.Start) break;
|
||||||
|
if (seg.Start >= currentPos && seg.End <= match.Start)
|
||||||
{
|
{
|
||||||
currentPara = textPart;
|
beforePara.AppendChild(seg.Run.CloneNode(true));
|
||||||
resultParas.Add(currentPara);
|
|
||||||
}
|
}
|
||||||
else
|
else if (seg.Start < match.Start && seg.End > currentPos)
|
||||||
{
|
{
|
||||||
MergeParagraph(currentPara, textPart);
|
int startOffset = Math.Max(0, currentPos - seg.Start);
|
||||||
|
int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start);
|
||||||
|
var runClone = (Run)seg.Run.CloneNode(true);
|
||||||
|
foreach (var t in runClone.Elements<Text>().ToList()) t.Remove();
|
||||||
|
string textPart = seg.Text.Substring(startOffset, endOffset - startOffset);
|
||||||
|
runClone.AppendChild(new Text(textPart));
|
||||||
|
beforePara.AppendChild(runClone);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (beforePara.ChildElements.OfType<Run>().Any())
|
||||||
|
{
|
||||||
|
resultParas.Add(beforePara);
|
||||||
|
currentPara = beforePara;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Обрабатываем значения замены для этого совпадения
|
var values = match.Definition.Values.ToList();
|
||||||
var values = match.Definition.Values;
|
if (values.Count == 0) continue;
|
||||||
|
|
||||||
// Первое значение – в текущий параграф (или создаём новый)
|
for (int vIdx = 0; vIdx < values.Count; vIdx++)
|
||||||
if (currentPara is null)
|
|
||||||
{
|
{
|
||||||
currentPara = CloneParagraphProperties(original);
|
var item = values[vIdx];
|
||||||
resultParas.Add(currentPara);
|
|
||||||
}
|
|
||||||
|
|
||||||
values.ForFirstNext(first =>
|
// Создаём новый параграф для каждого элемента
|
||||||
{
|
var newPara = CloneParagraphWithoutSection(original);
|
||||||
InsertFormattedRun(currentPara, first, structure, match.Start);
|
|
||||||
},
|
|
||||||
next =>
|
|
||||||
{
|
|
||||||
// Остальные значения – в новые параграфы
|
|
||||||
var newPara = CloneParagraphProperties(original);
|
|
||||||
InsertFormattedRun(newPara, next, structure, match.Start);
|
|
||||||
resultParas.Add(newPara);
|
resultParas.Add(newPara);
|
||||||
currentPara = newPara; // теперь текущий параграф – последний созданный
|
currentPara = newPara;
|
||||||
});
|
|
||||||
|
InsertFormattedRun(currentPara, item, structure, match.Start);
|
||||||
|
|
||||||
|
// Обработка смены ориентации
|
||||||
|
if (item.SplitValue == PageBreakType.NewLandscapeSection || item.SplitValue == PageBreakType.NewPortraitSection)
|
||||||
|
{
|
||||||
|
bool addPageSize = (vIdx != 0);
|
||||||
|
PageBreakType orientation = item.SplitValue;
|
||||||
|
if (vIdx != 0)
|
||||||
|
{
|
||||||
|
orientation = PageBreakType.NewLandscapeSection;
|
||||||
|
}
|
||||||
|
AddSectionProperties(currentPara, orientation, addPageSize, sourceSection, portraitSection);
|
||||||
|
lastOrientation = item.SplitValue;
|
||||||
|
sectionChangeInsideGroup = true;
|
||||||
|
}
|
||||||
|
else if (item.SplitValue == PageBreakType.PageBreak)
|
||||||
|
{
|
||||||
|
var seg = structure.Segments.FirstOrDefault(s => match.Start >= s.Start && match.Start < s.End);
|
||||||
|
var breakRun = new Run(new Break { Type = BreakValues.Page });
|
||||||
|
if (seg is not null && seg.Run.RunProperties is not null)
|
||||||
|
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
|
||||||
|
currentPara.AppendChild(breakRun);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Закрываем секцию, если была смена и последний параграф не имеет секции
|
||||||
|
if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara is not null)
|
||||||
|
{
|
||||||
|
if (currentPara.ParagraphProperties?.GetFirstChild<SectionProperties>() is null)
|
||||||
|
{
|
||||||
|
bool addPageSize = (lastOrientation.Value == PageBreakType.NewLandscapeSection);
|
||||||
|
AddSectionProperties(currentPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если исходная секция была landscape, внутри группы была смена, и последняя ориентация — книжная,
|
||||||
|
// добавляем landscape секцию в Body, чтобы остаток остался landscape.
|
||||||
|
if (body is not null)
|
||||||
|
{
|
||||||
|
var sourcePageSize = sourceSection.GetFirstChild<PageSize>();
|
||||||
|
if (sourcePageSize is not null)
|
||||||
|
{
|
||||||
|
bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape ||
|
||||||
|
(sourcePageSize.Width?.Value > sourcePageSize.Height?.Value);
|
||||||
|
bool lastIsPortrait = lastOrientation.HasValue && lastOrientation.Value == PageBreakType.NewPortraitSection;
|
||||||
|
if (sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait)
|
||||||
|
{
|
||||||
|
// Проверяем, есть ли уже секция landscape на Body
|
||||||
|
bool hasBodyLandscape = false;
|
||||||
|
foreach (var bodySec in body.Elements<SectionProperties>())
|
||||||
|
{
|
||||||
|
var ps = bodySec.GetFirstChild<PageSize>();
|
||||||
|
if (ps is not null && ps.Orient?.Value == PageOrientationValues.Landscape)
|
||||||
|
{
|
||||||
|
hasBodyLandscape = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasBodyLandscape)
|
||||||
|
{
|
||||||
|
// Создаём секцию landscape для Body
|
||||||
|
var bodySection = new SectionProperties();
|
||||||
|
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
|
||||||
|
// Если ориентация не landscape, меняем
|
||||||
|
if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape)
|
||||||
|
{
|
||||||
|
pageSizeClone.SwapValues();
|
||||||
|
pageSizeClone.Orient = PageOrientationValues.Landscape;
|
||||||
|
}
|
||||||
|
bodySection.AppendChild(pageSizeClone);
|
||||||
|
var sourceMargin = sourceSection.GetFirstChild<PageMargin>();
|
||||||
|
if (sourceMargin is not null)
|
||||||
|
{
|
||||||
|
var marginClone = (PageMargin)sourceMargin.CloneNode(true);
|
||||||
|
// Если исходная секция не landscape, но мы делаем landscape, меняем поля
|
||||||
|
if (sourceSection.GetFirstChild<PageSize>()?.Orient?.Value != PageOrientationValues.Landscape)
|
||||||
|
{
|
||||||
|
marginClone.SwapBottomRight();
|
||||||
|
}
|
||||||
|
bodySection.AppendChild(marginClone);
|
||||||
|
}
|
||||||
|
bodySection.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
|
||||||
|
body.AppendChild(bodySection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
currentPos = match.End;
|
currentPos = match.End;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Текст после последнего совпадения – используем BuildAfterParagraph, чтобы пропустить лишние разрывы
|
// 6. Обработка остатка текста (если есть)
|
||||||
if (currentPos < fullText.Length)
|
if (currentPos < fullText.Length)
|
||||||
{
|
{
|
||||||
var textPart = BuildAfterParagraph(original, structure, currentPos);
|
var remainderPara = BuildRemainderParagraph(original, structure, currentPos);
|
||||||
if (textPart is not null)
|
if (remainderPara is not null)
|
||||||
{
|
{
|
||||||
if (currentPara is null)
|
// Если внутри группы была смена, применяем последнюю ориентацию к остатку
|
||||||
|
if (sectionChangeInsideGroup && lastOrientation.HasValue)
|
||||||
{
|
{
|
||||||
currentPara = textPart;
|
var breakRun = new Run(new Break { Type = BreakValues.Page });
|
||||||
resultParas.Add(currentPara);
|
remainderPara.InsertAt(breakRun, 0);
|
||||||
}
|
bool addPageSize = (lastOrientation.Value == PageBreakType.NewLandscapeSection);
|
||||||
else
|
AddSectionProperties(remainderPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
|
||||||
{
|
|
||||||
MergeParagraph(currentPara, textPart);
|
|
||||||
}
|
}
|
||||||
|
resultParas.Add(remainderPara);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Удаляем пустые параграфы
|
// 7. Очистка пустых параграфов
|
||||||
for (int i = resultParas.Count - 1; i >= 0; i--)
|
for (int i = resultParas.Count - 1; i >= 0; i--)
|
||||||
{
|
{
|
||||||
if (!resultParas[i].ChildElements.OfType<Run>().Any() && resultParas[i].ParagraphProperties is null)
|
var p = resultParas[i];
|
||||||
|
if (!p.ChildElements.OfType<Run>().Any() && p.ParagraphProperties is null)
|
||||||
resultParas.RemoveAt(i);
|
resultParas.RemoveAt(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Логирование
|
||||||
|
#if DEBUG
|
||||||
|
if (body is not null)
|
||||||
|
LogDocumentStructure(body, "FINAL DOCUMENT STRUCTURE");
|
||||||
|
#endif
|
||||||
|
|
||||||
return resultParas.Count > 0 ? resultParas : null;
|
return resultParas.Count > 0 ? resultParas : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,70 @@
|
|||||||
namespace QWERTYkez.WordProcessor;
|
namespace QWERTYkez.WordProcessor;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Определяет тип разрыва или смены ориентации страницы, применяется к элементам следующим после замены
|
||||||
|
/// </summary>
|
||||||
|
public enum PageBreakType
|
||||||
|
{
|
||||||
|
/// <summary>Без разрыва или смены ориентации.</summary>
|
||||||
|
None,
|
||||||
|
|
||||||
|
/// <summary>Обычный разрыв страницы (новый лист).</summary>
|
||||||
|
PageBreak,
|
||||||
|
|
||||||
|
/// <summary>Начать новую секцию с альбомной ориентацией страницы.</summary>
|
||||||
|
NewLandscapeSection,
|
||||||
|
|
||||||
|
/// <summary>Начать новую секцию с книжной ориентацией страницы.</summary>
|
||||||
|
NewPortraitSection,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Представляет элемент замены текста, содержащий сам текст и указание
|
||||||
|
/// на тип разрыва или смены ориентации, который должен быть применён
|
||||||
|
/// после вставки этого текста.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Используется в методах множественной замены, например,
|
||||||
|
/// <see cref="IWordWriter.ReplaceItem(string, IEnumerable{ReplaceItem})"/>.
|
||||||
|
/// </remarks>
|
||||||
public readonly struct ReplaceItem
|
public readonly struct ReplaceItem
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Инициализирует новый экземпляр <see cref="ReplaceItem"/> с пустым текстом
|
||||||
|
/// и типом разрыва <see cref="PageBreakType.None"/>.
|
||||||
|
/// </summary>
|
||||||
public ReplaceItem() { }
|
public ReplaceItem() { }
|
||||||
public ReplaceItem(string text)
|
|
||||||
|
/// <summary>
|
||||||
|
/// Инициализирует новый экземпляр <see cref="ReplaceItem"/> с указанным текстом
|
||||||
|
/// и типом разрыва/смены ориентации.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">Текст, который будет вставлен вместо плейсхолдера.</param>
|
||||||
|
/// <param name="splitValue">
|
||||||
|
/// Тип разрыва или смены ориентации, который будет применён после вставки текста.
|
||||||
|
/// По умолчанию <see cref="PageBreakType.None"/>.
|
||||||
|
/// </param>
|
||||||
|
public ReplaceItem(string text, PageBreakType splitValue = PageBreakType.None)
|
||||||
{
|
{
|
||||||
Text = text;
|
Text = text;
|
||||||
}
|
SplitValue = splitValue;
|
||||||
public ReplaceItem(string text, bool breakPage)
|
|
||||||
{
|
|
||||||
Text = text;
|
|
||||||
BreakPage = breakPage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получает текст, который будет вставлен вместо плейсхолдера.
|
||||||
|
/// </summary>
|
||||||
public string Text { get; init; } = string.Empty;
|
public string Text { get; init; } = string.Empty;
|
||||||
public bool BreakPage { get; init; } = false;
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получает тип разрыва или смены ориентации, который будет применён
|
||||||
|
/// после вставки текста.
|
||||||
|
/// </summary>
|
||||||
|
public PageBreakType SplitValue { get; init; } = PageBreakType.None;
|
||||||
|
|
||||||
// Неявное преобразование из ReplaceItem в string
|
/// <summary>
|
||||||
//public static implicit operator string(ReplaceItem item) => item.Text;
|
/// Определяет явное преобразование из строки в <see cref="ReplaceItem"/>.
|
||||||
// Явное преобразование из string в ReplaceItem
|
/// </summary>
|
||||||
|
/// <param name="text">Строка текста.</param>
|
||||||
|
/// <returns>Новый экземпляр <see cref="ReplaceItem"/> с указанным текстом и <see cref="PageBreakType.None"/>.</returns>
|
||||||
public static explicit operator ReplaceItem(string text) => new() { Text = text };
|
public static explicit operator ReplaceItem(string text) => new() { Text = text };
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,7 @@ internal static class SimplyReplaceExt
|
|||||||
internal readonly int Length = length;
|
internal readonly int Length = length;
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class ParagraphStructure(string fullText, SimplyReplaceExt.TextNodeInfo[] textNodes)
|
private sealed class ParagraphStructure(string fullText, TextNodeInfo[] textNodes)
|
||||||
{
|
{
|
||||||
internal readonly string FullText = fullText;
|
internal readonly string FullText = fullText;
|
||||||
internal readonly TextNodeInfo[] TextNodes = textNodes;
|
internal readonly TextNodeInfo[] TextNodes = textNodes;
|
||||||
@@ -77,7 +77,7 @@ internal static class SimplyReplaceExt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, bool breakPage = false)
|
internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, PageBreakType splitValue = PageBreakType.None)
|
||||||
{
|
{
|
||||||
if (paragraph is null || string.IsNullOrEmpty(oldValue))
|
if (paragraph is null || string.IsNullOrEmpty(oldValue))
|
||||||
return false;
|
return false;
|
||||||
@@ -103,10 +103,13 @@ internal static class SimplyReplaceExt
|
|||||||
if (nodesToReplace.Count == 0)
|
if (nodesToReplace.Count == 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, newValue, breakPage);
|
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, newValue, splitValue);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, bool breakPage)
|
||||||
|
=> SimpleReplace(paragraph, oldValue, newValue, comparisonType, breakPage ? PageBreakType.PageBreak : PageBreakType.None);
|
||||||
|
|
||||||
internal static void Replace(this Paragraph paragraph, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
|
internal static void Replace(this Paragraph paragraph, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
|
||||||
{
|
{
|
||||||
if (paragraph is null || replacements is null || replacements.Count() == 0)
|
if (paragraph is null || replacements is null || replacements.Count() == 0)
|
||||||
@@ -120,10 +123,8 @@ internal static class SimplyReplaceExt
|
|||||||
if (structure.FullText.Length == 0)
|
if (structure.FullText.Length == 0)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Используем List с предопределенной емкостью
|
|
||||||
var replacementsInParagraph = new List<ReplacementInfo>(replacements.Count() * 2);
|
var replacementsInParagraph = new List<ReplacementInfo>(replacements.Count() * 2);
|
||||||
|
|
||||||
// Сначала находим все вхождения
|
|
||||||
var fullText = structure.FullText;
|
var fullText = structure.FullText;
|
||||||
foreach (var kvp in replacements)
|
foreach (var kvp in replacements)
|
||||||
{
|
{
|
||||||
@@ -137,7 +138,8 @@ internal static class SimplyReplaceExt
|
|||||||
{
|
{
|
||||||
OldValue = kvp.Key,
|
OldValue = kvp.Key,
|
||||||
NewValue = kvp.Value ?? string.Empty,
|
NewValue = kvp.Value ?? string.Empty,
|
||||||
Index = pos
|
Index = pos,
|
||||||
|
SplitValue = PageBreakType.None
|
||||||
});
|
});
|
||||||
pos += kvp.Key.Length;
|
pos += kvp.Key.Length;
|
||||||
}
|
}
|
||||||
@@ -146,10 +148,8 @@ internal static class SimplyReplaceExt
|
|||||||
if (replacementsInParagraph.Count == 0)
|
if (replacementsInParagraph.Count == 0)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Сортируем по убыванию позиции
|
|
||||||
replacementsInParagraph.Sort((x, y) => y.Index.CompareTo(x.Index));
|
replacementsInParagraph.Sort((x, y) => y.Index.CompareTo(x.Index));
|
||||||
|
|
||||||
// Выполняем замены
|
|
||||||
for (int i = 0; i < replacementsInParagraph.Count; i++)
|
for (int i = 0; i < replacementsInParagraph.Count; i++)
|
||||||
{
|
{
|
||||||
var replacement = replacementsInParagraph[i];
|
var replacement = replacementsInParagraph[i];
|
||||||
@@ -159,7 +159,7 @@ internal static class SimplyReplaceExt
|
|||||||
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
||||||
if (nodesToReplace.Count > 0)
|
if (nodesToReplace.Count > 0)
|
||||||
{
|
{
|
||||||
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue);
|
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.SplitValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -177,10 +177,8 @@ internal static class SimplyReplaceExt
|
|||||||
if (structure.FullText.Length == 0)
|
if (structure.FullText.Length == 0)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Используем List с предопределенной емкостью
|
|
||||||
var replacementsInParagraph = new List<ReplacementInfo>(replacements.Count() * 2);
|
var replacementsInParagraph = new List<ReplacementInfo>(replacements.Count() * 2);
|
||||||
|
|
||||||
// Сначала находим все вхождения
|
|
||||||
var fullText = structure.FullText;
|
var fullText = structure.FullText;
|
||||||
foreach (var kvp in replacements)
|
foreach (var kvp in replacements)
|
||||||
{
|
{
|
||||||
@@ -194,8 +192,8 @@ internal static class SimplyReplaceExt
|
|||||||
{
|
{
|
||||||
OldValue = kvp.Key,
|
OldValue = kvp.Key,
|
||||||
NewValue = kvp.Value.Text ?? string.Empty,
|
NewValue = kvp.Value.Text ?? string.Empty,
|
||||||
BreakPage = kvp.Value.BreakPage,
|
Index = pos,
|
||||||
Index = pos
|
SplitValue = kvp.Value.SplitValue
|
||||||
});
|
});
|
||||||
pos += kvp.Key.Length;
|
pos += kvp.Key.Length;
|
||||||
}
|
}
|
||||||
@@ -204,10 +202,8 @@ internal static class SimplyReplaceExt
|
|||||||
if (replacementsInParagraph.Count == 0)
|
if (replacementsInParagraph.Count == 0)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Сортируем по убыванию позиции
|
|
||||||
replacementsInParagraph.Sort((x, y) => y.Index.CompareTo(x.Index));
|
replacementsInParagraph.Sort((x, y) => y.Index.CompareTo(x.Index));
|
||||||
|
|
||||||
// Выполняем замены
|
|
||||||
for (int i = 0; i < replacementsInParagraph.Count; i++)
|
for (int i = 0; i < replacementsInParagraph.Count; i++)
|
||||||
{
|
{
|
||||||
var replacement = replacementsInParagraph[i];
|
var replacement = replacementsInParagraph[i];
|
||||||
@@ -217,7 +213,7 @@ internal static class SimplyReplaceExt
|
|||||||
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
||||||
if (nodesToReplace.Count > 0)
|
if (nodesToReplace.Count > 0)
|
||||||
{
|
{
|
||||||
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.BreakPage);
|
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.SplitValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,7 +223,7 @@ internal static class SimplyReplaceExt
|
|||||||
internal string OldValue { get; set; } = null!;
|
internal string OldValue { get; set; } = null!;
|
||||||
internal string NewValue { get; set; } = null!;
|
internal string NewValue { get; set; } = null!;
|
||||||
internal int Index { get; set; }
|
internal int Index { get; set; }
|
||||||
internal bool BreakPage { get; set; }
|
internal PageBreakType SplitValue { get; set; } = PageBreakType.None;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ParagraphStructure AnalyzeParagraphStructure(IEnumerable<Run> runs)
|
private static ParagraphStructure AnalyzeParagraphStructure(IEnumerable<Run> runs)
|
||||||
@@ -291,7 +287,7 @@ internal static class SimplyReplaceExt
|
|||||||
int matchStart,
|
int matchStart,
|
||||||
int matchEnd,
|
int matchEnd,
|
||||||
string newValue,
|
string newValue,
|
||||||
bool breakPage = false)
|
PageBreakType splitValue)
|
||||||
{
|
{
|
||||||
if (nodesToReplace.Count == 0) return;
|
if (nodesToReplace.Count == 0) return;
|
||||||
|
|
||||||
@@ -311,22 +307,61 @@ internal static class SimplyReplaceExt
|
|||||||
processedNewValue
|
processedNewValue
|
||||||
);
|
);
|
||||||
|
|
||||||
// Очищаем остальные текстовые ноды
|
|
||||||
for (int i = 1; i < nodesToReplace.Count; i++)
|
for (int i = 1; i < nodesToReplace.Count; i++)
|
||||||
{
|
{
|
||||||
nodesToReplace[i].Text.Text = string.Empty;
|
nodesToReplace[i].Text.Text = string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (breakPage)
|
if (splitValue == PageBreakType.PageBreak)
|
||||||
{
|
{
|
||||||
if (nodesToReplace[0].Text.Parent is Run run && run.Parent is Paragraph para)
|
if (nodesToReplace[0].Text.Parent is Run run && run.Parent is Paragraph para)
|
||||||
{
|
{
|
||||||
var breakRun = new Run(new Break() { Type = BreakValues.Page });
|
var breakRun = new Run(new Break { Type = BreakValues.Page });
|
||||||
if (run.RunProperties is not null)
|
if (run.RunProperties is not null)
|
||||||
breakRun.RunProperties = (RunProperties)run.RunProperties.CloneNode(true);
|
breakRun.RunProperties = (RunProperties)run.RunProperties.CloneNode(true);
|
||||||
para.AppendChild(breakRun);
|
para.AppendChild(breakRun);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if (splitValue == PageBreakType.NewLandscapeSection || splitValue == PageBreakType.NewPortraitSection)
|
||||||
|
{
|
||||||
|
var firstText = nodesToReplace[0].Text;
|
||||||
|
if (firstText.Parent is Run run && run.Parent is Paragraph para)
|
||||||
|
{
|
||||||
|
AddSectionProperties(para, splitValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue)
|
||||||
|
{
|
||||||
|
if (para is null) return;
|
||||||
|
PageOrientationValues orientation = splitValue == PageBreakType.NewLandscapeSection
|
||||||
|
? PageOrientationValues.Landscape
|
||||||
|
: PageOrientationValues.Portrait;
|
||||||
|
|
||||||
|
uint width, height;
|
||||||
|
if (orientation == PageOrientationValues.Landscape)
|
||||||
|
{
|
||||||
|
width = 16838;
|
||||||
|
height = 11906;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
width = 11906;
|
||||||
|
height = 16838;
|
||||||
|
}
|
||||||
|
|
||||||
|
var sectionProps = new SectionProperties(
|
||||||
|
new PageSize
|
||||||
|
{
|
||||||
|
Width = width,
|
||||||
|
Height = height,
|
||||||
|
Orient = orientation
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
para.ParagraphProperties ??= new ParagraphProperties();
|
||||||
|
para.ParagraphProperties.AppendChild(sectionProps);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static unsafe string ReplaceSpacesWithNonBreaking(string input)
|
private static unsafe string ReplaceSpacesWithNonBreaking(string input)
|
||||||
@@ -358,7 +393,6 @@ internal static class SimplyReplaceExt
|
|||||||
|
|
||||||
int end = Math.Min(start + length, original.Length);
|
int end = Math.Min(start + length, original.Length);
|
||||||
|
|
||||||
// Оптимизированная конкатенация
|
|
||||||
var sb = new StringBuilder(original.Length - length + replacement.Length);
|
var sb = new StringBuilder(original.Length - length + replacement.Length);
|
||||||
if (start > 0)
|
if (start > 0)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ internal class WordReader : IDisposable, IWordReader
|
|||||||
|
|
||||||
internal static WordReader? CreateInternal(FileInfo sourceFile)
|
internal static WordReader? CreateInternal(FileInfo sourceFile)
|
||||||
{
|
{
|
||||||
if (sourceFile is null || !sourceFile.Exists)
|
if (sourceFile is null || !File.Exists(sourceFile.FullName))
|
||||||
{
|
{
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
Debug.WriteLine($"[DEBUG] Source file is null or does not exist: {sourceFile?.FullName}");
|
Debug.WriteLine($"[DEBUG] Source file is null or does not exist: {sourceFile?.FullName}");
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ internal sealed class WordWriter : WordReader, IWordWriter
|
|||||||
|
|
||||||
internal static WordWriter? CreateInternal(FileInfo sourceFile, string? destinationPath = null!)
|
internal static WordWriter? CreateInternal(FileInfo sourceFile, string? destinationPath = null!)
|
||||||
{
|
{
|
||||||
if (sourceFile is null || !sourceFile.Exists) return null;
|
if (sourceFile is null || !File.Exists(sourceFile.FullName)) return null;
|
||||||
|
|
||||||
var ms = new MemoryStream();
|
var ms = new MemoryStream();
|
||||||
try
|
try
|
||||||
|
|||||||
Reference in New Issue
Block a user