Добавьте файлы проекта.
This commit is contained in:
89
QWERTYkez.WordProcessor/Builders/CellProps.cs
Normal file
89
QWERTYkez.WordProcessor/Builders/CellProps.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
public readonly struct CellProps(double? width = null!)
|
||||
{
|
||||
public double? Width { get; init; } = width;
|
||||
public TableVerticalAlignmentValues? VerticalAlignment { get; init; } = default;
|
||||
public MergedCell? Merge { get; init; } = default;
|
||||
|
||||
|
||||
#pragma warning disable IDE1006 // Стили именования
|
||||
public static CellProps V_H_ { get; } = new() { Merge = MergedCell.V_H_ };
|
||||
public static CellProps H_ { get; } = new() { Merge = MergedCell.H_ };
|
||||
public static CellProps V_ { get; } = new() { Merge = MergedCell.V_ };
|
||||
public static CellProps _V_H { get; } = new() { Merge = MergedCell._V_H };
|
||||
public static CellProps _H { get; } = new() { Merge = MergedCell._H };
|
||||
public static CellProps _V { get; } = new() { Merge = MergedCell._V };
|
||||
public static CellProps _VH_ { get; } = new() { Merge = MergedCell._VH_ };
|
||||
public static CellProps V__H { get; } = new() { Merge = MergedCell.V__H };
|
||||
#pragma warning restore IDE1006 // Стили именования
|
||||
|
||||
|
||||
internal bool TryExtract(out List<OpenXmlElement> list)
|
||||
{
|
||||
list =
|
||||
[
|
||||
new TableCellVerticalAlignment() { Val = VerticalAlignment ?? TableVerticalAlignmentValues.Center },
|
||||
new TableCellMargin()
|
||||
{
|
||||
TopMargin = new TopMargin() { Width = "0" },
|
||||
BottomMargin = new BottomMargin() { Width = "0" },
|
||||
LeftMargin = new LeftMargin() { Width = "0" },
|
||||
RightMargin = new RightMargin() { Width = "0" }
|
||||
}
|
||||
];
|
||||
|
||||
if (Width.HasValue)
|
||||
list.Add(new TableCellWidth()
|
||||
{
|
||||
Type = TableWidthUnitValues.Dxa,
|
||||
Width = ((uint)(Width.Value * 567d)).ToString() // 1 см = 567 DXA
|
||||
});
|
||||
|
||||
if (Merge.HasValue)
|
||||
{
|
||||
switch (Merge.Value)
|
||||
{
|
||||
case MergedCell.V_H_:
|
||||
list.Add(new HorizontalMerge() { Val = MergedCellValues.Restart });
|
||||
list.Add(new VerticalMerge() { Val = MergedCellValues.Restart });
|
||||
break;
|
||||
case MergedCell.H_:
|
||||
list.Add(new HorizontalMerge() { Val = MergedCellValues.Restart }); break;
|
||||
case MergedCell.V_:
|
||||
list.Add(new VerticalMerge() { Val = MergedCellValues.Restart }); break;
|
||||
case MergedCell._V_H:
|
||||
list.Add(new HorizontalMerge() { Val = MergedCellValues.Continue });
|
||||
list.Add(new VerticalMerge() { Val = MergedCellValues.Continue });
|
||||
break;
|
||||
case MergedCell._H:
|
||||
list.Add(new HorizontalMerge() { Val = MergedCellValues.Continue }); break;
|
||||
case MergedCell._V:
|
||||
list.Add(new VerticalMerge() { Val = MergedCellValues.Continue }); break;
|
||||
case MergedCell._VH_:
|
||||
list.Add(new HorizontalMerge() { Val = MergedCellValues.Restart });
|
||||
list.Add(new VerticalMerge() { Val = MergedCellValues.Continue });
|
||||
break;
|
||||
case MergedCell.V__H:
|
||||
list.Add(new HorizontalMerge() { Val = MergedCellValues.Continue });
|
||||
list.Add(new VerticalMerge() { Val = MergedCellValues.Restart });
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return list.Count > 0;
|
||||
}
|
||||
}
|
||||
public enum MergedCell
|
||||
{
|
||||
V_H_,
|
||||
H_,
|
||||
V_,
|
||||
|
||||
_V_H,
|
||||
_H,
|
||||
_V,
|
||||
|
||||
_VH_,
|
||||
V__H,
|
||||
}
|
||||
162
QWERTYkez.WordProcessor/Builders/FontProps.cs
Normal file
162
QWERTYkez.WordProcessor/Builders/FontProps.cs
Normal file
@@ -0,0 +1,162 @@
|
||||
using MathStyle = DocumentFormat.OpenXml.Math.Style;
|
||||
using MathStyleValues = DocumentFormat.OpenXml.Math.StyleValues;
|
||||
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
public record FontProps
|
||||
{
|
||||
public FontProps(double? size = null) => Size = size ?? 12;
|
||||
|
||||
public string? FontFamily { get; init; }
|
||||
|
||||
public double? Size
|
||||
{
|
||||
get => _SizeD.HasValue ? _SizeD.Value / 2d : null;
|
||||
init => _SizeD = value.HasValue ? (uint?)(value.Value * 2) : null;
|
||||
}
|
||||
uint? _SizeD;
|
||||
|
||||
public bool IsItalic { get; init; } = false;
|
||||
|
||||
public bool IsBold { get; init; } = false;
|
||||
|
||||
public UnderlineValues? Underline { get; init; }
|
||||
|
||||
public VerticalPositionValues? SubSup { get; init; }
|
||||
|
||||
public string? Color { get; init; }
|
||||
|
||||
|
||||
public bool TryExtract(out List<OpenXmlElement> list)
|
||||
{
|
||||
list = [];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(FontFamily))
|
||||
list.Add(new RunFonts { Ascii = FontFamily, HighAnsi = FontFamily });
|
||||
|
||||
if (_SizeD is not null)
|
||||
list.Add(new FontSize { Val = _SizeD.Value.ToString() });
|
||||
|
||||
if (IsBold)
|
||||
list.Add(new Bold());
|
||||
|
||||
if (IsItalic)
|
||||
list.Add(new Italic());
|
||||
|
||||
if (Underline is not null)
|
||||
list.Add(new Underline { Val = Underline });
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Color))
|
||||
list.Add(new Color { Val = Color });
|
||||
|
||||
if (SubSup is not null)
|
||||
list.Add(new VerticalTextAlignment { Val = SubSup });
|
||||
|
||||
return list.Count > 0;
|
||||
}
|
||||
public bool TryExtractWithoutFamily(out List<OpenXmlElement> list)
|
||||
{
|
||||
list = [];
|
||||
|
||||
if (_SizeD is not null)
|
||||
list.Add(new FontSize { Val = _SizeD.Value.ToString() });
|
||||
|
||||
if (IsBold)
|
||||
list.Add(new Bold());
|
||||
|
||||
if (IsItalic)
|
||||
list.Add(new Italic());
|
||||
|
||||
if (Underline is not null)
|
||||
list.Add(new Underline { Val = Underline });
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Color))
|
||||
list.Add(new Color { Val = Color });
|
||||
|
||||
if (SubSup is not null)
|
||||
list.Add(new VerticalTextAlignment { Val = SubSup });
|
||||
|
||||
return list.Count > 0;
|
||||
}
|
||||
public bool TrySupExtract(out List<OpenXmlElement> list)
|
||||
{
|
||||
list = [];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(FontFamily))
|
||||
list.Add(new RunFonts { Ascii = FontFamily, HighAnsi = FontFamily });
|
||||
|
||||
if (_SizeD is not null)
|
||||
list.Add(new FontSize { Val = _SizeD.Value.ToString() });
|
||||
|
||||
if (IsBold)
|
||||
list.Add(new Bold());
|
||||
|
||||
if (IsItalic)
|
||||
list.Add(new Italic());
|
||||
|
||||
if (Underline is not null)
|
||||
list.Add(new Underline { Val = Underline });
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Color))
|
||||
list.Add(new Color { Val = Color });
|
||||
|
||||
list.Add(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript });
|
||||
|
||||
return list.Count > 0;
|
||||
}
|
||||
public bool TrySubExtract(out List<OpenXmlElement> list)
|
||||
{
|
||||
list = [];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(FontFamily))
|
||||
list.Add(new RunFonts { Ascii = FontFamily, HighAnsi = FontFamily });
|
||||
|
||||
if (_SizeD is not null)
|
||||
list.Add(new FontSize { Val = _SizeD.Value.ToString() });
|
||||
|
||||
if (IsBold)
|
||||
list.Add(new Bold());
|
||||
|
||||
if (IsItalic)
|
||||
list.Add(new Italic());
|
||||
|
||||
if (Underline is not null)
|
||||
list.Add(new Underline { Val = Underline });
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Color))
|
||||
list.Add(new Color { Val = Color });
|
||||
|
||||
list.Add(new VerticalTextAlignment { Val = VerticalPositionValues.Subscript });
|
||||
|
||||
return list.Count > 0;
|
||||
}
|
||||
|
||||
public bool TryExtractForMath(out List<OpenXmlElement> list)
|
||||
{
|
||||
list = [];
|
||||
|
||||
// Для математики используем только элемент Style
|
||||
if (IsBold)
|
||||
list.Add(new MathStyle { Val = MathStyleValues.BoldItalic });
|
||||
else list.Add(new MathStyle { Val = MathStyleValues.Italic });
|
||||
// Обычное начертание можно не добавлять, так как по умолчанию и так обычное
|
||||
// (но если нужно явно сбросить, можно добавить Style { Val = StyleValues.Plain })
|
||||
|
||||
return list.Count > 0;
|
||||
}
|
||||
|
||||
// Фабричные методы для создания FontProps
|
||||
public static FontProps Default => new();
|
||||
|
||||
public static FontProps WithFont(string fontFamily, double? size = null) =>
|
||||
new(size) { FontFamily = fontFamily };
|
||||
|
||||
public static FontProps WithSize(double size) =>
|
||||
new(size);
|
||||
|
||||
public static FontProps WithStyle(bool bold = false, bool italic = false) =>
|
||||
new() { IsBold = bold, IsItalic = italic };
|
||||
|
||||
public static FontProps WithColor(string hexColor) =>
|
||||
new() { Color = hexColor };
|
||||
}
|
||||
357
QWERTYkez.WordProcessor/Builders/FormulaHelper.cs
Normal file
357
QWERTYkez.WordProcessor/Builders/FormulaHelper.cs
Normal file
@@ -0,0 +1,357 @@
|
||||
using Base = DocumentFormat.OpenXml.Math.Base;
|
||||
using ControlProperties = DocumentFormat.OpenXml.Math.ControlProperties;
|
||||
using Degree = DocumentFormat.OpenXml.Math.Degree;
|
||||
using Denominator = DocumentFormat.OpenXml.Math.Denominator;
|
||||
using Fraction = DocumentFormat.OpenXml.Math.Fraction;
|
||||
using FractionProperties = DocumentFormat.OpenXml.Math.FractionProperties;
|
||||
using HideDegree = DocumentFormat.OpenXml.Math.HideDegree;
|
||||
using MathRun = DocumentFormat.OpenXml.Math.Run;
|
||||
using MathRunProperties = DocumentFormat.OpenXml.Math.RunProperties;
|
||||
using MathText = DocumentFormat.OpenXml.Math.Text;
|
||||
using Numerator = DocumentFormat.OpenXml.Math.Numerator;
|
||||
using Radical = DocumentFormat.OpenXml.Math.Radical;
|
||||
using RadicalProperties = DocumentFormat.OpenXml.Math.RadicalProperties;
|
||||
using SubArgument = DocumentFormat.OpenXml.Math.SubArgument;
|
||||
using Subscript = DocumentFormat.OpenXml.Math.Subscript;
|
||||
using SubSuperscript = DocumentFormat.OpenXml.Math.SubSuperscript;
|
||||
using SuperArgument = DocumentFormat.OpenXml.Math.SuperArgument;
|
||||
using Superscript = DocumentFormat.OpenXml.Math.Superscript;
|
||||
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
internal static class FormulaHelper
|
||||
{
|
||||
// Вспомогательный метод для создания MathRun с форматированием
|
||||
public static MathRun CreateMathRun(FontProps? font)
|
||||
{
|
||||
var mathRun = new MathRun();
|
||||
|
||||
// 1. Математический стиль (полужирный/курсив) – добавляем первым
|
||||
if (font is not null && font.TryExtractForMath(out var mathStyleElements))
|
||||
{
|
||||
var mathPr = new MathRunProperties(mathStyleElements);
|
||||
mathRun.AppendChild(mathPr);
|
||||
}
|
||||
|
||||
// 2. Wordprocessing: цвет, размер, подчёркивание (без семейства шрифта)
|
||||
var wordPr = new RunProperties();
|
||||
if (font is not null && font.TryExtractWithoutFamily(out var wordElements))
|
||||
{
|
||||
foreach (var elem in wordElements)
|
||||
wordPr.AppendChild(elem.CloneNode(true));
|
||||
}
|
||||
mathRun.AppendChild(wordPr);
|
||||
|
||||
return mathRun;
|
||||
}
|
||||
|
||||
public static void AddText(OpenXmlElement parent, string text, FontProps? font)
|
||||
{
|
||||
if (parent is MathRun mathRun)
|
||||
{
|
||||
mathRun.AppendChild(new MathText(text));
|
||||
}
|
||||
else
|
||||
{
|
||||
var run = CreateMathRun(font);
|
||||
run.AppendChild(new MathText(text));
|
||||
parent.AppendChild(run);
|
||||
}
|
||||
}
|
||||
|
||||
public static Fraction CreateFraction(
|
||||
Action<IFormula> numeratorBuilder,
|
||||
Action<IFormula> denominatorBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var fraction = new Fraction();
|
||||
var font = builder.BaseFont;
|
||||
|
||||
// Добавляем свойства дроби с форматированием (для черты дроби)
|
||||
var fPr = new FractionProperties();
|
||||
if (font.TryExtractWithoutFamily(out var wordElements))
|
||||
{
|
||||
var ctrlPr = new ControlProperties();
|
||||
var rPr = new RunProperties();
|
||||
foreach (var elem in wordElements)
|
||||
rPr.AppendChild(elem.CloneNode(true));
|
||||
rPr.AppendChild(new RunFonts { Ascii = "Cambria Math", HighAnsi = "Cambria Math" });
|
||||
ctrlPr.AppendChild(rPr);
|
||||
fPr.AppendChild(ctrlPr);
|
||||
}
|
||||
fraction.AppendChild(fPr);
|
||||
|
||||
// Числитель
|
||||
var numeratorElem = new Numerator();
|
||||
fraction.AppendChild(numeratorElem);
|
||||
builder.PushContext(numeratorElem);
|
||||
numeratorBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
// Знаменатель
|
||||
var denominatorElem = new Denominator();
|
||||
fraction.AppendChild(denominatorElem);
|
||||
builder.PushContext(denominatorElem);
|
||||
denominatorBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
return fraction;
|
||||
}
|
||||
|
||||
public static Radical CreateRadical(
|
||||
Action<IFormula> radicandBuilder,
|
||||
Action<IFormula>? degreeBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var radical = new Radical();
|
||||
var font = builder.BaseFont;
|
||||
|
||||
var radPr = new RadicalProperties();
|
||||
|
||||
// Цвет, размер и подчёркивание для знака корня (ControlProperties)
|
||||
if (font is not null && font.TryExtractWithoutFamily(out var wordElements))
|
||||
{
|
||||
var ctrlPr = new ControlProperties();
|
||||
var rPr = new RunProperties();
|
||||
foreach (var elem in wordElements)
|
||||
rPr.AppendChild(elem.CloneNode(true));
|
||||
rPr.AppendChild(new RunFonts { Ascii = "Cambria Math", HighAnsi = "Cambria Math" });
|
||||
ctrlPr.AppendChild(rPr);
|
||||
radPr.AppendChild(ctrlPr);
|
||||
}
|
||||
|
||||
// Если степень не задана, скрываем её
|
||||
if (degreeBuilder is null)
|
||||
{
|
||||
radPr.HideDegree = new HideDegree { Val = DocumentFormat.OpenXml.Math.BooleanValues.One };
|
||||
}
|
||||
|
||||
// Добавляем свойства радикала (с цветом)
|
||||
radical.AppendChild(radPr);
|
||||
|
||||
// Степень (если есть)
|
||||
if (degreeBuilder is not null)
|
||||
{
|
||||
var degree = new Degree();
|
||||
radical.AppendChild(degree);
|
||||
builder.PushContext(degree);
|
||||
degreeBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
|
||||
// Подкоренное выражение
|
||||
var radicand = new Base();
|
||||
radical.AppendChild(radicand);
|
||||
builder.PushContext(radicand);
|
||||
radicandBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
return radical;
|
||||
}
|
||||
|
||||
public static void AddIntegral(
|
||||
OpenXmlElement currentContext,
|
||||
Action<IFormula> functionBuilder,
|
||||
Action<IFormula> differentialBuilder,
|
||||
Action<IFormula>? lowerLimitBuilder,
|
||||
Action<IFormula>? upperLimitBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var font = builder.BaseFont;
|
||||
|
||||
if (lowerLimitBuilder is null && upperLimitBuilder is null)
|
||||
{
|
||||
var integralRun = CreateMathRun(font);
|
||||
integralRun.AppendChild(new MathText("∫"));
|
||||
currentContext.AppendChild(integralRun);
|
||||
|
||||
var funcRun = CreateMathRun(font);
|
||||
currentContext.AppendChild(funcRun);
|
||||
builder.PushContext(funcRun);
|
||||
functionBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
var diffRun = CreateMathRun(font);
|
||||
currentContext.AppendChild(diffRun);
|
||||
builder.PushContext(diffRun);
|
||||
differentialBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
else
|
||||
{
|
||||
var integralWithLimits = new SubSuperscript();
|
||||
currentContext.AppendChild(integralWithLimits);
|
||||
|
||||
var baseElem = new Base();
|
||||
var integralRun = CreateMathRun(font);
|
||||
integralRun.AppendChild(new MathText("∫"));
|
||||
baseElem.AppendChild(integralRun);
|
||||
integralWithLimits.AppendChild(baseElem);
|
||||
|
||||
if (lowerLimitBuilder is not null)
|
||||
{
|
||||
var subArg = new SubArgument();
|
||||
integralWithLimits.AppendChild(subArg);
|
||||
builder.PushContext(subArg);
|
||||
lowerLimitBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
if (upperLimitBuilder is not null)
|
||||
{
|
||||
var superArg = new SuperArgument();
|
||||
integralWithLimits.AppendChild(superArg);
|
||||
builder.PushContext(superArg);
|
||||
upperLimitBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
|
||||
var funcRun = CreateMathRun(font);
|
||||
currentContext.AppendChild(funcRun);
|
||||
builder.PushContext(funcRun);
|
||||
functionBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
var diffRun = CreateMathRun(font);
|
||||
currentContext.AppendChild(diffRun);
|
||||
builder.PushContext(diffRun);
|
||||
differentialBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddSum(
|
||||
OpenXmlElement currentContext,
|
||||
Action<IFormula> expressionBuilder,
|
||||
Action<IFormula>? lowerLimitBuilder,
|
||||
Action<IFormula>? upperLimitBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var font = builder.BaseFont;
|
||||
|
||||
if (lowerLimitBuilder is null && upperLimitBuilder is null)
|
||||
{
|
||||
var sumRun = CreateMathRun(font);
|
||||
sumRun.AppendChild(new MathText("∑"));
|
||||
currentContext.AppendChild(sumRun);
|
||||
|
||||
var exprRun = CreateMathRun(font);
|
||||
currentContext.AppendChild(exprRun);
|
||||
builder.PushContext(exprRun);
|
||||
expressionBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
else
|
||||
{
|
||||
var sumWithLimits = new SubSuperscript();
|
||||
currentContext.AppendChild(sumWithLimits);
|
||||
|
||||
var baseElem = new Base();
|
||||
var sumRun = CreateMathRun(font);
|
||||
sumRun.AppendChild(new MathText("∑"));
|
||||
baseElem.AppendChild(sumRun);
|
||||
sumWithLimits.AppendChild(baseElem);
|
||||
|
||||
if (lowerLimitBuilder is not null)
|
||||
{
|
||||
var subArg = new SubArgument();
|
||||
sumWithLimits.AppendChild(subArg);
|
||||
builder.PushContext(subArg);
|
||||
lowerLimitBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
if (upperLimitBuilder is not null)
|
||||
{
|
||||
var superArg = new SuperArgument();
|
||||
sumWithLimits.AppendChild(superArg);
|
||||
builder.PushContext(superArg);
|
||||
upperLimitBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
|
||||
var exprRun = CreateMathRun(font);
|
||||
currentContext.AppendChild(exprRun);
|
||||
builder.PushContext(exprRun);
|
||||
expressionBuilder(builder);
|
||||
builder.PopContext();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>Создаёт степень.</summary>
|
||||
public static Superscript CreateSuperscript(
|
||||
Action<IFormula> baseBuilder,
|
||||
Action<IFormula> supBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var superscript = new Superscript();
|
||||
|
||||
// Основание
|
||||
var baseElem = new Base();
|
||||
superscript.AppendChild(baseElem);
|
||||
builder.PushContext(baseElem);
|
||||
baseBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
// Показатель
|
||||
var superArg = new SuperArgument();
|
||||
superscript.AppendChild(superArg);
|
||||
builder.PushContext(superArg);
|
||||
supBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
return superscript;
|
||||
}
|
||||
|
||||
/// <summary>Создаёт нижний индекс.</summary>
|
||||
public static Subscript CreateSubscript(
|
||||
Action<IFormula> baseBuilder,
|
||||
Action<IFormula> subBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var subscript = new Subscript();
|
||||
|
||||
var baseElem = new Base();
|
||||
subscript.AppendChild(baseElem);
|
||||
builder.PushContext(baseElem);
|
||||
baseBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
var subArg = new SubArgument();
|
||||
subscript.AppendChild(subArg);
|
||||
builder.PushContext(subArg);
|
||||
subBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
return subscript;
|
||||
}
|
||||
|
||||
/// <summary>Создаёт одновременные нижний и верхний индексы.</summary>
|
||||
public static SubSuperscript CreateSubSuperscript(
|
||||
Action<IFormula> baseBuilder,
|
||||
Action<IFormula> subBuilder,
|
||||
Action<IFormula> supBuilder,
|
||||
IFormula builder)
|
||||
{
|
||||
var subSup = new SubSuperscript();
|
||||
|
||||
var baseElem = new Base();
|
||||
subSup.AppendChild(baseElem);
|
||||
builder.PushContext(baseElem);
|
||||
baseBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
var subArg = new SubArgument();
|
||||
subSup.AppendChild(subArg);
|
||||
builder.PushContext(subArg);
|
||||
subBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
var superArg = new SuperArgument();
|
||||
subSup.AppendChild(superArg);
|
||||
builder.PushContext(superArg);
|
||||
supBuilder(builder);
|
||||
builder.PopContext();
|
||||
|
||||
return subSup;
|
||||
}
|
||||
}
|
||||
315
QWERTYkez.WordProcessor/Builders/Interfaces.cs
Normal file
315
QWERTYkez.WordProcessor/Builders/Interfaces.cs
Normal file
@@ -0,0 +1,315 @@
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
public interface ITable
|
||||
{
|
||||
/// <summary>Базовый шрифт, используемый по умолчанию для содержимого таблицы.</summary>
|
||||
FontProps BaseFont { get; }
|
||||
|
||||
/// <summary>Добавляет строку в таблицу, настраиваемую с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации строки через <see cref="IRow"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ITable"/> для цепочки вызовов.</returns>
|
||||
ITable AddRow(Action<IRow> configure);
|
||||
|
||||
/// <summary>Добавляет строку с указанной высотой, настраиваемую с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="height">Высота строки в сантиметрах.</param>
|
||||
/// <param name="configure">Делегат для конфигурации строки через <see cref="IRow"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ITable"/> для цепочки вызовов.</returns>
|
||||
ITable AddRow(double height, Action<IRow> configure);
|
||||
|
||||
/// <summary>Добавляет строку с ячейками, содержащими заданные тексты, используя указанный шрифт.</summary>
|
||||
/// <param name="font">Шрифт для всех ячеек строки.</param>
|
||||
/// <param name="cellTexts">Массив текстов для ячеек.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ITable"/> для цепочки вызовов.</returns>
|
||||
ITable AddRowWithCells(FontProps font, params string[] cellTexts);
|
||||
|
||||
/// <summary>Добавляет строку с ячейками, содержащими заданные тексты, используя базовый шрифт таблицы.</summary>
|
||||
/// <param name="cellTexts">Массив текстов для ячеек.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ITable"/> для цепочки вызовов.</returns>
|
||||
ITable AddRowWithCells(params string[] cellTexts);
|
||||
|
||||
/// <summary>Задаёт свойства таблицы: ширину и стиль границ, выравнивание.</summary>
|
||||
/// <param name="borderWidth">Ширина границ в пунктах (1/8 pt). По умолчанию 8.</param>
|
||||
/// <param name="borderValues">Стиль границ. По умолчанию <see cref="BorderValues.Single"/>.</param>
|
||||
/// <param name="tableAlignment">Выравнивание таблицы на странице. По умолчанию <see cref="TableRowAlignmentValues.Center"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ITable"/> для цепочки вызовов.</returns>
|
||||
ITable Properties(uint borderWidth = 8, BorderValues? borderValues = null, TableRowAlignmentValues? tableAlignment = null);
|
||||
|
||||
/// <summary>Создаёт объект <see cref="Table"/> на основе выполненных настроек.</summary>
|
||||
/// <returns>Готовый объект <see cref="Table"/> для вставки в документ.</returns>
|
||||
internal Table Build();
|
||||
}
|
||||
|
||||
public interface IRow
|
||||
{
|
||||
/// <summary>Базовый шрифт, используемый по умолчанию для содержимого строки.</summary>
|
||||
FontProps BaseFont { get; }
|
||||
|
||||
/// <summary>Добавляет ячейку, настраиваемую с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации ячейки через <see cref="ICell"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCell(Action<ICell> configure);
|
||||
|
||||
/// <summary>Добавляет ячейку с заданными свойствами (без текста).</summary>
|
||||
/// <param name="cellProps">Свойства ячейки (ширина, объединение, вертикальное выравнивание).</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCell(CellProps cellProps);
|
||||
|
||||
/// <summary>Добавляет ячейку с заданными свойствами и текстом (используется базовый шрифт).</summary>
|
||||
/// <param name="cellProps">Свойства ячейки.</param>
|
||||
/// <param name="text">Текст ячейки.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCell(CellProps cellProps, string text);
|
||||
|
||||
/// <summary>Добавляет ячейку с заданными свойствами, текстом и указанным шрифтом.</summary>
|
||||
/// <param name="cellProps">Свойства ячейки.</param>
|
||||
/// <param name="text">Текст ячейки.</param>
|
||||
/// <param name="font">Шрифт для текста. Если <see langword="null"/>, используется базовый шрифт.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCell(CellProps cellProps, string text, FontProps font);
|
||||
|
||||
/// <summary>Добавляет ячейку с простым текстом (используется базовый шрифт).</summary>
|
||||
/// <param name="text">Текст ячейки.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCell(string text);
|
||||
|
||||
/// <summary>Добавляет ячейку с простым текстом и указанным шрифтом.</summary>
|
||||
/// <param name="text">Текст ячейки.</param>
|
||||
/// <param name="font">Шрифт для текста. Если <see langword="null"/>, используется базовый шрифт.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCell(string text, FontProps font);
|
||||
|
||||
/// <summary>Добавляет ячейку, содержащую один абзац, построенный с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации абзаца через <see cref="IParagraph"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCellWithPara(Action<IParagraph> configure);
|
||||
|
||||
/// <summary>Добавляет ячейку с указанными свойствами, содержащую один абзац, построенный с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="cellProps">Свойства ячейки.</param>
|
||||
/// <param name="configure">Делегат для конфигурации абзаца через <see cref="IParagraph"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow AddCellWithPara(CellProps cellProps, Action<IParagraph> configure);
|
||||
|
||||
/// <summary>Устанавливает точную высоту строки (свойство Exact).</summary>
|
||||
/// <param name="heightInCm">Высота в сантиметрах.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow SetExactHeight(double heightInCm);
|
||||
|
||||
/// <summary>Устанавливает минимальную высоту строки (свойство AtLeast).</summary>
|
||||
/// <param name="heightInCm">Высота в сантиметрах.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow SetHeight(double heightInCm);
|
||||
|
||||
/// <summary>Позволяет напрямую настроить свойства строки <see cref="TableRowProperties"/>.</summary>
|
||||
/// <param name="configure">Делегат для настройки свойств.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IRow"/> для цепочки вызовов.</returns>
|
||||
IRow SetProperties(Action<TableRowProperties> configure);
|
||||
|
||||
/// <summary>Создаёт объект <see cref="TableRow"/> на основе выполненных настроек.</summary>
|
||||
/// <returns>Готовый объект <see cref="TableRow"/> для вставки в таблицу.</returns>
|
||||
internal TableRow Build();
|
||||
}
|
||||
|
||||
public interface ICell
|
||||
{
|
||||
/// <summary>Базовый шрифт, используемый по умолчанию для содержимого ячейки.</summary>
|
||||
FontProps BaseFont { get; }
|
||||
|
||||
/// <summary>Добавляет в ячейку абзац, содержащий математическую формулу.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации формулы через <see cref="IFormula"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ICell"/> для цепочки вызовов.</returns>
|
||||
ICell AddFormula(Action<IFormula> configure);
|
||||
|
||||
/// <summary>Добавляет в ячейку абзац, построенный с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации абзаца через <see cref="IParagraph"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ICell"/> для цепочки вызовов.</returns>
|
||||
ICell AddParagraph(Action<IParagraph> configure);
|
||||
|
||||
/// <summary>Добавляет в ячейку абзац, состоящий из нескольких строк текста (разделённых переносами).</summary>
|
||||
/// <param name="lines">Массив строк, каждая строка будет размещена на новой строке абзаца.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ICell"/> для цепочки вызовов.</returns>
|
||||
ICell AddParagraph(params string[] lines);
|
||||
|
||||
/// <summary>Добавляет в ячейку абзац с указанным текстом и опциональным шрифтом.</summary>
|
||||
/// <param name="text">Текст абзаца.</param>
|
||||
/// <param name="font">Шрифт для текста. Если <see langword="null"/>, используется базовый шрифт.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ICell"/> для цепочки вызовов.</returns>
|
||||
ICell AddParagraph(string text, FontProps? font = null);
|
||||
|
||||
/// <summary>Устанавливает свойства ячейки (ширина, объединение, вертикальное выравнивание).</summary>
|
||||
/// <param name="props">Свойства ячейки.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="ICell"/> для цепочки вызовов.</returns>
|
||||
ICell SetCellProps(CellProps props);
|
||||
|
||||
/// <summary>Создаёт объект <see cref="TableCell"/> на основе выполненных настроек.</summary>
|
||||
/// <returns>Готовый объект <see cref="TableCell"/> для вставки в строку.</returns>
|
||||
internal TableCell Build();
|
||||
}
|
||||
|
||||
public interface IText
|
||||
{
|
||||
/// <summary>Базовый шрифт, используемый по умолчанию для содержимого текстового блока.</summary>
|
||||
FontProps BaseFont { get; }
|
||||
|
||||
/// <summary>Добавляет в документ абзац, содержащий математическую формулу.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации формулы через <see cref="IFormula"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IText"/> для цепочки вызовов.</returns>
|
||||
IText AddFormula(Action<IFormula> configure);
|
||||
|
||||
/// <summary>Добавляет абзац, построенный с помощью <paramref name="configure"/>.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации абзаца через <see cref="IParagraph"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IText"/> для цепочки вызовов.</returns>
|
||||
IText AddParagraph(Action<IParagraph> configure);
|
||||
|
||||
/// <summary>Добавляет абзац, состоящий из нескольких строк текста (разделённых переносами).</summary>
|
||||
/// <param name="lines">Массив строк, каждая строка будет размещена на новой строке абзаца.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IText"/> для цепочки вызовов.</returns>
|
||||
IText AddParagraph(params string[] lines);
|
||||
|
||||
/// <summary>Добавляет абзац с указанным текстом и опциональным шрифтом.</summary>
|
||||
/// <param name="text">Текст абзаца.</param>
|
||||
/// <param name="font">Шрифт для текста. Если <see langword="null"/>, используется базовый шрифт.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IText"/> для цепочки вызовов.</returns>
|
||||
IText AddParagraph(string text, FontProps? font = null);
|
||||
|
||||
/// <summary>Создаёт список абзацев <see cref="Paragraph"/> на основе выполненных настроек.</summary>
|
||||
/// <returns>Список готовых абзацев для вставки в документ.</returns>
|
||||
internal List<Paragraph> Build();
|
||||
}
|
||||
|
||||
public interface IParagraph
|
||||
{
|
||||
/// <summary>Базовый шрифт, используемый по умолчанию для содержимого абзаца.</summary>
|
||||
FontProps BaseFont { get; }
|
||||
|
||||
/// <summary>Добавляет в абзац математическую формулу (внутри отдельного <see cref="Run"/>).</summary>
|
||||
/// <param name="configure">Делегат для конфигурации формулы через <see cref="IFormula"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddFormula(Action<IFormula> configure);
|
||||
|
||||
/// <summary>Добавляет в абзац математическую формулу (внутри отдельного <see cref="Run"/>) и разрыв строки (<see cref="DocumentFormat.OpenXml.Wordprocessing.Break"/>) в текущий абзац.</summary>
|
||||
/// <param name="configure">Делегат для конфигурации формулы через <see cref="IFormula"/>.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddFormulaBreak(Action<IFormula> configure);
|
||||
|
||||
/// <summary>Добавляет разрыв строки (<see cref="DocumentFormat.OpenXml.Wordprocessing.Break"/>) в текущий абзац.</summary>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph Break();
|
||||
|
||||
/// <summary>Добавляет разрыв строки (<see cref="DocumentFormat.OpenXml.Wordprocessing.Break"/>) в текущий абзац.</summary>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph BreakPage();
|
||||
|
||||
/// <summary>Добавляет текстовый фрагмент (<see cref="Run"/>) с указанным текстом и опциональным шрифтом.</summary>
|
||||
/// <param name="text">Текст фрагмента.</param>
|
||||
/// <param name="font">Шрифт для текста. Если <see langword="null"/>, используется базовый шрифт.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddRun(string text, FontProps? font = null);
|
||||
|
||||
/// <summary>Добавляет текстовый фрагмент (<see cref="Run"/>) с указанным текстом и опциональным шрифтом и разрыв строки (<see cref="DocumentFormat.OpenXml.Wordprocessing.Break"/>) в текущий абзац.</summary>
|
||||
/// <param name="text">Текст фрагмента.</param>
|
||||
/// <param name="font">Шрифт для текста. Если <see langword="null"/>, используется базовый шрифт.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddRunBreak(string text, FontProps? font = null);
|
||||
|
||||
/// <summary>Добавляет текстовый фрагмент с полным контролем над свойствами <see cref="RunProperties"/>.</summary>
|
||||
/// <param name="text">Текст фрагмента.</param>
|
||||
/// <param name="configure">Делегат для настройки свойств фрагмента.</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddRunWithCustomProps(string text, Action<RunProperties> configure);
|
||||
|
||||
/// <summary>Добавляет текстовый фрагмент, отформатированный как нижний индекс (<see cref="VerticalPositionValues.Subscript"/>).</summary>
|
||||
/// <param name="text">Текст фрагмента.</param>
|
||||
/// <param name="font">Базовый шрифт (свойства <see cref="SubSup"/> будут переопределены).</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddSubRun(string text, FontProps? font = null);
|
||||
|
||||
/// <summary>Добавляет текстовый фрагмент, отформатированный как верхний индекс (<see cref="VerticalPositionValues.Superscript"/>).</summary>
|
||||
/// <param name="text">Текст фрагмента.</param>
|
||||
/// <param name="font">Базовый шрифт (свойства <see cref="SubSup"/> будут переопределены).</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph AddSupRun(string text, FontProps? font = null);
|
||||
|
||||
/// <summary>Устанавливает выравнивание абзаца.</summary>
|
||||
/// <param name="alignment">Тип выравнивания (лево, право, центр, по ширине).</param>
|
||||
/// <returns>Тот же экземпляр <see cref="IParagraph"/> для цепочки вызовов.</returns>
|
||||
IParagraph SetAlignment(JustificationValues alignment);
|
||||
|
||||
/// <summary>Создаёт объект <see cref="Paragraph"/> на основе выполненных настроек.</summary>
|
||||
/// <returns>Готовый объект <see cref="Paragraph"/>.</returns>
|
||||
internal Paragraph Build();
|
||||
}
|
||||
|
||||
public interface IFormula
|
||||
{
|
||||
FontProps BaseFont { get; }
|
||||
|
||||
IFormula Text(string text);
|
||||
|
||||
|
||||
IFormula Division(string numerator, string denominator);
|
||||
IFormula Division(string numerator, Action<IFormula> denominator);
|
||||
IFormula Division(Action<IFormula> numerator, string denominator);
|
||||
IFormula Division(Action<IFormula> numerator, Action<IFormula> denominator);
|
||||
|
||||
|
||||
IFormula Sup(string baseText, string supText);
|
||||
IFormula Sup(string baseText, Action<IFormula> supText);
|
||||
IFormula Sup(Action<IFormula> baseText, string supText);
|
||||
IFormula Sup(Action<IFormula> baseText, Action<IFormula> supText);
|
||||
|
||||
|
||||
IFormula Sub(string baseText, string subText);
|
||||
IFormula Sub(string baseText, Action<IFormula> subText);
|
||||
IFormula Sub(Action<IFormula> baseText, string subText);
|
||||
IFormula Sub(Action<IFormula> baseText, Action<IFormula> subText);
|
||||
|
||||
|
||||
IFormula SubSup(string baseText, string subText, string supText);
|
||||
IFormula SubSup(string baseText, string subText, Action<IFormula> supText);
|
||||
IFormula SubSup(string baseText, Action<IFormula> subText, string supText);
|
||||
IFormula SubSup(string baseText, Action<IFormula> subText, Action<IFormula> supText);
|
||||
IFormula SubSup(Action<IFormula> baseText, string subText, string supText);
|
||||
IFormula SubSup(Action<IFormula> baseText, string subText, Action<IFormula> supText);
|
||||
IFormula SubSup(Action<IFormula> baseText, Action<IFormula> subText, string supText);
|
||||
IFormula SubSup(Action<IFormula> baseText, Action<IFormula> subText, Action<IFormula> supText);
|
||||
|
||||
|
||||
IFormula Root(string radicand);
|
||||
IFormula Root(Action<IFormula> radicand);
|
||||
IFormula Root(string radicand, string degree);
|
||||
IFormula Root(string radicand, Action<IFormula> degree);
|
||||
IFormula Root(Action<IFormula> radicand, string degree);
|
||||
IFormula Root(Action<IFormula> radicand, Action<IFormula> degree);
|
||||
|
||||
|
||||
IFormula Integral(string function, string differential, string? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(string function, string differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(string function, string differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(string function, string differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(string function, Action<IFormula> differential, string? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(string function, Action<IFormula> differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(string function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(string function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, string differential, string? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, string differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, string differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, string differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, Action<IFormula> differential, string? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, Action<IFormula> differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Integral(Action<IFormula> function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
|
||||
|
||||
IFormula Sum(string expression, string? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Sum(string expression, string? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Sum(string expression, Action<IFormula>? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Sum(string expression, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Sum(Action<IFormula> expression, string? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Sum(Action<IFormula> expression, string? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
IFormula Sum(Action<IFormula> expression, Action<IFormula>? lowerLimit = null, string? upperLimit = null);
|
||||
IFormula Sum(Action<IFormula> expression, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null);
|
||||
|
||||
|
||||
internal void PushContext(OpenXmlElement element);
|
||||
internal void PopContext();
|
||||
}
|
||||
431
QWERTYkez.WordProcessor/Builders/ParagraphBuilderBase.cs
Normal file
431
QWERTYkez.WordProcessor/Builders/ParagraphBuilderBase.cs
Normal file
@@ -0,0 +1,431 @@
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
abstract class ParagraphBuilderBase : IParagraph, IFormula
|
||||
{
|
||||
public FontProps BaseFont { get; internal set; }
|
||||
|
||||
// Конструктор для установки базового шрифта
|
||||
protected ParagraphBuilderBase(FontProps? baseFont = null)
|
||||
{
|
||||
BaseFont = baseFont is not null && baseFont.SubSup.HasValue
|
||||
? baseFont with { SubSup = null }
|
||||
: baseFont ?? new FontProps();
|
||||
}
|
||||
|
||||
|
||||
internal FontProps GetEffectiveFont(FontProps? overrideFont) => overrideFont ?? BaseFont;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
protected Paragraph _paragraph = null!;
|
||||
protected List<Run> _runs = null!;
|
||||
|
||||
internal IParagraph ParagraphBuilder => CreateParagraphBuilder();
|
||||
protected virtual IParagraph CreateParagraphBuilder()
|
||||
{
|
||||
_paragraph = new Paragraph
|
||||
{
|
||||
ParagraphProperties = new ParagraphProperties(
|
||||
new Justification { Val = JustificationValues.Center },
|
||||
new SpacingBetweenLines
|
||||
{
|
||||
After = "0",
|
||||
Before = "0",
|
||||
LineRule = LineSpacingRuleValues.Auto
|
||||
},
|
||||
new Indentation
|
||||
{
|
||||
Left = "0",
|
||||
Right = "0",
|
||||
FirstLine = "0",
|
||||
Hanging = "0"
|
||||
}
|
||||
)
|
||||
};
|
||||
_runs = [];
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
Paragraph IParagraph.Build()
|
||||
{
|
||||
foreach (var run in _runs)
|
||||
{
|
||||
_paragraph.AppendChild(run);
|
||||
}
|
||||
return _paragraph;
|
||||
}
|
||||
|
||||
// Настройка выравнивания
|
||||
public IParagraph SetAlignment(JustificationValues alignment)
|
||||
{
|
||||
var props = _paragraph.ParagraphProperties;
|
||||
props?.Justification = new Justification { Val = alignment };
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление текста
|
||||
public IParagraph AddRun(string text, FontProps? font = null)
|
||||
{
|
||||
// Заменяем обычные пробелы на неразрывные для сохранения видимости
|
||||
string processedText = text.Replace(' ', '\u00A0');
|
||||
|
||||
var effectiveFont = GetEffectiveFont(font);
|
||||
Run run;
|
||||
|
||||
if (effectiveFont.TryExtract(out var elements))
|
||||
{
|
||||
run = new Run(new RunProperties(elements), new Text(processedText));
|
||||
}
|
||||
else
|
||||
{
|
||||
run = new Run(new Text(processedText));
|
||||
}
|
||||
|
||||
_runs.Add(run);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление текста
|
||||
public IParagraph AddRunBreak(string text, FontProps? font = null)
|
||||
{
|
||||
// Заменяем обычные пробелы на неразрывные для сохранения видимости
|
||||
string processedText = text.Replace(' ', '\u00A0');
|
||||
|
||||
var effectiveFont = GetEffectiveFont(font);
|
||||
Run run;
|
||||
|
||||
if (effectiveFont.TryExtract(out var elements))
|
||||
{
|
||||
run = new Run(new RunProperties(elements), new Text(processedText));
|
||||
}
|
||||
else
|
||||
{
|
||||
run = new Run(new Text(processedText));
|
||||
}
|
||||
|
||||
_runs.Add(run);
|
||||
|
||||
_runs.Add(new Run(new Break()));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление текста
|
||||
public IParagraph AddSupRun(string text, FontProps? font = null)
|
||||
{
|
||||
var effectiveFont = GetEffectiveFont(font);
|
||||
Run run;
|
||||
|
||||
if (effectiveFont.TrySupExtract(out var elements))
|
||||
{
|
||||
run = new Run(new RunProperties(elements), new Text(text));
|
||||
}
|
||||
else
|
||||
{
|
||||
run = new Run(new Text(text));
|
||||
}
|
||||
|
||||
_runs.Add(run);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление текста
|
||||
public IParagraph AddSubRun(string text, FontProps? font = null)
|
||||
{
|
||||
var effectiveFont = GetEffectiveFont(font);
|
||||
Run run;
|
||||
|
||||
if (effectiveFont.TrySubExtract(out var elements))
|
||||
{
|
||||
run = new Run(new RunProperties(elements), new Text(text));
|
||||
}
|
||||
else
|
||||
{
|
||||
run = new Run(new Text(text));
|
||||
}
|
||||
|
||||
_runs.Add(run);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IParagraph AddRunWithCustomProps(string text, Action<RunProperties> configure)
|
||||
{
|
||||
var props = new RunProperties();
|
||||
configure(props);
|
||||
_runs.Add(new Run(props, new Text(text)));
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление разрыва строки
|
||||
public IParagraph Break()
|
||||
{
|
||||
_runs.Add(new Run(new Break()));
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление разрыва строки
|
||||
public IParagraph BreakPage()
|
||||
{
|
||||
_runs.Add(new Run(new Break() { Type = BreakValues.Page }));
|
||||
return this;
|
||||
}
|
||||
|
||||
// Метод AddFormula для IParagraphBuilder
|
||||
IParagraph IParagraph.AddFormula(Action<IFormula> configure)
|
||||
{
|
||||
var math = new OfficeMath();
|
||||
try
|
||||
{
|
||||
_mathContextStack.Push(math);
|
||||
configure(this);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_mathContextStack.Pop();
|
||||
}
|
||||
|
||||
var run = new Run(); // без RunProperties
|
||||
run.AppendChild(math);
|
||||
_runs.Add(run);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Метод AddFormula для IParagraphBuilder
|
||||
IParagraph IParagraph.AddFormulaBreak(Action<IFormula> configure)
|
||||
{
|
||||
var math = new OfficeMath();
|
||||
try
|
||||
{
|
||||
_mathContextStack.Push(math);
|
||||
configure(this);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_mathContextStack.Pop();
|
||||
}
|
||||
|
||||
var run = new Run(); // без RunProperties
|
||||
run.AppendChild(math);
|
||||
_runs.Add(run);
|
||||
_runs.Add(new Run(new Break()));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Стек для вложенных математических конструкций
|
||||
private readonly Stack<OpenXmlElement> _mathContextStack = new();
|
||||
bool TryGetCurrentMathContext(out OpenXmlElement element)
|
||||
{
|
||||
if (_mathContextStack.Count > 0)
|
||||
{
|
||||
element = _mathContextStack.Peek();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
element = null!;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Вспомогательные методы для стека (используются FormulaHelper)
|
||||
void IFormula.PushContext(OpenXmlElement element) => _mathContextStack.Push(element);
|
||||
void IFormula.PopContext() => _mathContextStack.Pop();
|
||||
|
||||
|
||||
// Реализация IFormulaBuilder
|
||||
public IFormula Text(string text)
|
||||
{
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
FormulaHelper.AddText(element, text, BaseFont);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// Division
|
||||
public IFormula Division(string numerator, string denominator) =>
|
||||
Division(ToAction(numerator), ToAction(denominator));
|
||||
public IFormula Division(string numerator, Action<IFormula> denominator) =>
|
||||
Division(ToAction(numerator), denominator);
|
||||
public IFormula Division(Action<IFormula> numerator, string denominator) =>
|
||||
Division(numerator, ToAction(denominator));
|
||||
public IFormula Division(Action<IFormula> numerator, Action<IFormula> denominator)
|
||||
{
|
||||
var fraction = FormulaHelper.CreateFraction(numerator, denominator, this);
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
element.AppendChild(fraction);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// Sup
|
||||
public IFormula Sup(string baseText, string supText) =>
|
||||
Sup(ToAction(baseText), ToAction(supText));
|
||||
public IFormula Sup(string baseText, Action<IFormula> supText) =>
|
||||
Sup(ToAction(baseText), supText);
|
||||
public IFormula Sup(Action<IFormula> baseText, string supText) =>
|
||||
Sup(baseText, ToAction(supText));
|
||||
public IFormula Sup(Action<IFormula> baseText, Action<IFormula> supText)
|
||||
{
|
||||
var superscript = FormulaHelper.CreateSuperscript(baseText, supText, this);
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
element.AppendChild(superscript);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// Sub
|
||||
public IFormula Sub(string baseText, string subText) =>
|
||||
Sub(ToAction(baseText), ToAction(subText));
|
||||
public IFormula Sub(string baseText, Action<IFormula> subText) =>
|
||||
Sub(ToAction(baseText), subText);
|
||||
public IFormula Sub(Action<IFormula> baseText, string subText) =>
|
||||
Sub(baseText, ToAction(subText));
|
||||
public IFormula Sub(Action<IFormula> baseText, Action<IFormula> subText)
|
||||
{
|
||||
var subscript = FormulaHelper.CreateSubscript(baseText, subText, this);
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
element.AppendChild(subscript);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// SubSup
|
||||
public IFormula SubSup(string baseText, string subText, string supText) =>
|
||||
SubSup(ToAction(baseText), ToAction(subText), ToAction(supText));
|
||||
public IFormula SubSup(string baseText, string subText, Action<IFormula> supText) =>
|
||||
SubSup(ToAction(baseText), ToAction(subText), supText);
|
||||
public IFormula SubSup(string baseText, Action<IFormula> subText, string supText) =>
|
||||
SubSup(ToAction(baseText), subText, ToAction(supText));
|
||||
public IFormula SubSup(string baseText, Action<IFormula> subText, Action<IFormula> supText) =>
|
||||
SubSup(ToAction(baseText), subText, supText);
|
||||
public IFormula SubSup(Action<IFormula> baseText, string subText, string supText) =>
|
||||
SubSup(baseText, ToAction(subText), ToAction(supText));
|
||||
public IFormula SubSup(Action<IFormula> baseText, string subText, Action<IFormula> supText) =>
|
||||
SubSup(baseText, ToAction(subText), supText);
|
||||
public IFormula SubSup(Action<IFormula> baseText, Action<IFormula> subText, string supText) =>
|
||||
SubSup(baseText, subText, ToAction(supText));
|
||||
public IFormula SubSup(Action<IFormula> baseText, Action<IFormula> subText, Action<IFormula> supText)
|
||||
{
|
||||
var subSup = FormulaHelper.CreateSubSuperscript(baseText, subText, supText, this);
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
element.AppendChild(subSup);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// Root
|
||||
public IFormula Root(string radicand) => Root(ToAction(radicand));
|
||||
public IFormula Root(Action<IFormula> radicand)
|
||||
{
|
||||
var radical = FormulaHelper.CreateRadical(radicand, null, this);
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
element.AppendChild(radical);
|
||||
return this;
|
||||
}
|
||||
public IFormula Root(string radicand, string degree) =>
|
||||
Root(ToAction(radicand), ToAction(degree));
|
||||
public IFormula Root(string radicand, Action<IFormula> degree) =>
|
||||
Root(ToAction(radicand), degree);
|
||||
public IFormula Root(Action<IFormula> radicand, string degree) =>
|
||||
Root(radicand, ToAction(degree));
|
||||
public IFormula Root(Action<IFormula> radicand, Action<IFormula> degree)
|
||||
{
|
||||
var radical = FormulaHelper.CreateRadical(radicand, degree, this);
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
element.AppendChild(radical);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
private void AddIntegralCore(
|
||||
Action<IFormula> function,
|
||||
Action<IFormula> differential,
|
||||
Action<IFormula>? lowerLimit,
|
||||
Action<IFormula>? upperLimit)
|
||||
{
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
FormulaHelper.AddIntegral(element, function, differential, lowerLimit, upperLimit, this);
|
||||
}
|
||||
|
||||
public IFormula Integral(string function, string differential, string? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(ToAction(function), ToAction(differential), ToNullableAction(lowerLimit), ToNullableAction(upperLimit));
|
||||
public IFormula Integral(string function, string differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(ToAction(function), ToAction(differential), ToNullableAction(lowerLimit), upperLimit);
|
||||
public IFormula Integral(string function, string differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(ToAction(function), ToAction(differential), lowerLimit, ToNullableAction(upperLimit));
|
||||
public IFormula Integral(string function, string differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(ToAction(function), ToAction(differential), lowerLimit, upperLimit);
|
||||
public IFormula Integral(string function, Action<IFormula> differential, string? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(ToAction(function), differential, ToNullableAction(lowerLimit), ToNullableAction(upperLimit));
|
||||
public IFormula Integral(string function, Action<IFormula> differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(ToAction(function), differential, ToNullableAction(lowerLimit), upperLimit);
|
||||
public IFormula Integral(string function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(ToAction(function), differential, lowerLimit, ToNullableAction(upperLimit));
|
||||
public IFormula Integral(string function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(ToAction(function), differential, lowerLimit, upperLimit);
|
||||
public IFormula Integral(Action<IFormula> function, string differential, string? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(function, ToAction(differential), ToNullableAction(lowerLimit), ToNullableAction(upperLimit));
|
||||
public IFormula Integral(Action<IFormula> function, string differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(function, ToAction(differential), ToNullableAction(lowerLimit), upperLimit);
|
||||
public IFormula Integral(Action<IFormula> function, string differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(function, ToAction(differential), lowerLimit, ToNullableAction(upperLimit));
|
||||
public IFormula Integral(Action<IFormula> function, string differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(function, ToAction(differential), lowerLimit, upperLimit);
|
||||
public IFormula Integral(Action<IFormula> function, Action<IFormula> differential, string? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(function, differential, ToNullableAction(lowerLimit), ToNullableAction(upperLimit));
|
||||
public IFormula Integral(Action<IFormula> function, Action<IFormula> differential, string? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Integral(function, differential, ToNullableAction(lowerLimit), upperLimit);
|
||||
public IFormula Integral(Action<IFormula> function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, string? upperLimit = null) =>
|
||||
Integral(function, differential, lowerLimit, ToNullableAction(upperLimit));
|
||||
public IFormula Integral(Action<IFormula> function, Action<IFormula> differential, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null)
|
||||
{
|
||||
AddIntegralCore(function, differential, lowerLimit, upperLimit);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
// Sum
|
||||
private void AddSumCore(
|
||||
Action<IFormula> expression,
|
||||
Action<IFormula>? lowerLimit,
|
||||
Action<IFormula>? upperLimit)
|
||||
{
|
||||
if (TryGetCurrentMathContext(out var element))
|
||||
FormulaHelper.AddSum(element, expression, lowerLimit, upperLimit, this);
|
||||
}
|
||||
|
||||
public IFormula Sum(string expression, string? lowerLimit = null, string? upperLimit = null) =>
|
||||
Sum(ToAction(expression), ToNullableAction(lowerLimit), ToNullableAction(upperLimit));
|
||||
public IFormula Sum(string expression, string? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Sum(ToAction(expression), ToNullableAction(lowerLimit), upperLimit);
|
||||
public IFormula Sum(string expression, Action<IFormula>? lowerLimit = null, string? upperLimit = null) =>
|
||||
Sum(ToAction(expression), lowerLimit, ToNullableAction(upperLimit));
|
||||
public IFormula Sum(string expression, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Sum(ToAction(expression), lowerLimit, upperLimit);
|
||||
public IFormula Sum(Action<IFormula> expression, string? lowerLimit = null, string? upperLimit = null) =>
|
||||
Sum(expression, ToNullableAction(lowerLimit), ToNullableAction(upperLimit));
|
||||
public IFormula Sum(Action<IFormula> expression, string? lowerLimit = null, Action<IFormula>? upperLimit = null) =>
|
||||
Sum(expression, ToNullableAction(lowerLimit), upperLimit);
|
||||
public IFormula Sum(Action<IFormula> expression, Action<IFormula>? lowerLimit = null, string? upperLimit = null) =>
|
||||
Sum(expression, lowerLimit, ToNullableAction(upperLimit));
|
||||
public IFormula Sum(Action<IFormula> expression, Action<IFormula>? lowerLimit = null, Action<IFormula>? upperLimit = null)
|
||||
{
|
||||
AddSumCore(expression, lowerLimit, upperLimit);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// Вспомогательный метод для преобразования строки в делегат
|
||||
private static Action<IFormula>? ToNullableAction(string? text) => text is null ? null : (b => b.Text(text));
|
||||
private static Action<IFormula> ToAction(string text) => b => b.Text(text);
|
||||
}
|
||||
328
QWERTYkez.WordProcessor/Builders/TableBuilder.cs
Normal file
328
QWERTYkez.WordProcessor/Builders/TableBuilder.cs
Normal file
@@ -0,0 +1,328 @@
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
internal sealed class TableBuilder : ParagraphBuilderBase, ITable, IRow, ICell
|
||||
{
|
||||
private readonly Table _table = new();
|
||||
|
||||
internal TableBuilder(FontProps? baseFont) : base(baseFont)
|
||||
{
|
||||
}
|
||||
|
||||
internal static TableBuilder Create(FontProps? baseFont = null) => new(baseFont);
|
||||
|
||||
|
||||
// Метод завершения сборки
|
||||
public Table Build() => _table;
|
||||
|
||||
// Публичные методы настройки таблицы
|
||||
public ITable Properties(
|
||||
uint borderWidth = 8,
|
||||
BorderValues? borderValues = null,
|
||||
TableRowAlignmentValues? tableAlignment = null)
|
||||
{
|
||||
var borderType = borderValues ?? BorderValues.Single;
|
||||
var alignment = tableAlignment ?? TableRowAlignmentValues.Center;
|
||||
|
||||
_table.AppendChild(new TableProperties(
|
||||
new TableBorders(
|
||||
new TopBorder() { Val = borderType, Size = borderWidth },
|
||||
new BottomBorder() { Val = borderType, Size = borderWidth },
|
||||
new LeftBorder() { Val = borderType, Size = borderWidth },
|
||||
new RightBorder() { Val = borderType, Size = borderWidth },
|
||||
new InsideHorizontalBorder() { Val = borderType, Size = borderWidth },
|
||||
new InsideVerticalBorder() { Val = borderType, Size = borderWidth }
|
||||
),
|
||||
new TableJustification { Val = alignment },
|
||||
new TableLayout() { Type = TableLayoutValues.Autofit }
|
||||
));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление строк с использованием IRowBuilder
|
||||
public ITable AddRow(Action<IRow> configure)
|
||||
{
|
||||
var IRowBuilder = RowBuilder;
|
||||
configure(this);
|
||||
_table.AppendChild(IRowBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public ITable AddRow(double height, Action<IRow> configure)
|
||||
{
|
||||
var IRowBuilder = RowBuilder.SetHeight(height);
|
||||
configure(this);
|
||||
_table.AppendChild(IRowBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
// Быстрые методы для добавления строк с ячейками
|
||||
public ITable AddRowWithCells(params string[] cellTexts)
|
||||
{
|
||||
AddRow(row =>
|
||||
{
|
||||
foreach (var text in cellTexts)
|
||||
{
|
||||
row.AddCell(text);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
public ITable AddRowWithCells(FontProps font, params string[] cellTexts)
|
||||
{
|
||||
AddRow(row =>
|
||||
{
|
||||
foreach (var text in cellTexts)
|
||||
{
|
||||
row.AddCell(text, font);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private TableRow _row = null!;
|
||||
internal IRow RowBuilder
|
||||
{
|
||||
get
|
||||
{
|
||||
_row = new();
|
||||
return this;
|
||||
}
|
||||
}
|
||||
TableRow IRow.Build() => _row;
|
||||
|
||||
|
||||
// Настройка высоты строки (исправленный метод)
|
||||
public IRow SetHeight(double heightInCm)
|
||||
{
|
||||
var height = new TableRowHeight
|
||||
{
|
||||
Val = (UInt32Value)(uint)(heightInCm * 567), // 1 см = 567 DXA
|
||||
HeightType = HeightRuleValues.AtLeast
|
||||
};
|
||||
|
||||
// Убедимся, что TableRowProperties существует
|
||||
if (_row.TableRowProperties is null)
|
||||
{
|
||||
_row.TableRowProperties = new TableRowProperties();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Удалим существующий TableRowHeight, если он есть
|
||||
var existingHeight = _row.TableRowProperties.Elements<TableRowHeight>().FirstOrDefault();
|
||||
existingHeight?.Remove();
|
||||
}
|
||||
|
||||
// Добавляем TableRowHeight как дочерний элемент
|
||||
_row.TableRowProperties.AppendChild(height);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRow SetExactHeight(double heightInCm)
|
||||
{
|
||||
var height = new TableRowHeight
|
||||
{
|
||||
Val = (UInt32Value)(uint)(heightInCm * 567),
|
||||
HeightType = HeightRuleValues.Exact
|
||||
};
|
||||
|
||||
// Убедимся, что TableRowProperties существует
|
||||
if (_row.TableRowProperties is null)
|
||||
{
|
||||
_row.TableRowProperties = new TableRowProperties();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Удалим существующий TableRowHeight, если он есть
|
||||
var existingHeight = _row.TableRowProperties.Elements<TableRowHeight>().FirstOrDefault();
|
||||
existingHeight?.Remove();
|
||||
}
|
||||
|
||||
// Добавляем TableRowHeight как дочерний элемент
|
||||
_row.TableRowProperties.AppendChild(height);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление ячеек
|
||||
public IRow AddCell(Action<ICell> configure)
|
||||
{
|
||||
var cellBuilder = CellBuilder;
|
||||
configure(this);
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRow AddCell(string text)
|
||||
{
|
||||
var cellBuilder = CellBuilder;
|
||||
cellBuilder.AddParagraph(p => p.AddRun(text));
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRow AddCell(string text, FontProps font)
|
||||
{
|
||||
var cellBuilder = CellBuilder;
|
||||
|
||||
if (font is not null)
|
||||
cellBuilder.AddParagraph(p => p.AddRun(text, font));
|
||||
else cellBuilder.AddParagraph(p => p.AddRun(text));
|
||||
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRow AddCell(CellProps cellProps, string text, FontProps font)
|
||||
{
|
||||
var cellBuilder = CellBuilder.SetCellProps(cellProps);
|
||||
|
||||
if (font is not null)
|
||||
cellBuilder.AddParagraph(p => p.AddRun(text, font));
|
||||
else cellBuilder.AddParagraph(p => p.AddRun(text));
|
||||
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRow AddCell(CellProps cellProps, string text)
|
||||
{
|
||||
var cellBuilder = CellBuilder.SetCellProps(cellProps);
|
||||
cellBuilder.AddParagraph(p => p.AddRun(text));
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRow AddCell(CellProps cellProps)
|
||||
{
|
||||
var cellBuilder = CellBuilder.SetCellProps(cellProps);
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
// Метод для установки произвольных свойств строки
|
||||
public IRow SetProperties(Action<TableRowProperties> configure)
|
||||
{
|
||||
_row.TableRowProperties ??= new TableRowProperties();
|
||||
configure(_row.TableRowProperties);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public IRow AddCellWithPara(Action<IParagraph> configure)
|
||||
{
|
||||
var cellBuilder = CellBuilder;
|
||||
cellBuilder.AddParagraph(configure);
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
public IRow AddCellWithPara(CellProps cellProps, Action<IParagraph> configure)
|
||||
{
|
||||
var cellBuilder = CellBuilder.SetCellProps(cellProps);
|
||||
cellBuilder.AddParagraph(configure);
|
||||
_row.AppendChild(cellBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private TableCell _cell = null!;
|
||||
private List<Paragraph> _paragraphs = null!;
|
||||
internal ICell CellBuilder
|
||||
{
|
||||
get
|
||||
{
|
||||
_cell = new();
|
||||
_paragraphs = [];
|
||||
return this;
|
||||
}
|
||||
}
|
||||
TableCell ICell.Build()
|
||||
{
|
||||
foreach (var paragraph in _paragraphs)
|
||||
{
|
||||
_cell.AppendChild(paragraph);
|
||||
}
|
||||
return _cell;
|
||||
}
|
||||
|
||||
// Установка свойств ячейки
|
||||
public ICell SetCellProps(CellProps props)
|
||||
{
|
||||
if (props.TryExtract(out var elements))
|
||||
{
|
||||
_cell.TableCellProperties = new TableCellProperties(elements);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление параграфов
|
||||
public ICell AddParagraph(Action<IParagraph> configure)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
configure(paraBuilder);
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public ICell AddParagraph(string text, FontProps? font = null)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
|
||||
if (font is not null)
|
||||
{
|
||||
paraBuilder.AddRun(text, font);
|
||||
}
|
||||
else
|
||||
{
|
||||
paraBuilder.AddRun(text);
|
||||
}
|
||||
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public ICell AddParagraph(params string[] lines)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
if (lines.Length > 0)
|
||||
{
|
||||
paraBuilder.AddRun(lines[0]);
|
||||
for (int i = 1; i < lines.Length; i++)
|
||||
{
|
||||
paraBuilder.Break();
|
||||
paraBuilder.AddRun(lines[i]);
|
||||
}
|
||||
}
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
// Метод AddFormula для ICellBuilder
|
||||
ICell ICell.AddFormula(Action<IFormula> configure)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
paraBuilder.AddFormula(configure);
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
}
|
||||
110
QWERTYkez.WordProcessor/Builders/TextBuilder.cs
Normal file
110
QWERTYkez.WordProcessor/Builders/TextBuilder.cs
Normal file
@@ -0,0 +1,110 @@
|
||||
namespace QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
internal sealed class TextBuilder : ParagraphBuilderBase, IText
|
||||
{
|
||||
private readonly ParagraphProperties? _baseParagraphProperties;
|
||||
|
||||
internal TextBuilder(FontProps? baseFont, ParagraphProperties? baseParagraphProperties = null) : base(baseFont)
|
||||
{
|
||||
_baseParagraphProperties = baseParagraphProperties?.CloneNode(true) as ParagraphProperties;
|
||||
}
|
||||
|
||||
internal static TextBuilder Create(FontProps? baseFont = null, ParagraphProperties? baseParagraphProperties = null) =>
|
||||
new(baseFont, baseParagraphProperties);
|
||||
|
||||
|
||||
|
||||
|
||||
// Переопределяем создание параграфа
|
||||
protected override IParagraph CreateParagraphBuilder()
|
||||
{
|
||||
_paragraph = new Paragraph();
|
||||
|
||||
if (_baseParagraphProperties is not null)
|
||||
{
|
||||
_paragraph.ParagraphProperties = _baseParagraphProperties.CloneNode(true) as ParagraphProperties;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Используем стандартные свойства (как в базовом классе)
|
||||
_paragraph.ParagraphProperties = new ParagraphProperties(
|
||||
new Justification { Val = JustificationValues.Center },
|
||||
new SpacingBetweenLines
|
||||
{
|
||||
After = "0",
|
||||
Before = "0",
|
||||
LineRule = LineSpacingRuleValues.Auto
|
||||
},
|
||||
new Indentation
|
||||
{
|
||||
Left = "0",
|
||||
Right = "0",
|
||||
FirstLine = "0",
|
||||
Hanging = "0"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
_runs = [];
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private readonly List<Paragraph> _paragraphs = [];
|
||||
public List<Paragraph> Build() => _paragraphs;
|
||||
|
||||
IText IText.AddFormula(Action<IFormula> configure)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
paraBuilder.AddFormula(configure);
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
// Добавление параграфов
|
||||
public IText AddParagraph(Action<IParagraph> configure)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
configure(paraBuilder);
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IText AddParagraph(string text, FontProps? font = null)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
|
||||
if (font is not null)
|
||||
{
|
||||
paraBuilder.AddRun(text, font);
|
||||
}
|
||||
else
|
||||
{
|
||||
paraBuilder.AddRun(text);
|
||||
}
|
||||
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
|
||||
public IText AddParagraph(params string[] lines)
|
||||
{
|
||||
var paraBuilder = ParagraphBuilder;
|
||||
if (lines.Length > 0)
|
||||
{
|
||||
paraBuilder.AddRun(lines[0]);
|
||||
for (int i = 1; i < lines.Length; i++)
|
||||
{
|
||||
paraBuilder.Break();
|
||||
paraBuilder.AddRun(lines[i]);
|
||||
}
|
||||
}
|
||||
_paragraphs.Add(paraBuilder.Build());
|
||||
return this;
|
||||
}
|
||||
}
|
||||
371
QWERTYkez.WordProcessor/HeaderFooterProcessor.cs
Normal file
371
QWERTYkez.WordProcessor/HeaderFooterProcessor.cs
Normal file
@@ -0,0 +1,371 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Обработчик текста в верхних и нижних колонтитулах DOCX документов
|
||||
/// </summary>
|
||||
internal static class HeaderFooterProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// Заменяет текст во всех колонтитулах документа
|
||||
/// </summary>
|
||||
internal static void ReplaceInHeadersFooters(WordprocessingDocument document, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
|
||||
{
|
||||
if (document is null || string.IsNullOrEmpty(oldValue) || newValues is null)
|
||||
return;
|
||||
|
||||
var headers = GetAllHeaders(document).ToList();
|
||||
var footers = GetAllFooters(document).ToList();
|
||||
|
||||
if (headers.Count == 0 && footers.Count == 0)
|
||||
return;
|
||||
|
||||
#if DEBUG
|
||||
int headerMatches = 0;
|
||||
int footerMatches = 0;
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
if (ContainsText(header, oldValue, comparisonType))
|
||||
{
|
||||
headerMatches++;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var footer in footers)
|
||||
{
|
||||
if (ContainsText(footer, oldValue, comparisonType))
|
||||
{
|
||||
footerMatches++;
|
||||
}
|
||||
}
|
||||
|
||||
if (headerMatches > 0 || footerMatches > 0)
|
||||
{
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters] Looking for '{oldValue}'");
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters] Headers: {headers.Count} total, {headerMatches} with matches");
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters] Footers: {footers.Count} total, {footerMatches} with matches");
|
||||
}
|
||||
#endif
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
ReplaceInElement(header, oldValue, newValues, comparisonType);
|
||||
}
|
||||
|
||||
foreach (var footer in footers)
|
||||
{
|
||||
ReplaceInElement(footer, oldValue, newValues, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет словарную замену во всех колонтитулах
|
||||
/// </summary>
|
||||
internal static void ReplaceInHeadersFooters(WordprocessingDocument document, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (document is null || replacements is null || !replacements.Any())
|
||||
return;
|
||||
|
||||
var headers = GetAllHeaders(document).ToList();
|
||||
var footers = GetAllFooters(document).ToList();
|
||||
|
||||
if (headers.Count == 0 && footers.Count == 0)
|
||||
return;
|
||||
|
||||
#if DEBUG
|
||||
int headerMatches = 0;
|
||||
int footerMatches = 0;
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && ContainsText(header, kvp.Key, comparisonType))
|
||||
{
|
||||
headerMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var footer in footers)
|
||||
{
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && ContainsText(footer, kvp.Key, comparisonType))
|
||||
{
|
||||
footerMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerMatches > 0 || footerMatches > 0)
|
||||
{
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters(dict)] START with {replacements.Count()} items");
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters(dict)] Headers: {headers.Count} total, {headerMatches} with matches");
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters(dict)] Footers: {footers.Count} total, {footerMatches} with matches");
|
||||
}
|
||||
#endif
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
ReplaceInElement(header, replacements, comparisonType);
|
||||
}
|
||||
|
||||
foreach (var footer in footers)
|
||||
{
|
||||
ReplaceInElement(footer, replacements, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет словарную замену во всех колонтитулах
|
||||
/// </summary>
|
||||
internal static void ReplaceInHeadersFooters(WordprocessingDocument document, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (document is null || replacements is null || !replacements.Any())
|
||||
return;
|
||||
|
||||
var headers = GetAllHeaders(document).ToList();
|
||||
var footers = GetAllFooters(document).ToList();
|
||||
|
||||
if (headers.Count == 0 && footers.Count == 0)
|
||||
return;
|
||||
|
||||
#if DEBUG
|
||||
int headerMatches = 0;
|
||||
int footerMatches = 0;
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && ContainsText(header, kvp.Key, comparisonType))
|
||||
{
|
||||
headerMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var footer in footers)
|
||||
{
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && ContainsText(footer, kvp.Key, comparisonType))
|
||||
{
|
||||
footerMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerMatches > 0 || footerMatches > 0)
|
||||
{
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters(dict)] START with {replacements.Count()} items");
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters(dict)] Headers: {headers.Count} total, {headerMatches} with matches");
|
||||
Debug.WriteLine($"[DEBUG] [HeaderFooterProcessor.ReplaceInHeadersFooters(dict)] Footers: {footers.Count} total, {footerMatches} with matches");
|
||||
}
|
||||
#endif
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
ReplaceInElement(header, replacements, comparisonType);
|
||||
}
|
||||
|
||||
foreach (var footer in footers)
|
||||
{
|
||||
ReplaceInElement(footer, replacements, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет текст в указанном элементе (Header или Footer)
|
||||
/// </summary>
|
||||
private static void ReplaceInElement(OpenXmlElement element, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null)
|
||||
return;
|
||||
|
||||
var paragraphs = element.Descendants<Paragraph>().ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
var tables = TableTextProcessor.GetAllTables(element).ToList();
|
||||
var tableParagraphs = tables.SelectMany(t => TableTextProcessor.GetTableParagraphs(t)).ToList();
|
||||
|
||||
var allParagraphs = paragraphs.Concat(tableParagraphs).Distinct().ToList();
|
||||
|
||||
if (newValues.Count() == 1)
|
||||
{
|
||||
foreach (var paragraph in allParagraphs)
|
||||
{
|
||||
paragraph?.SimpleReplace(oldValue, newValues.First(), comparisonType);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var paragraph in allParagraphs)
|
||||
{
|
||||
if (paragraph is not null && paragraph.InnerText.IndexOf(oldValue, comparisonType) >= 0)
|
||||
{
|
||||
paragraph.ReplaceWithMultiple(oldValue, newValues, comparisonType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет словарную замену в указанном элементе
|
||||
/// </summary>
|
||||
private static void ReplaceInElement(OpenXmlElement element, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null || replacements is null || !replacements.Any())
|
||||
return;
|
||||
|
||||
var paragraphs = element.Descendants<Paragraph>().ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
var tables = TableTextProcessor.GetAllTables(element).ToList();
|
||||
var tableParagraphs = tables.SelectMany(t => TableTextProcessor.GetTableParagraphs(t)).ToList();
|
||||
|
||||
var allParagraphs = paragraphs.Concat(tableParagraphs).Distinct().ToList();
|
||||
|
||||
foreach (var paragraph in allParagraphs)
|
||||
{
|
||||
if (paragraph is null)
|
||||
continue;
|
||||
|
||||
var paraText = paragraph.InnerText;
|
||||
bool hasMatch = false;
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && paraText.IndexOf(kvp.Key, comparisonType) >= 0)
|
||||
{
|
||||
hasMatch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasMatch)
|
||||
continue;
|
||||
|
||||
var newParagraphs = MultiReplaceExt.ProcessParagraphWithAllReplacements(paragraph, replacements, comparisonType);
|
||||
if (newParagraphs is not null && newParagraphs.Count > 0)
|
||||
{
|
||||
ReplaceParagraphInParent(paragraph, newParagraphs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет словарную замену в указанном элементе
|
||||
/// </summary>
|
||||
private static void ReplaceInElement(OpenXmlElement element, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null || replacements is null || !replacements.Any())
|
||||
return;
|
||||
|
||||
var paragraphs = element.Descendants<Paragraph>().ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
var tables = TableTextProcessor.GetAllTables(element).ToList();
|
||||
var tableParagraphs = tables.SelectMany(t => TableTextProcessor.GetTableParagraphs(t)).ToList();
|
||||
|
||||
var allParagraphs = paragraphs.Concat(tableParagraphs).Distinct().ToList();
|
||||
|
||||
foreach (var paragraph in allParagraphs)
|
||||
{
|
||||
if (paragraph is null)
|
||||
continue;
|
||||
|
||||
var paraText = paragraph.InnerText;
|
||||
bool hasMatch = false;
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && paraText.IndexOf(kvp.Key, comparisonType) >= 0)
|
||||
{
|
||||
hasMatch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasMatch)
|
||||
continue;
|
||||
|
||||
var newParagraphs = MultiReplaceExt.ProcessParagraphWithAllReplacements(paragraph, replacements, comparisonType);
|
||||
if (newParagraphs is not null && newParagraphs.Count > 0)
|
||||
{
|
||||
ReplaceParagraphInParent(paragraph, newParagraphs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
private static bool ContainsText(OpenXmlElement element, string searchText, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null || string.IsNullOrEmpty(searchText))
|
||||
return false;
|
||||
|
||||
return element.InnerText?.IndexOf(searchText, comparisonType) >= 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Остальные методы остаются без изменений
|
||||
|
||||
/// <summary>
|
||||
/// Находит и возвращает все верхние колонтитулы в документе
|
||||
/// </summary>
|
||||
internal static IEnumerable<OpenXmlElement> GetAllHeaders(WordprocessingDocument document)
|
||||
{
|
||||
if (document?.MainDocumentPart is null)
|
||||
yield break;
|
||||
|
||||
foreach (var headerPart in document.MainDocumentPart.HeaderParts)
|
||||
{
|
||||
if (headerPart?.Header is not null)
|
||||
{
|
||||
yield return headerPart.Header;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Находит и возвращает все нижние колонтитулы в документе
|
||||
/// </summary>
|
||||
internal static IEnumerable<OpenXmlElement> GetAllFooters(WordprocessingDocument document)
|
||||
{
|
||||
if (document?.MainDocumentPart is null)
|
||||
yield break;
|
||||
|
||||
foreach (var footerPart in document.MainDocumentPart.FooterParts)
|
||||
{
|
||||
if (footerPart?.Footer is not null)
|
||||
{
|
||||
yield return footerPart.Footer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет, содержит ли документ колонтитулы
|
||||
/// </summary>
|
||||
internal static bool HasHeadersOrFooters(WordprocessingDocument document)
|
||||
{
|
||||
if (document?.MainDocumentPart is null)
|
||||
return false;
|
||||
|
||||
return document.MainDocumentPart.HeaderParts.Any() || document.MainDocumentPart.FooterParts.Any();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет параграф на новые параграфы в родительском элементе
|
||||
/// </summary>
|
||||
private static void ReplaceParagraphInParent(Paragraph oldParagraph, List<Paragraph> newParagraphs)
|
||||
{
|
||||
ParagraphReplacer.ReplaceParagraph(oldParagraph, newParagraphs);
|
||||
}
|
||||
}
|
||||
14
QWERTYkez.WordProcessor/IWordReader.cs
Normal file
14
QWERTYkez.WordProcessor/IWordReader.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
public interface IWordReader
|
||||
{
|
||||
long DocumentSize { get; }
|
||||
string? FilePath { get; }
|
||||
bool IsValid { get; }
|
||||
|
||||
ISet<string> FindPlaceholders();
|
||||
|
||||
|
||||
bool TryWrite(string destinationPath, Action<IWordWriter> action);
|
||||
bool TryWrite(Action<IWordWriter> write, Action<IWordReader> read);
|
||||
}
|
||||
29
QWERTYkez.WordProcessor/IWordWriter.cs
Normal file
29
QWERTYkez.WordProcessor/IWordWriter.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
public interface IWordWriter : IWordReader
|
||||
{
|
||||
/// <summary> Добавляет новый параграф с указанным текстом в конец документа. </summary>
|
||||
void AddParagraph(string text, bool preserveFormatting = true);
|
||||
|
||||
|
||||
void ReplaceItem(IDictionary<string, IEnumerable<ReplaceItem>> replacements);
|
||||
void ReplaceItem(IDictionary<string, ReplaceItem> replacements);
|
||||
void ReplaceItem(IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements);
|
||||
void ReplaceItem(IEnumerable<KeyValuePair<string, ReplaceItem>> replacements);
|
||||
void ReplaceItem(string oldValue, IEnumerable<ReplaceItem> newValues);
|
||||
void ReplaceItem(string oldValue, params ReplaceItem[] newValues);
|
||||
void ReplaceString(IDictionary<string, IEnumerable<string>> replacements);
|
||||
void ReplaceString(IDictionary<string, string> replacements);
|
||||
void ReplaceString(IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements);
|
||||
void ReplaceString(IEnumerable<KeyValuePair<string, string>> replacements);
|
||||
void ReplaceString(string oldValue, IEnumerable<string> newValues);
|
||||
void ReplaceString(string oldValue, params string[] newValues);
|
||||
void ReplaceToTable(string oldValue, Action<ITable> buildTable);
|
||||
void ReplaceToText(string oldValue, Action<IText> buildText);
|
||||
void Save();
|
||||
void SaveTo(string path);
|
||||
Task SaveToAsync(string path, CancellationToken cancellationToken = default);
|
||||
bool TrySaveTo(string path, out Exception? error);
|
||||
}
|
||||
106
QWERTYkez.WordProcessor/IeExtension.cs
Normal file
106
QWERTYkez.WordProcessor/IeExtension.cs
Normal file
@@ -0,0 +1,106 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
494
QWERTYkez.WordProcessor/MultiReplace.cs
Normal file
494
QWERTYkez.WordProcessor/MultiReplace.cs
Normal file
@@ -0,0 +1,494 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
|
||||
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение
|
||||
/// остаётся в текущем параграфе, а последующие создают новые.
|
||||
/// Текст между вхождениями и после последнего сохраняется в соответствующих параграфах.
|
||||
/// </summary>
|
||||
internal static class MultiReplaceExt
|
||||
{
|
||||
// ---------- ПУБЛИЧНЫЕ МЕТОДЫ (СИГНАТУРЫ НЕИЗМЕННЫ) ----------
|
||||
|
||||
#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;
|
||||
var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } };
|
||||
body.Replace(dict, comparisonType);
|
||||
}
|
||||
|
||||
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;
|
||||
var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } };
|
||||
body.Replace(dict, comparisonType);
|
||||
}
|
||||
|
||||
#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;
|
||||
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;
|
||||
var newParas = ProcessMultiReplacements(p, replacements, null, comparisonType);
|
||||
if (newParas is not null && newParas.Count > 0)
|
||||
ParagraphReplacer.ReplaceParagraph(p, newParas);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (body is null || replacements is null) return;
|
||||
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;
|
||||
var newParas = ProcessMultiReplacements(p, null, replacements, comparisonType);
|
||||
if (newParas is not null && newParas.Count > 0)
|
||||
ParagraphReplacer.ReplaceParagraph(p, newParas);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Paragraph.ReplaceWithMultiple (один ключ)
|
||||
|
||||
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
|
||||
{
|
||||
if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0)
|
||||
return false;
|
||||
|
||||
var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } };
|
||||
var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType);
|
||||
if (newParas is null || newParas.Count == 0) return false;
|
||||
|
||||
if (paragraph.Parent is not null)
|
||||
{
|
||||
ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
|
||||
{
|
||||
if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0)
|
||||
return false;
|
||||
|
||||
var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } };
|
||||
var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType);
|
||||
if (newParas is null || newParas.Count == 0) return false;
|
||||
|
||||
if (paragraph.Parent is not null)
|
||||
{
|
||||
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)
|
||||
{
|
||||
return ProcessMultiReplacements(paragraph, replacements, null, comparisonType);
|
||||
}
|
||||
|
||||
internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
|
||||
Paragraph paragraph,
|
||||
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements,
|
||||
StringComparison comparisonType)
|
||||
{
|
||||
return ProcessMultiReplacements(paragraph, null, replacements, comparisonType);
|
||||
}
|
||||
|
||||
internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
|
||||
Paragraph paragraph,
|
||||
IEnumerable<KeyValuePair<string, string>> replacements,
|
||||
StringComparison comparisonType)
|
||||
{
|
||||
Dictionary<string, IEnumerable<string>> dict = replacements
|
||||
.Where(kvp => !string.IsNullOrEmpty(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)[kvp.Value]);
|
||||
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
|
||||
{
|
||||
public MatchDefinition Definition { get; set; } = null!;
|
||||
public int Start { get; set; }
|
||||
public int End { get; set; }
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private class ParagraphStructure(string fullText, List<MultiReplaceExt.RunSegment> segments)
|
||||
{
|
||||
public string FullText { get; } = fullText;
|
||||
public List<RunSegment> Segments { get; } = segments;
|
||||
}
|
||||
|
||||
private static ParagraphStructure AnalyzeParagraphStructure(List<Run> runs)
|
||||
{
|
||||
var segments = new List<RunSegment>();
|
||||
var sb = new StringBuilder();
|
||||
int pos = 0;
|
||||
foreach (var run in runs)
|
||||
{
|
||||
string text = GetRunText(run);
|
||||
if (string.IsNullOrEmpty(text)) continue;
|
||||
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();
|
||||
}
|
||||
|
||||
private static Paragraph CloneParagraphProperties(Paragraph original)
|
||||
{
|
||||
var newPara = new Paragraph();
|
||||
if (original.ParagraphProperties is not null)
|
||||
newPara.ParagraphProperties = (ParagraphProperties)original.ParagraphProperties.CloneNode(true);
|
||||
return newPara;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Строит параграф, содержащий копии всех элементов исходного параграфа,
|
||||
/// попадающих в текстовый диапазон [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;
|
||||
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
|
||||
// Находим первый текстовый сегмент, который начинается на или после position
|
||||
var firstTextSeg = structure.Segments.FirstOrDefault(s => s.Start >= position);
|
||||
bool passedFirstText = false;
|
||||
|
||||
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 без текста – добавляем только если уже прошли первый текстовый сегмент
|
||||
if (passedFirstText)
|
||||
newPara.AppendChild(run.CloneNode(true));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seg.Start >= position)
|
||||
{
|
||||
// Полностью после позиции
|
||||
newPara.AppendChild(run.CloneNode(true));
|
||||
if (seg == firstTextSeg)
|
||||
passedFirstText = true;
|
||||
}
|
||||
else if (seg.End > position)
|
||||
{
|
||||
// Частично пересекает – обрезаем текст
|
||||
var runClone = (Run)run.CloneNode(true);
|
||||
foreach (var t in runClone.Elements<Text>().ToList())
|
||||
t.Remove();
|
||||
|
||||
int offset = position - seg.Start;
|
||||
string newText = seg.Text.Substring(offset);
|
||||
runClone.AppendChild(new Text(newText));
|
||||
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())
|
||||
run.Remove();
|
||||
|
||||
if (!newPara.ChildElements.OfType<Run>().Any() && newPara.ParagraphProperties is null)
|
||||
return null;
|
||||
|
||||
return newPara;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вставляет в параграф новый Run с текстом из ReplaceItem,
|
||||
/// копируя форматирование из сегмента, содержащего указанную позицию.
|
||||
/// Если BreakPage == true, добавляет отдельный Run с разрывом страницы.
|
||||
/// </summary>
|
||||
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);
|
||||
textRun.AppendChild(new Text(item.Text ?? string.Empty));
|
||||
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>
|
||||
private static void MergeParagraph(Paragraph target, Paragraph source)
|
||||
{
|
||||
foreach (var child in source.ChildElements)
|
||||
target.AppendChild(child.CloneNode(true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Основной алгоритм: обрабатывает все вхождения всех ключей из предоставленных словарей.
|
||||
/// </summary>
|
||||
private static List<Paragraph>? ProcessMultiReplacements(
|
||||
Paragraph original,
|
||||
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
|
||||
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
|
||||
StringComparison comparisonType)
|
||||
{
|
||||
// 1. Собираем определения замен
|
||||
var definitions = new List<MatchDefinition>();
|
||||
if (stringReplacements is not null)
|
||||
{
|
||||
foreach (var kvp in stringReplacements)
|
||||
{
|
||||
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))]));
|
||||
}
|
||||
}
|
||||
if (itemReplacements is not null)
|
||||
{
|
||||
foreach (var kvp in itemReplacements)
|
||||
{
|
||||
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
|
||||
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
|
||||
}
|
||||
}
|
||||
|
||||
if (definitions.Count == 0) return null;
|
||||
|
||||
// 2. Анализ структуры параграфа
|
||||
var runs = original.Descendants<Run>().ToList();
|
||||
if (runs.Count == 0) return null;
|
||||
var structure = AnalyzeParagraphStructure(runs);
|
||||
string fullText = structure.FullText;
|
||||
if (fullText.Length == 0) return null;
|
||||
|
||||
// 3. Находим все вхождения всех ключей
|
||||
var matches = new List<Match>();
|
||||
foreach (var def in definitions)
|
||||
{
|
||||
int pos = 0;
|
||||
while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1)
|
||||
{
|
||||
matches.Add(new Match
|
||||
{
|
||||
Definition = def,
|
||||
Start = pos,
|
||||
End = pos + def.Key.Length
|
||||
});
|
||||
pos += def.Key.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.Count == 0) return null;
|
||||
|
||||
// 4. Сортируем по позиции
|
||||
matches.Sort((a, b) => a.Start.CompareTo(b.Start));
|
||||
|
||||
// 5. Построение результирующих параграфов
|
||||
var resultParas = new List<Paragraph>();
|
||||
Paragraph? currentPara = null;
|
||||
int currentPos = 0;
|
||||
|
||||
for (int i = 0; i < matches.Count; i++)
|
||||
{
|
||||
var match = matches[i];
|
||||
|
||||
// Текст перед текущим совпадением (от currentPos до match.Start)
|
||||
if (currentPos < match.Start)
|
||||
{
|
||||
var textPart = BuildRangeParagraph(original, structure, currentPos, match.Start);
|
||||
if (textPart is not null)
|
||||
{
|
||||
if (currentPara is null)
|
||||
{
|
||||
currentPara = textPart;
|
||||
resultParas.Add(currentPara);
|
||||
}
|
||||
else
|
||||
{
|
||||
MergeParagraph(currentPara, textPart);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Обрабатываем значения замены для этого совпадения
|
||||
var values = match.Definition.Values;
|
||||
|
||||
// Первое значение – в текущий параграф (или создаём новый)
|
||||
if (currentPara is null)
|
||||
{
|
||||
currentPara = CloneParagraphProperties(original);
|
||||
resultParas.Add(currentPara);
|
||||
}
|
||||
|
||||
values.ForFirstNext(first =>
|
||||
{
|
||||
InsertFormattedRun(currentPara, first, structure, match.Start);
|
||||
},
|
||||
next =>
|
||||
{
|
||||
// Остальные значения – в новые параграфы
|
||||
var newPara = CloneParagraphProperties(original);
|
||||
InsertFormattedRun(newPara, next, structure, match.Start);
|
||||
resultParas.Add(newPara);
|
||||
currentPara = newPara; // теперь текущий параграф – последний созданный
|
||||
});
|
||||
|
||||
currentPos = match.End;
|
||||
}
|
||||
|
||||
// Текст после последнего совпадения – используем BuildAfterParagraph, чтобы пропустить лишние разрывы
|
||||
if (currentPos < fullText.Length)
|
||||
{
|
||||
var textPart = BuildAfterParagraph(original, structure, currentPos);
|
||||
if (textPart is not null)
|
||||
{
|
||||
if (currentPara is null)
|
||||
{
|
||||
currentPara = textPart;
|
||||
resultParas.Add(currentPara);
|
||||
}
|
||||
else
|
||||
{
|
||||
MergeParagraph(currentPara, textPart);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Удаляем пустые параграфы
|
||||
for (int i = resultParas.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!resultParas[i].ChildElements.OfType<Run>().Any() && resultParas[i].ParagraphProperties is null)
|
||||
resultParas.RemoveAt(i);
|
||||
}
|
||||
|
||||
return resultParas.Count > 0 ? resultParas : null;
|
||||
}
|
||||
}
|
||||
135
QWERTYkez.WordProcessor/NormalizedSet.cs
Normal file
135
QWERTYkez.WordProcessor/NormalizedSet.cs
Normal file
@@ -0,0 +1,135 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Множество строк, которое автоматически приводит все добавляемые элементы
|
||||
/// к верхнему регистру и удаляет диакритические знаки (например, 'ё' -> 'Е').
|
||||
/// Реализует ISet<string>, поэтому может использоваться там, где ожидается этот интерфейс.
|
||||
/// </summary>
|
||||
public class NormalizedSet : ISet<string>
|
||||
{
|
||||
private readonly HashSet<string> _inner;
|
||||
|
||||
/// <summary>
|
||||
/// Создаёт пустое нормализованное множество.
|
||||
/// </summary>
|
||||
public NormalizedSet()
|
||||
{
|
||||
_inner = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создаёт нормализованное множество, заполненное элементами из указанной коллекции.
|
||||
/// </summary>
|
||||
/// <param name="collection">Коллекция, элементы которой будут нормализованы и добавлены.</param>
|
||||
public NormalizedSet(IEnumerable<string> collection)
|
||||
{
|
||||
_inner = [.. collection.Select(Normalize)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Нормализует строку: верхний регистр и удаление диакритики.
|
||||
/// </summary>
|
||||
private static string Normalize(string s)
|
||||
{
|
||||
if (string.IsNullOrEmpty(s))
|
||||
return s;
|
||||
|
||||
var normalized = s.Normalize(NormalizationForm.FormD);
|
||||
var sb = new StringBuilder();
|
||||
foreach (char c in normalized)
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
|
||||
sb.Append(c);
|
||||
}
|
||||
return sb.ToString().Normalize(NormalizationForm.FormC).ToUpperInvariant();
|
||||
}
|
||||
|
||||
// ---------- Реализация ISet<string> ----------
|
||||
|
||||
public bool Add(string item) => _inner.Add(Normalize(item));
|
||||
|
||||
void ICollection<string>.Add(string item) => Add(item);
|
||||
|
||||
public void UnionWith(IEnumerable<string> other)
|
||||
{
|
||||
foreach (var item in other)
|
||||
Add(item);
|
||||
}
|
||||
|
||||
public void IntersectWith(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
_inner.IntersectWith(normalizedOther);
|
||||
}
|
||||
|
||||
public void ExceptWith(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
_inner.ExceptWith(normalizedOther);
|
||||
}
|
||||
|
||||
public void SymmetricExceptWith(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
_inner.SymmetricExceptWith(normalizedOther);
|
||||
}
|
||||
|
||||
public bool IsSubsetOf(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
return _inner.IsSubsetOf(normalizedOther);
|
||||
}
|
||||
|
||||
public bool IsSupersetOf(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
return _inner.IsSupersetOf(normalizedOther);
|
||||
}
|
||||
|
||||
public bool IsProperSupersetOf(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
return _inner.IsProperSupersetOf(normalizedOther);
|
||||
}
|
||||
|
||||
public bool IsProperSubsetOf(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
return _inner.IsProperSubsetOf(normalizedOther);
|
||||
}
|
||||
|
||||
public bool Overlaps(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
return _inner.Overlaps(normalizedOther);
|
||||
}
|
||||
|
||||
public bool SetEquals(IEnumerable<string> other)
|
||||
{
|
||||
var normalizedOther = new HashSet<string>(other.Select(Normalize));
|
||||
return _inner.SetEquals(normalizedOther);
|
||||
}
|
||||
|
||||
// ---------- Реализация ICollection<string> ----------
|
||||
|
||||
public int Count => _inner.Count;
|
||||
|
||||
public bool IsReadOnly => false;
|
||||
|
||||
public void Clear() => _inner.Clear();
|
||||
|
||||
public bool Contains(string item) => _inner.Contains(Normalize(item));
|
||||
|
||||
public void CopyTo(string[] array, int arrayIndex) => _inner.CopyTo(array, arrayIndex);
|
||||
|
||||
public bool Remove(string item) => _inner.Remove(Normalize(item));
|
||||
|
||||
// ---------- Реализация IEnumerable<string> и IEnumerable ----------
|
||||
|
||||
public IEnumerator<string> GetEnumerator() => _inner.GetEnumerator();
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
47
QWERTYkez.WordProcessor/ParagraphReplacer.cs
Normal file
47
QWERTYkez.WordProcessor/ParagraphReplacer.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Вспомогательный класс для замены параграфов в различных контейнерах
|
||||
/// </summary>
|
||||
internal static class ParagraphReplacer
|
||||
{
|
||||
/// <summary>
|
||||
/// Заменяет параграф на новые параграфы в родительском элементе
|
||||
/// </summary>
|
||||
/// <param name="oldParagraph">Старый параграф для замены</param>
|
||||
/// <param name="newParagraphs">Новые параграфы</param>
|
||||
internal static void ReplaceParagraph(Paragraph oldParagraph, List<Paragraph> newParagraphs)
|
||||
{
|
||||
if (oldParagraph is null || newParagraphs is null || newParagraphs.Count == 0)
|
||||
return;
|
||||
|
||||
var parent = oldParagraph.Parent;
|
||||
if (parent is null)
|
||||
return;
|
||||
|
||||
int paraIndex = -1;
|
||||
var children = parent.ChildElements;
|
||||
|
||||
// Находим индекс параграфа
|
||||
for (int i = 0; i < children.Count; i++)
|
||||
{
|
||||
if (children[i] == oldParagraph)
|
||||
{
|
||||
paraIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (paraIndex == -1)
|
||||
return;
|
||||
|
||||
// Удаляем старый параграф
|
||||
parent.RemoveChild(oldParagraph);
|
||||
|
||||
// Вставляем новые параграфы
|
||||
for (int i = 0; i < newParagraphs.Count; i++)
|
||||
{
|
||||
parent.InsertAt(newParagraphs[i], paraIndex + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
175
QWERTYkez.WordProcessor/PlaceholderFinder.cs
Normal file
175
QWERTYkez.WordProcessor/PlaceholderFinder.cs
Normal file
@@ -0,0 +1,175 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
internal static class PlaceholderFinder
|
||||
{
|
||||
public static ISet<string> FindInDocument(WordprocessingDocument doc, Body body)
|
||||
{
|
||||
ISet<string> result = new NormalizedSet();
|
||||
|
||||
// 1. Основной текст
|
||||
FindInParagraphs(body.Elements<Paragraph>(), result);
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
foreach (var table in body.Descendants<Table>())
|
||||
{
|
||||
FindInParagraphs(table.Descendants<Paragraph>(), result);
|
||||
}
|
||||
|
||||
// 3. Колонтитулы
|
||||
FindInHeadersAndFooters(doc, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void FindInParagraphs(IEnumerable<Paragraph> paragraphs, ISet<string> result)
|
||||
{
|
||||
// Локальная коллекция для каждого вызова - оптимизация для уменьшения аллокаций
|
||||
List<string>? tempList = null;
|
||||
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
var text = GetParagraphText(paragraph);
|
||||
if (string.IsNullOrEmpty(text)) continue;
|
||||
|
||||
// Откладываем создание списка до первого найденного плейсхолдера
|
||||
bool hasPlaceholders = FindPlaceholdersInText(text, ref tempList);
|
||||
|
||||
if (hasPlaceholders && tempList is not null)
|
||||
{
|
||||
// Добавляем найденные плейсхолдеры с учетом регистра
|
||||
foreach (var placeholder in tempList)
|
||||
{
|
||||
result.Add(placeholder);
|
||||
}
|
||||
tempList.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static unsafe bool FindPlaceholdersInText(string text, ref List<string>? output)
|
||||
{
|
||||
fixed (char* pText = text)
|
||||
{
|
||||
char* start = pText;
|
||||
char* end = pText + text.Length;
|
||||
bool foundAny = false;
|
||||
|
||||
while (start < end)
|
||||
{
|
||||
// Ищем начало плейсхолдера
|
||||
char* dollarStart = null;
|
||||
while (start < end)
|
||||
{
|
||||
if (*start == '$')
|
||||
{
|
||||
dollarStart = start;
|
||||
start++;
|
||||
break;
|
||||
}
|
||||
start++;
|
||||
}
|
||||
|
||||
if (dollarStart is null || start >= end) break;
|
||||
|
||||
// Ищем конец плейсхолдера
|
||||
char* dollarEnd = null;
|
||||
char* contentStart = start; // Начало содержимого (после первого $)
|
||||
|
||||
while (start < end)
|
||||
{
|
||||
if (*start == '$')
|
||||
{
|
||||
dollarEnd = start;
|
||||
start++;
|
||||
break;
|
||||
}
|
||||
start++;
|
||||
}
|
||||
|
||||
if (dollarEnd is null) break;
|
||||
|
||||
// Извлекаем содержимое между долларами
|
||||
int contentLength = (int)(dollarEnd - contentStart);
|
||||
if (contentLength > 0) // Игнорируем пустые "$$"
|
||||
{
|
||||
foundAny = true;
|
||||
output ??= [];
|
||||
|
||||
string content = new(contentStart, 0, contentLength);
|
||||
output.Add(content);
|
||||
}
|
||||
}
|
||||
|
||||
return foundAny;
|
||||
}
|
||||
}
|
||||
|
||||
private static void FindInHeadersAndFooters(WordprocessingDocument doc, ISet<string> result)
|
||||
{
|
||||
if (doc.MainDocumentPart is null) return;
|
||||
|
||||
// Верхние колонтитулы
|
||||
foreach (var headerPart in doc.MainDocumentPart.HeaderParts)
|
||||
{
|
||||
if (headerPart?.Header is not null)
|
||||
{
|
||||
FindInParagraphs(headerPart.Header.Descendants<Paragraph>(), result);
|
||||
}
|
||||
}
|
||||
|
||||
// Нижние колонтитулы
|
||||
foreach (var footerPart in doc.MainDocumentPart.FooterParts)
|
||||
{
|
||||
if (footerPart?.Footer is not null)
|
||||
{
|
||||
FindInParagraphs(footerPart.Footer.Descendants<Paragraph>(), result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetParagraphText(Paragraph paragraph)
|
||||
{
|
||||
if (paragraph is null) return string.Empty;
|
||||
|
||||
// Используем Span для минимальных аллокаций
|
||||
var texts = paragraph.Descendants<Text>();
|
||||
|
||||
// Быстрая проверка: если всего один WordText элемент
|
||||
if (texts is ICollection<Text> collection && collection.Count == 1)
|
||||
{
|
||||
foreach (var text in collection)
|
||||
{
|
||||
return text.Text ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
// Для нескольких WordText элементов
|
||||
int totalLength = 0;
|
||||
|
||||
// Первый проход: подсчет общей длины
|
||||
foreach (var text in texts)
|
||||
{
|
||||
if (text.Text is not null)
|
||||
{
|
||||
totalLength += text.Text.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (totalLength == 0) return string.Empty;
|
||||
|
||||
// Второй проход: копирование
|
||||
var chars = new char[totalLength];
|
||||
int position = 0;
|
||||
|
||||
foreach (var text in texts)
|
||||
{
|
||||
if (text.Text is not null)
|
||||
{
|
||||
text.Text.CopyTo(0, chars, position, text.Text.Length);
|
||||
position += text.Text.Length;
|
||||
}
|
||||
}
|
||||
|
||||
return new string(chars);
|
||||
}
|
||||
}
|
||||
15
QWERTYkez.WordProcessor/QWERTYkez.WordProcessor.csproj
Normal file
15
QWERTYkez.WordProcessor/QWERTYkez.WordProcessor.csproj
Normal file
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
|
||||
<PackageReference Include="IsExternalInit" Version="1.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
24
QWERTYkez.WordProcessor/ReplaceItem.cs
Normal file
24
QWERTYkez.WordProcessor/ReplaceItem.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
public readonly struct ReplaceItem
|
||||
{
|
||||
public ReplaceItem() { }
|
||||
public ReplaceItem(string text)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
public ReplaceItem(string text, bool breakPage)
|
||||
{
|
||||
Text = text;
|
||||
BreakPage = breakPage;
|
||||
}
|
||||
|
||||
public string Text { get; init; } = string.Empty;
|
||||
public bool BreakPage { get; init; } = false;
|
||||
|
||||
|
||||
// Неявное преобразование из ReplaceItem в string
|
||||
//public static implicit operator string(ReplaceItem item) => item.Text;
|
||||
// Явное преобразование из string в ReplaceItem
|
||||
public static explicit operator ReplaceItem(string text) => new() { Text = text };
|
||||
}
|
||||
220
QWERTYkez.WordProcessor/ReplaceToTableExt.cs
Normal file
220
QWERTYkez.WordProcessor/ReplaceToTableExt.cs
Normal file
@@ -0,0 +1,220 @@
|
||||
using QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
internal static class ReplaceToTableExt
|
||||
{
|
||||
/// <summary>
|
||||
/// Заменяет параграф на таблицу, созданную с помощью TableBuilder
|
||||
/// </summary>
|
||||
internal static void ReplaceWithTableBuilder(Paragraph paragraph, Action<TableBuilder> buildTable, FontProps? baseFont)
|
||||
{
|
||||
if (paragraph is null || paragraph.Parent is null || buildTable is null)
|
||||
return;
|
||||
|
||||
var parent = paragraph.Parent;
|
||||
|
||||
// Создаем TableBuilder с базовым шрифтом
|
||||
var builder = TableBuilder.Create(baseFont);
|
||||
buildTable(builder);
|
||||
var table = builder.Build();
|
||||
|
||||
// Находим индекс параграфа среди детей родителя
|
||||
int paraIndex = -1;
|
||||
var children = parent.ChildElements;
|
||||
|
||||
for (int i = 0; i < children.Count; i++)
|
||||
{
|
||||
if (children[i] == paragraph)
|
||||
{
|
||||
paraIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (paraIndex == -1)
|
||||
return;
|
||||
|
||||
// Удаляем старый параграф и вставляем таблицу на его место
|
||||
parent.RemoveChild(paragraph);
|
||||
parent.InsertAt(table, paraIndex);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет все параграфы, содержащие указанный текст, на таблицы
|
||||
/// </summary>
|
||||
internal static void ReplaceParagraphsContainingTextToTable(Body body,
|
||||
string oldValue, Action<TableBuilder> buildTable)
|
||||
{
|
||||
if (body is null || string.IsNullOrEmpty(oldValue) || buildTable is null)
|
||||
return;
|
||||
|
||||
var paragraphs = body.Elements<Paragraph>().ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
for (int i = paragraphs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var paragraph = paragraphs[i];
|
||||
if (paragraph is null) continue;
|
||||
|
||||
var paraText = paragraph.InnerText;
|
||||
if (string.IsNullOrEmpty(paraText) ||
|
||||
paraText.IndexOf(oldValue, StringComparison.OrdinalIgnoreCase) < 0)
|
||||
continue;
|
||||
|
||||
// Извлекаем свойства шрифта для передачи в TableBuilder
|
||||
var fontProps = ExtractFontPropsFromParagraph(paragraph, oldValue);
|
||||
|
||||
// Заменяем параграф на таблицу
|
||||
ReplaceWithTableBuilder(paragraph, buildTable, fontProps);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Извлекает свойства шрифта (FontProps) из Run, содержащего указанный текст в параграфе.
|
||||
/// </summary>
|
||||
private static FontProps? ExtractFontPropsFromParagraph(Paragraph paragraph, string searchText)
|
||||
{
|
||||
if (paragraph is null || string.IsNullOrEmpty(searchText))
|
||||
return null;
|
||||
|
||||
var runs = paragraph.Descendants<Run>().ToList();
|
||||
if (runs.Count == 0)
|
||||
return null;
|
||||
|
||||
// Собираем полный текст параграфа и позиции каждого Run для анализа
|
||||
var runInfos = new List<(Run Run, int Start, int End, string Text)>();
|
||||
int currentPosition = 0;
|
||||
|
||||
foreach (var run in runs)
|
||||
{
|
||||
var runText = GetRunText(run);
|
||||
if (!string.IsNullOrEmpty(runText))
|
||||
{
|
||||
runInfos.Add((run, currentPosition, currentPosition + runText.Length, runText));
|
||||
currentPosition += runText.Length;
|
||||
}
|
||||
}
|
||||
|
||||
// Ищем Run, который содержит искомый текст (регистронезависимо)
|
||||
foreach (var (run, start, end, text) in runInfos)
|
||||
{
|
||||
// Проверяем, содержится ли искомый текст в этом Run
|
||||
if (text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
return CreateFontPropsFromRun(run);
|
||||
}
|
||||
}
|
||||
|
||||
// Если точное вхождение не найдено, ищем пересечение текста
|
||||
var fullText = string.Concat(runInfos.Select(r => r.Text));
|
||||
int textIndex = fullText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (textIndex >= 0)
|
||||
{
|
||||
// Находим первый Run, который пересекается с найденным текстом
|
||||
var intersectingRun = runInfos.FirstOrDefault(r =>
|
||||
r.Start <= textIndex && r.End > textIndex);
|
||||
|
||||
if (intersectingRun.Run is not null)
|
||||
{
|
||||
return CreateFontPropsFromRun(intersectingRun.Run);
|
||||
}
|
||||
}
|
||||
|
||||
return null; // Не удалось найти подходящий Run
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создаёт FontProps на основе свойств указанного Run.
|
||||
/// </summary>
|
||||
private static FontProps CreateFontPropsFromRun(Run run)
|
||||
{
|
||||
var runProperties = run.RunProperties;
|
||||
if (runProperties is null)
|
||||
return new FontProps();
|
||||
|
||||
var fontProps = new FontProps();
|
||||
|
||||
// Font Family
|
||||
var runFonts = runProperties.GetFirstChild<RunFonts>();
|
||||
if (runFonts is not null)
|
||||
{
|
||||
fontProps = fontProps with
|
||||
{
|
||||
FontFamily = runFonts.Ascii ?? runFonts.HighAnsi ?? runFonts.ComplexScript
|
||||
};
|
||||
}
|
||||
|
||||
// Font Size
|
||||
var fontSize = runProperties.GetFirstChild<FontSize>();
|
||||
if (fontSize is not null && !string.IsNullOrEmpty(fontSize.Val) &&
|
||||
uint.TryParse(fontSize.Val, out uint halfPoints))
|
||||
{
|
||||
fontProps = fontProps with { Size = halfPoints / 2.0 };
|
||||
}
|
||||
|
||||
// Bold
|
||||
var bold = runProperties.GetFirstChild<Bold>();
|
||||
if (bold is not null)
|
||||
{
|
||||
bool isBold = true;
|
||||
if (bold.Val is not null)
|
||||
{
|
||||
isBold = bold.Val.Value;
|
||||
}
|
||||
fontProps = fontProps with { IsBold = isBold };
|
||||
}
|
||||
|
||||
// Italic
|
||||
var italic = runProperties.GetFirstChild<Italic>();
|
||||
if (italic is not null)
|
||||
{
|
||||
bool isItalic = true;
|
||||
if (italic.Val is not null)
|
||||
{
|
||||
isItalic = italic.Val.Value;
|
||||
}
|
||||
fontProps = fontProps with { IsItalic = isItalic };
|
||||
}
|
||||
|
||||
// Underline
|
||||
var underline = runProperties.GetFirstChild<Underline>();
|
||||
if (underline is not null && underline.Val is not null)
|
||||
{
|
||||
fontProps = fontProps with { Underline = underline.Val.Value };
|
||||
}
|
||||
|
||||
// Color
|
||||
var color = runProperties.GetFirstChild<Color>();
|
||||
if (color is not null && !string.IsNullOrEmpty(color.Val))
|
||||
{
|
||||
fontProps = fontProps with { Color = color.Val };
|
||||
}
|
||||
|
||||
// Subscript/Superscript
|
||||
var verticalAlignment = runProperties.GetFirstChild<VerticalTextAlignment>();
|
||||
if (verticalAlignment is not null && verticalAlignment.Val is not null)
|
||||
{
|
||||
fontProps = fontProps with { SubSup = verticalAlignment.Val.Value };
|
||||
}
|
||||
|
||||
return fontProps;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вспомогательный метод для получения текста из Run.
|
||||
/// </summary>
|
||||
private static string GetRunText(Run run)
|
||||
{
|
||||
if (run is null) return string.Empty;
|
||||
|
||||
var sb = new StringBuilder();
|
||||
foreach (var text in run.Elements<Text>())
|
||||
{
|
||||
sb.Append(text.Text ?? string.Empty);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
231
QWERTYkez.WordProcessor/ReplaceToTextExt.cs
Normal file
231
QWERTYkez.WordProcessor/ReplaceToTextExt.cs
Normal file
@@ -0,0 +1,231 @@
|
||||
using QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Вспомогательный класс для замены параграфов, содержащих указанный текст, на текст, построенный с помощью TextBuilder.
|
||||
/// </summary>
|
||||
internal static class ReplaceToTextExt
|
||||
{
|
||||
/// <summary>
|
||||
/// Заменяет все параграфы, содержащие указанный текст, на текст, построенный с помощью TextBuilder.
|
||||
/// </summary>
|
||||
internal static void ReplaceParagraphsContainingTextToText(
|
||||
Body body,
|
||||
string oldValue,
|
||||
Action<IText> buildText)
|
||||
{
|
||||
if (body is null || string.IsNullOrEmpty(oldValue) || buildText is null)
|
||||
return;
|
||||
|
||||
var paragraphs = body.Elements<Paragraph>().ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
for (int i = paragraphs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var paragraph = paragraphs[i];
|
||||
if (paragraph is null) continue;
|
||||
|
||||
var paraText = paragraph.InnerText;
|
||||
if (string.IsNullOrEmpty(paraText) ||
|
||||
paraText.IndexOf(oldValue, StringComparison.OrdinalIgnoreCase) < 0)
|
||||
continue;
|
||||
|
||||
// Извлекаем свойства шрифта для передачи в TextBuilder
|
||||
var fontProps = ExtractFontPropsFromParagraph(paragraph, oldValue);
|
||||
// Извлекаем свойства параграфа для наследования
|
||||
var paragraphProps = paragraph.ParagraphProperties?.CloneNode(true) as ParagraphProperties;
|
||||
|
||||
// Заменяем параграф на текст с наследованием форматирования
|
||||
ReplaceWithTextBuilder(paragraph, buildText, fontProps, paragraphProps);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReplaceWithTextBuilder(
|
||||
Paragraph paragraph,
|
||||
Action<IText> buildText,
|
||||
FontProps? baseFont,
|
||||
ParagraphProperties? baseParagraphProps)
|
||||
{
|
||||
if (paragraph is null || paragraph.Parent is null || buildText is null)
|
||||
return;
|
||||
|
||||
var parent = paragraph.Parent;
|
||||
|
||||
// Создаем TextBuilder с базовым шрифтом и свойствами параграфа
|
||||
var builder = TextBuilder.Create(baseFont, baseParagraphProps);
|
||||
buildText(builder);
|
||||
var newParagraphs = builder.Build();
|
||||
|
||||
// Находим индекс параграфа среди детей родителя
|
||||
int paraIndex = -1;
|
||||
var children = parent.ChildElements;
|
||||
|
||||
for (int i = 0; i < children.Count; i++)
|
||||
{
|
||||
if (children[i] == paragraph)
|
||||
{
|
||||
paraIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (paraIndex == -1)
|
||||
return;
|
||||
|
||||
parent.RemoveChild(paragraph);
|
||||
|
||||
for (int i = 0; i < newParagraphs.Count; i++)
|
||||
{
|
||||
parent.InsertAt(newParagraphs[i], paraIndex + i);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Извлекает свойства шрифта (FontProps) из Run, содержащего указанный текст в параграфе.
|
||||
/// </summary>
|
||||
private static FontProps? ExtractFontPropsFromParagraph(Paragraph paragraph, string searchText)
|
||||
{
|
||||
if (paragraph is null || string.IsNullOrEmpty(searchText))
|
||||
return null;
|
||||
|
||||
var runs = paragraph.Descendants<Run>().ToList();
|
||||
if (runs.Count == 0)
|
||||
return null;
|
||||
|
||||
// Собираем полный текст параграфа и позиции каждого Run для анализа
|
||||
var runInfos = new List<(Run Run, int Start, int End, string Text)>();
|
||||
int currentPosition = 0;
|
||||
|
||||
foreach (var run in runs)
|
||||
{
|
||||
var runText = GetRunText(run);
|
||||
if (!string.IsNullOrEmpty(runText))
|
||||
{
|
||||
runInfos.Add((run, currentPosition, currentPosition + runText.Length, runText));
|
||||
currentPosition += runText.Length;
|
||||
}
|
||||
}
|
||||
|
||||
// Ищем Run, который содержит искомый текст (регистронезависимо)
|
||||
foreach (var (run, start, end, text) in runInfos)
|
||||
{
|
||||
// Проверяем, содержится ли искомый текст в этом Run
|
||||
if (text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
return CreateFontPropsFromRun(run);
|
||||
}
|
||||
}
|
||||
|
||||
// Если точное вхождение не найдено, ищем пересечение текста
|
||||
var fullText = string.Concat(runInfos.Select(r => r.Text));
|
||||
int textIndex = fullText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (textIndex >= 0)
|
||||
{
|
||||
// Находим первый Run, который пересекается с найденным текстом
|
||||
var intersectingRun = runInfos.FirstOrDefault(r =>
|
||||
r.Start <= textIndex && r.End > textIndex);
|
||||
|
||||
if (intersectingRun.Run is not null)
|
||||
{
|
||||
return CreateFontPropsFromRun(intersectingRun.Run);
|
||||
}
|
||||
}
|
||||
|
||||
return null; // Не удалось найти подходящий Run
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создаёт FontProps на основе свойств указанного Run.
|
||||
/// </summary>
|
||||
private static FontProps CreateFontPropsFromRun(Run run)
|
||||
{
|
||||
var runProperties = run.RunProperties;
|
||||
if (runProperties is null)
|
||||
return new FontProps();
|
||||
|
||||
var fontProps = new FontProps();
|
||||
|
||||
// Font Family
|
||||
var runFonts = runProperties.GetFirstChild<RunFonts>();
|
||||
if (runFonts is not null)
|
||||
{
|
||||
fontProps = fontProps with
|
||||
{
|
||||
FontFamily = runFonts.Ascii ?? runFonts.HighAnsi ?? runFonts.ComplexScript
|
||||
};
|
||||
}
|
||||
|
||||
// Font Size
|
||||
var fontSize = runProperties.GetFirstChild<FontSize>();
|
||||
if (fontSize is not null && !string.IsNullOrEmpty(fontSize.Val) &&
|
||||
uint.TryParse(fontSize.Val, out uint halfPoints))
|
||||
{
|
||||
fontProps = fontProps with { Size = halfPoints / 2.0 };
|
||||
}
|
||||
|
||||
// Bold
|
||||
var bold = runProperties.GetFirstChild<Bold>();
|
||||
if (bold is not null)
|
||||
{
|
||||
bool isBold = true;
|
||||
if (bold.Val is not null)
|
||||
{
|
||||
isBold = bold.Val.Value;
|
||||
}
|
||||
fontProps = fontProps with { IsBold = isBold };
|
||||
}
|
||||
|
||||
// Italic
|
||||
var italic = runProperties.GetFirstChild<Italic>();
|
||||
if (italic is not null)
|
||||
{
|
||||
bool isItalic = true;
|
||||
if (italic.Val is not null)
|
||||
{
|
||||
isItalic = italic.Val.Value;
|
||||
}
|
||||
fontProps = fontProps with { IsItalic = isItalic };
|
||||
}
|
||||
|
||||
// Underline
|
||||
var underline = runProperties.GetFirstChild<Underline>();
|
||||
if (underline is not null && underline.Val is not null)
|
||||
{
|
||||
fontProps = fontProps with { Underline = underline.Val.Value };
|
||||
}
|
||||
|
||||
// Color
|
||||
var color = runProperties.GetFirstChild<Color>();
|
||||
if (color is not null && !string.IsNullOrEmpty(color.Val))
|
||||
{
|
||||
fontProps = fontProps with { Color = color.Val };
|
||||
}
|
||||
|
||||
// Subscript/Superscript
|
||||
var verticalAlignment = runProperties.GetFirstChild<VerticalTextAlignment>();
|
||||
if (verticalAlignment is not null && verticalAlignment.Val is not null)
|
||||
{
|
||||
fontProps = fontProps with { SubSup = verticalAlignment.Val.Value };
|
||||
}
|
||||
|
||||
return fontProps;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вспомогательный метод для получения текста из Run.
|
||||
/// </summary>
|
||||
private static string GetRunText(Run run)
|
||||
{
|
||||
if (run is null) return string.Empty;
|
||||
|
||||
var sb = new StringBuilder();
|
||||
foreach (var text in run.Elements<Text>())
|
||||
{
|
||||
sb.Append(text.Text ?? string.Empty);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
374
QWERTYkez.WordProcessor/SimplyReplace.cs
Normal file
374
QWERTYkez.WordProcessor/SimplyReplace.cs
Normal file
@@ -0,0 +1,374 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
internal static class SimplyReplaceExt
|
||||
{
|
||||
private readonly struct TextNodeInfo(Text text, int startIndex, int length)
|
||||
{
|
||||
internal readonly Text Text = text;
|
||||
internal readonly int StartIndex = startIndex;
|
||||
internal readonly int Length = length;
|
||||
}
|
||||
|
||||
private sealed class ParagraphStructure(string fullText, SimplyReplaceExt.TextNodeInfo[] textNodes)
|
||||
{
|
||||
internal readonly string FullText = fullText;
|
||||
internal readonly TextNodeInfo[] TextNodes = textNodes;
|
||||
|
||||
internal int FindFirstNodeIndexAtPosition(int position)
|
||||
{
|
||||
if (position < 0 || position >= FullText.Length)
|
||||
return -1;
|
||||
|
||||
int left = 0;
|
||||
int right = TextNodes.Length - 1;
|
||||
int result = -1;
|
||||
|
||||
while (left <= right)
|
||||
{
|
||||
int mid = left + ((right - left) >> 1);
|
||||
if (TextNodes[mid].StartIndex <= position)
|
||||
{
|
||||
result = mid;
|
||||
left = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result >= 0 && TextNodes[result].StartIndex + TextNodes[result].Length > position
|
||||
? result : -1;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Replace(this Body body, string oldValue, string newValue, StringComparison comparisonType)
|
||||
{
|
||||
if (body is null || string.IsNullOrEmpty(oldValue)) return;
|
||||
|
||||
var paragraphs = body.Elements<Paragraph>();
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
paragraph?.SimpleReplace(oldValue, newValue, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (body is null || replacements is null || replacements.Count() == 0)
|
||||
return;
|
||||
|
||||
var paragraphs = body.Elements<Paragraph>();
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
paragraph?.Replace(replacements, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, ReplaceItem>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (body is null || replacements is null || replacements.Count() == 0)
|
||||
return;
|
||||
|
||||
var paragraphs = body.Elements<Paragraph>();
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
paragraph?.Replace(replacements, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, bool breakPage = false)
|
||||
{
|
||||
if (paragraph is null || string.IsNullOrEmpty(oldValue))
|
||||
return false;
|
||||
|
||||
var paragraphText = paragraph.InnerText;
|
||||
if (string.IsNullOrEmpty(paragraphText))
|
||||
return false;
|
||||
|
||||
int matchIndex = paragraphText.IndexOf(oldValue, comparisonType);
|
||||
if (matchIndex == -1)
|
||||
return false;
|
||||
|
||||
var runs = paragraph.Elements<Run>();
|
||||
if (!runs.Any())
|
||||
return false;
|
||||
|
||||
var structure = AnalyzeParagraphStructure(runs);
|
||||
if (structure.FullText.Length == 0)
|
||||
return false;
|
||||
|
||||
int matchEnd = matchIndex + oldValue.Length;
|
||||
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
||||
if (nodesToReplace.Count == 0)
|
||||
return false;
|
||||
|
||||
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, newValue, breakPage);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static void Replace(this Paragraph paragraph, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (paragraph is null || replacements is null || replacements.Count() == 0)
|
||||
return;
|
||||
|
||||
var runs = paragraph.Elements<Run>().ToList();
|
||||
if (runs.Count == 0)
|
||||
return;
|
||||
|
||||
var structure = AnalyzeParagraphStructure(runs);
|
||||
if (structure.FullText.Length == 0)
|
||||
return;
|
||||
|
||||
// Используем List с предопределенной емкостью
|
||||
var replacementsInParagraph = new List<ReplacementInfo>(replacements.Count() * 2);
|
||||
|
||||
// Сначала находим все вхождения
|
||||
var fullText = structure.FullText;
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (string.IsNullOrEmpty(kvp.Key))
|
||||
continue;
|
||||
|
||||
int pos = 0;
|
||||
while ((pos = fullText.IndexOf(kvp.Key, pos, comparisonType)) != -1)
|
||||
{
|
||||
replacementsInParagraph.Add(new ReplacementInfo
|
||||
{
|
||||
OldValue = kvp.Key,
|
||||
NewValue = kvp.Value ?? string.Empty,
|
||||
Index = pos
|
||||
});
|
||||
pos += kvp.Key.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (replacementsInParagraph.Count == 0)
|
||||
return;
|
||||
|
||||
// Сортируем по убыванию позиции
|
||||
replacementsInParagraph.Sort((x, y) => y.Index.CompareTo(x.Index));
|
||||
|
||||
// Выполняем замены
|
||||
for (int i = 0; i < replacementsInParagraph.Count; i++)
|
||||
{
|
||||
var replacement = replacementsInParagraph[i];
|
||||
int matchIndex = replacement.Index;
|
||||
int matchEnd = matchIndex + replacement.OldValue.Length;
|
||||
|
||||
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
||||
if (nodesToReplace.Count > 0)
|
||||
{
|
||||
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Replace(this Paragraph paragraph, IEnumerable<KeyValuePair<string, ReplaceItem>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (paragraph is null || replacements is null || replacements.Count() == 0)
|
||||
return;
|
||||
|
||||
var runs = paragraph.Elements<Run>().ToList();
|
||||
if (runs.Count == 0)
|
||||
return;
|
||||
|
||||
var structure = AnalyzeParagraphStructure(runs);
|
||||
if (structure.FullText.Length == 0)
|
||||
return;
|
||||
|
||||
// Используем List с предопределенной емкостью
|
||||
var replacementsInParagraph = new List<ReplacementInfo>(replacements.Count() * 2);
|
||||
|
||||
// Сначала находим все вхождения
|
||||
var fullText = structure.FullText;
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (string.IsNullOrEmpty(kvp.Key))
|
||||
continue;
|
||||
|
||||
int pos = 0;
|
||||
while ((pos = fullText.IndexOf(kvp.Key, pos, comparisonType)) != -1)
|
||||
{
|
||||
replacementsInParagraph.Add(new ReplacementInfo
|
||||
{
|
||||
OldValue = kvp.Key,
|
||||
NewValue = kvp.Value.Text ?? string.Empty,
|
||||
BreakPage = kvp.Value.BreakPage,
|
||||
Index = pos
|
||||
});
|
||||
pos += kvp.Key.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (replacementsInParagraph.Count == 0)
|
||||
return;
|
||||
|
||||
// Сортируем по убыванию позиции
|
||||
replacementsInParagraph.Sort((x, y) => y.Index.CompareTo(x.Index));
|
||||
|
||||
// Выполняем замены
|
||||
for (int i = 0; i < replacementsInParagraph.Count; i++)
|
||||
{
|
||||
var replacement = replacementsInParagraph[i];
|
||||
int matchIndex = replacement.Index;
|
||||
int matchEnd = matchIndex + replacement.OldValue.Length;
|
||||
|
||||
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
|
||||
if (nodesToReplace.Count > 0)
|
||||
{
|
||||
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.BreakPage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class ReplacementInfo
|
||||
{
|
||||
internal string OldValue { get; set; } = null!;
|
||||
internal string NewValue { get; set; } = null!;
|
||||
internal int Index { get; set; }
|
||||
internal bool BreakPage { get; set; }
|
||||
}
|
||||
|
||||
private static ParagraphStructure AnalyzeParagraphStructure(IEnumerable<Run> runs)
|
||||
{
|
||||
var textNodesList = new List<TextNodeInfo>(32);
|
||||
var sb = new StringBuilder(256);
|
||||
int currentIndex = 0;
|
||||
|
||||
foreach (var run in runs)
|
||||
{
|
||||
var texts = run.Elements<Text>();
|
||||
foreach (var text in texts)
|
||||
{
|
||||
var textValue = text.Text;
|
||||
if (string.IsNullOrEmpty(textValue))
|
||||
continue;
|
||||
|
||||
textNodesList.Add(new TextNodeInfo(
|
||||
text,
|
||||
currentIndex,
|
||||
textValue.Length
|
||||
));
|
||||
|
||||
sb.Append(textValue);
|
||||
currentIndex += textValue.Length;
|
||||
}
|
||||
}
|
||||
|
||||
return new ParagraphStructure(sb.ToString(), [.. textNodesList]);
|
||||
}
|
||||
|
||||
private static List<TextNodeInfo> FindNodesToReplace(
|
||||
ParagraphStructure structure,
|
||||
int matchStart,
|
||||
int matchEnd)
|
||||
{
|
||||
var result = new List<TextNodeInfo>(4);
|
||||
int firstNodeIndex = structure.FindFirstNodeIndexAtPosition(matchStart);
|
||||
|
||||
if (firstNodeIndex == -1)
|
||||
return result;
|
||||
|
||||
var textNodes = structure.TextNodes;
|
||||
for (int i = firstNodeIndex; i < textNodes.Length; i++)
|
||||
{
|
||||
var node = textNodes[i];
|
||||
if (node.StartIndex >= matchEnd)
|
||||
break;
|
||||
|
||||
if (node.StartIndex + node.Length > matchStart)
|
||||
{
|
||||
result.Add(node);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void ExecuteReplacement(
|
||||
List<TextNodeInfo> nodesToReplace,
|
||||
int matchStart,
|
||||
int matchEnd,
|
||||
string newValue,
|
||||
bool breakPage = false)
|
||||
{
|
||||
if (nodesToReplace.Count == 0) return;
|
||||
|
||||
var firstNode = nodesToReplace[0];
|
||||
string oldText = firstNode.Text.Text ?? string.Empty;
|
||||
int startInFirstNode = matchStart - firstNode.StartIndex;
|
||||
int charsToReplaceInFirstNode = Math.Min(
|
||||
oldText.Length - startInFirstNode,
|
||||
matchEnd - matchStart
|
||||
);
|
||||
|
||||
string processedNewValue = ReplaceSpacesWithNonBreaking(newValue);
|
||||
firstNode.Text.Text = ReplaceSubstringOptimized(
|
||||
oldText,
|
||||
startInFirstNode,
|
||||
charsToReplaceInFirstNode,
|
||||
processedNewValue
|
||||
);
|
||||
|
||||
// Очищаем остальные текстовые ноды
|
||||
for (int i = 1; i < nodesToReplace.Count; i++)
|
||||
{
|
||||
nodesToReplace[i].Text.Text = string.Empty;
|
||||
}
|
||||
|
||||
if (breakPage)
|
||||
{
|
||||
if (nodesToReplace[0].Text.Parent is Run run && run.Parent is Paragraph para)
|
||||
{
|
||||
var breakRun = new Run(new Break() { Type = BreakValues.Page });
|
||||
if (run.RunProperties is not null)
|
||||
breakRun.RunProperties = (RunProperties)run.RunProperties.CloneNode(true);
|
||||
para.AppendChild(breakRun);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static unsafe string ReplaceSpacesWithNonBreaking(string input)
|
||||
{
|
||||
if (!input.Contains(' '))
|
||||
return input;
|
||||
|
||||
fixed (char* pInput = input)
|
||||
{
|
||||
char* resultPtr = stackalloc char[input.Length];
|
||||
for (int i = 0; i < input.Length; i++)
|
||||
{
|
||||
resultPtr[i] = pInput[i] == ' ' ? '\u00A0' : pInput[i];
|
||||
}
|
||||
return new string(resultPtr, 0, input.Length);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ReplaceSubstringOptimized(string original, int start, int length, string replacement)
|
||||
{
|
||||
if (string.IsNullOrEmpty(original))
|
||||
return replacement ?? string.Empty;
|
||||
|
||||
if (start < 0 || start >= original.Length || length <= 0)
|
||||
return original;
|
||||
|
||||
if (start == 0 && length == original.Length)
|
||||
return replacement;
|
||||
|
||||
int end = Math.Min(start + length, original.Length);
|
||||
|
||||
// Оптимизированная конкатенация
|
||||
var sb = new StringBuilder(original.Length - length + replacement.Length);
|
||||
if (start > 0)
|
||||
{
|
||||
sb.Append(original, 0, start);
|
||||
}
|
||||
sb.Append(replacement);
|
||||
if (end < original.Length)
|
||||
{
|
||||
sb.Append(original, end, original.Length - end);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
307
QWERTYkez.WordProcessor/TableTextProcessor.cs
Normal file
307
QWERTYkez.WordProcessor/TableTextProcessor.cs
Normal file
@@ -0,0 +1,307 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Обработчик текста в таблицах DOCX документов
|
||||
/// </summary>
|
||||
internal static class TableTextProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// Заменяет текст во всех таблицах указанного элемента
|
||||
/// </summary>
|
||||
internal static void ReplaceInTables(OpenXmlElement element, string oldValue, string newValue, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null || string.IsNullOrEmpty(oldValue) || newValue is null)
|
||||
return;
|
||||
|
||||
var tables = GetAllTables(element).ToList();
|
||||
if (tables.Count == 0)
|
||||
return;
|
||||
|
||||
#if DEBUG
|
||||
int totalTableMatches = 0;
|
||||
int totalTableParagraphs = 0;
|
||||
foreach (var table in tables)
|
||||
{
|
||||
var paragraphs = GetTableParagraphs(table).ToList();
|
||||
totalTableParagraphs += paragraphs.Count;
|
||||
foreach (var para in paragraphs)
|
||||
{
|
||||
if (para?.InnerText?.IndexOf(oldValue, comparisonType) >= 0)
|
||||
{
|
||||
totalTableMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (totalTableMatches > 0)
|
||||
{
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables] Looking for '{oldValue}' in {tables.Count} tables");
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables] Total paragraphs in tables: {totalTableParagraphs}");
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables] Tables with matches: {totalTableMatches}");
|
||||
}
|
||||
#endif
|
||||
|
||||
foreach (var table in tables)
|
||||
{
|
||||
ReplaceInTable(table, oldValue, newValue, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет текст во всех таблицах указанного элемента
|
||||
/// </summary>
|
||||
internal static void ReplaceInTables(OpenXmlElement element, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null || string.IsNullOrEmpty(oldValue) || newValues is null)
|
||||
return;
|
||||
|
||||
var tables = GetAllTables(element).ToList();
|
||||
if (tables.Count == 0)
|
||||
return;
|
||||
|
||||
#if DEBUG
|
||||
int totalTableMatches = 0;
|
||||
int totalTableParagraphs = 0;
|
||||
foreach (var table in tables)
|
||||
{
|
||||
var paragraphs = GetTableParagraphs(table).ToList();
|
||||
totalTableParagraphs += paragraphs.Count;
|
||||
foreach (var para in paragraphs)
|
||||
{
|
||||
if (para?.InnerText?.IndexOf(oldValue, comparisonType) >= 0)
|
||||
{
|
||||
totalTableMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (totalTableMatches > 0)
|
||||
{
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables] Looking for '{oldValue}' in {tables.Count} tables");
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables] Total paragraphs in tables: {totalTableParagraphs}");
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables] Tables with matches: {totalTableMatches}");
|
||||
}
|
||||
#endif
|
||||
|
||||
foreach (var table in tables)
|
||||
{
|
||||
ReplaceInTable(table, oldValue, newValues, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет словарную замену во всех таблицах
|
||||
/// </summary>
|
||||
internal static void ReplaceInTables(OpenXmlElement element, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (element is null || replacements is null || !replacements.Any())
|
||||
return;
|
||||
|
||||
var tables = GetAllTables(element).ToList();
|
||||
if (tables.Count == 0)
|
||||
return;
|
||||
|
||||
#if DEBUG
|
||||
int tablesWithMatches = 0;
|
||||
foreach (var table in tables)
|
||||
{
|
||||
var paragraphs = GetTableParagraphs(table).ToList();
|
||||
foreach (var para in paragraphs)
|
||||
{
|
||||
var paraText = para.InnerText;
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && paraText.IndexOf(kvp.Key, comparisonType) >= 0)
|
||||
{
|
||||
tablesWithMatches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (tablesWithMatches > 0) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tablesWithMatches > 0)
|
||||
{
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables(dict)] START with {replacements.Count()} items");
|
||||
Debug.WriteLine($"[DEBUG] [TableTextProcessor.ReplaceInTables(dict)] Processing {tables.Count} tables, {tablesWithMatches} have matches");
|
||||
}
|
||||
#endif
|
||||
|
||||
foreach (var table in tables)
|
||||
{
|
||||
ReplaceInTable(table, replacements, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет текст в конкретной таблице
|
||||
/// </summary>
|
||||
private static void ReplaceInTable(Table table, string oldValue, string newValue, StringComparison comparisonType)
|
||||
{
|
||||
if (table is null)
|
||||
return;
|
||||
|
||||
var paragraphs = GetTableParagraphs(table).ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
paragraph?.SimpleReplace(oldValue, newValue, comparisonType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет текст в конкретной таблице
|
||||
/// </summary>
|
||||
private static void ReplaceInTable(Table table, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
|
||||
{
|
||||
if (table is null)
|
||||
return;
|
||||
|
||||
var paragraphs = GetTableParagraphs(table).ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
if (newValues.Count() == 1)
|
||||
{
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
paragraph?.SimpleReplace(oldValue, newValues.First(), comparisonType);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = paragraphs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var paragraph = paragraphs[i];
|
||||
if (paragraph is not null && paragraph.InnerText.IndexOf(oldValue, comparisonType) >= 0)
|
||||
{
|
||||
paragraph.ReplaceWithMultiple(oldValue, newValues, comparisonType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет словарную замену в конкретной таблице
|
||||
/// </summary>
|
||||
private static void ReplaceInTable(Table table, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
|
||||
{
|
||||
if (table is null || replacements is null || !replacements.Any())
|
||||
return;
|
||||
|
||||
var paragraphs = GetTableParagraphs(table).ToList();
|
||||
if (paragraphs.Count == 0)
|
||||
return;
|
||||
|
||||
for (int i = paragraphs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var paragraph = paragraphs[i];
|
||||
if (paragraph is null)
|
||||
continue;
|
||||
|
||||
var paraText = paragraph.InnerText;
|
||||
bool hasMatch = false;
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key) && paraText.IndexOf(kvp.Key, comparisonType) >= 0)
|
||||
{
|
||||
hasMatch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasMatch)
|
||||
continue;
|
||||
|
||||
var newParagraphs = MultiReplaceExt.ProcessParagraphWithAllReplacements(paragraph, replacements, comparisonType);
|
||||
if (newParagraphs is not null && newParagraphs.Count > 0)
|
||||
{
|
||||
ReplaceParagraphsInTableCell(paragraph, newParagraphs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Находит и возвращает все таблицы в указанном элементе
|
||||
/// </summary>
|
||||
internal static IEnumerable<Table> GetAllTables(OpenXmlElement element)
|
||||
{
|
||||
if (element is null)
|
||||
yield break;
|
||||
|
||||
// Используем стек вместо очереди для рекурсивного поиска
|
||||
var stack = new Stack<OpenXmlElement>();
|
||||
stack.Push(element);
|
||||
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
var current = stack.Pop();
|
||||
|
||||
if (current is Table table)
|
||||
{
|
||||
yield return table;
|
||||
// Не ищем таблицы внутри таблиц (вложенные таблицы уже будут обработаны как дочерние элементы)
|
||||
continue;
|
||||
}
|
||||
|
||||
// Добавляем дочерние элементы в обратном порядке для сохранения порядка
|
||||
var children = current.ChildElements;
|
||||
for (int i = children.Count - 1; i >= 0; i--)
|
||||
{
|
||||
stack.Push(children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Находит все параграфы внутри таблицы
|
||||
/// </summary>
|
||||
internal static IEnumerable<Paragraph> GetTableParagraphs(Table table)
|
||||
{
|
||||
if (table is null)
|
||||
yield break;
|
||||
|
||||
// Используем обход в ширину для таблиц
|
||||
var cells = new Queue<TableCell>();
|
||||
|
||||
foreach (var row in table.Elements<TableRow>())
|
||||
{
|
||||
foreach (var cell in row.Elements<TableCell>())
|
||||
{
|
||||
cells.Enqueue(cell);
|
||||
}
|
||||
}
|
||||
|
||||
while (cells.Count > 0)
|
||||
{
|
||||
var cell = cells.Dequeue();
|
||||
|
||||
foreach (var paragraph in cell.Elements<Paragraph>())
|
||||
{
|
||||
yield return paragraph;
|
||||
}
|
||||
|
||||
// Ищем вложенные таблицы в ячейке
|
||||
foreach (var nestedTable in cell.Elements<Table>())
|
||||
{
|
||||
foreach (var nestedPara in GetTableParagraphs(nestedTable))
|
||||
{
|
||||
yield return nestedPara;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет параграф в ячейке таблицы на новые параграфы
|
||||
/// </summary>
|
||||
private static void ReplaceParagraphsInTableCell(Paragraph oldParagraph, List<Paragraph> newParagraphs)
|
||||
{
|
||||
ParagraphReplacer.ReplaceParagraph(oldParagraph, newParagraphs);
|
||||
}
|
||||
}
|
||||
321
QWERTYkez.WordProcessor/WordProcessor.cs
Normal file
321
QWERTYkez.WordProcessor/WordProcessor.cs
Normal file
@@ -0,0 +1,321 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Статический класс для работы с документами Word через процессоры чтения/записи.
|
||||
/// </summary>
|
||||
public static class WordProcessor
|
||||
{
|
||||
#region Read Operations
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ только для чтения и выполнить действия.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Путь к исходному файлу .docx</param>
|
||||
/// <param name="read">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryRead(string sourcePath, Action<IWordReader> read)
|
||||
{
|
||||
return TryRead(new FileInfo(sourcePath), read);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ только для чтения и выполнить действия.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">Объект <see cref="FileInfo"/> исходного файла .docx</param>
|
||||
/// <param name="read">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryRead(FileInfo sourceFile, Action<IWordReader> read)
|
||||
{
|
||||
if (sourceFile is null || read is null)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine("[DEBUG] SourceFile or action is null");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
using var processor = WordReader.CreateInternal(sourceFile);
|
||||
if (processor is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
read(processor);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error in read action: {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Read Operations from Memory
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ из массива байт только для чтения и выполнить действия.
|
||||
/// </summary>
|
||||
/// <param name="data">Массив байт, содержащий документ .docx</param>
|
||||
/// <param name="read">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryRead(byte[] data, Action<IWordReader> read)
|
||||
=> TryRead(new ReadOnlyMemory<byte>(data), read);
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ из <see cref="ReadOnlyMemory{byte}"/> только для чтения и выполнить действия.
|
||||
/// </summary>
|
||||
/// <param name="data">Буфер с документом .docx</param>
|
||||
/// <param name="read">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryRead(ReadOnlyMemory<byte> data, Action<IWordReader> read)
|
||||
{
|
||||
if (data.IsEmpty || read is null)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine("[DEBUG] Data is empty or action is null");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
using var processor = WordReader.CreateFromData(data);
|
||||
if (processor is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
read(processor);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error in read action from memory: {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Write Operations
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ для записи и выполнить действия с последующей перезаписью исходного файла.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Путь к исходному файлу .docx</param>
|
||||
/// <param name="write">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryWrite(string sourcePath, Action<IWordWriter> write)
|
||||
{
|
||||
return TryWrite(sourcePath, sourcePath, write);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ для записи и выполнить действия с последующей перезаписью исходного файла.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">Объект <see cref="FileInfo"/> исходного файла .docx</param>
|
||||
/// <param name="write">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryWrite(FileInfo sourceFile, Action<IWordWriter> write)
|
||||
{
|
||||
return TryWrite(sourceFile, sourceFile.FullName, write);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ для записи, выполнить действия и сохранить результат по новому пути.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">Путь к исходному файлу .docx</param>
|
||||
/// <param name="destinationPath">Путь для сохранения результата (null - перезапись исходного файла)</param>
|
||||
/// <param name="write">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryWrite(string sourcePath, string? destinationPath, Action<IWordWriter> write)
|
||||
{
|
||||
return TryWrite(new FileInfo(sourcePath), destinationPath, write);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ для записи, выполнить действия и сохранить результат по новому пути.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">Объект <see cref="FileInfo"/> исходного файла .docx</param>
|
||||
/// <param name="destinationPath">Путь для сохранения результата (null - перезапись исходного файла)</param>
|
||||
/// <param name="write">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryWrite(FileInfo sourceFile, string? destinationPath, Action<IWordWriter> write)
|
||||
{
|
||||
if (sourceFile is null || write is null)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine("[DEBUG] SourceFile or action is null");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
using var processor = WordWriter.CreateInternal(sourceFile, destinationPath);
|
||||
if (processor is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
write(processor);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error in write action: {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Write Operations from Memory
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ из массива байт для записи, выполнить действия и сохранить результат по указанному пути.
|
||||
/// </summary>
|
||||
/// <param name="data">Массив байт, содержащий документ .docx</param>
|
||||
/// <param name="destinationPath">Путь для сохранения результата</param>
|
||||
/// <param name="write">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryWrite(byte[] data, string destinationPath, Action<IWordWriter> write)
|
||||
=> TryWrite(new ReadOnlyMemory<byte>(data), destinationPath, write);
|
||||
|
||||
/// <summary>
|
||||
/// Пытается открыть документ из <see cref="ReadOnlyMemory{byte}"/> для записи, выполнить действия и сохранить результат по указанному пути.
|
||||
/// </summary>
|
||||
/// <param name="data">Буфер с документом .docx</param>
|
||||
/// <param name="destinationPath">Путь для сохранения результата</param>
|
||||
/// <param name="write">Действия для выполнения над документом</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/></returns>
|
||||
public static bool TryWrite(ReadOnlyMemory<byte> data, string destinationPath, Action<IWordWriter> write)
|
||||
{
|
||||
if (data.IsEmpty || write is null)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine("[DEBUG] Data is empty or write is null");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
using var processor = WordWriter.CreateFromData(data, destinationPath);
|
||||
if (processor is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
write(processor);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error in write action from memory: {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Пытается создать новый документ Word, отредактировать его и вернуть результат в виде массива байт.
|
||||
/// </summary>
|
||||
/// <param name="result">Результирующий массив байт (если операция успешна).</param>
|
||||
/// <param name="write">Действия для заполнения документа.</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/>.</returns>
|
||||
public static bool TryCreate(out byte[] result, Action<IWordWriter> write)
|
||||
{
|
||||
result = null!;
|
||||
if (write is null) return false;
|
||||
|
||||
try
|
||||
{
|
||||
using var writer = WordWriter.CreateNew();
|
||||
write(writer);
|
||||
result = writer.GetDocumentBytes();
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается создать новый документ Word, отредактировать его и записать в указанный поток.
|
||||
/// </summary>
|
||||
/// <param name="outputStream">Поток, в который будет записан документ.</param>
|
||||
/// <param name="write">Действия для заполнения документа.</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/>.</returns>
|
||||
public static bool TryCreate(Stream outputStream, Action<IWordWriter> write)
|
||||
{
|
||||
if (write is null || outputStream is null) return false;
|
||||
|
||||
try
|
||||
{
|
||||
using var writer = WordWriter.CreateNew();
|
||||
write(writer);
|
||||
writer.SaveTo(outputStream);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается создать новый документ Word, отредактировать его и сохранить на диск.
|
||||
/// </summary>
|
||||
/// <param name="destinationPath">Путь для сохранения результата.</param>
|
||||
/// <param name="write">Действия для заполнения документа.</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/>.</returns>
|
||||
public static bool TryCreate(string destinationPath, Action<IWordWriter> write)
|
||||
{
|
||||
if (string.IsNullOrEmpty(destinationPath) || write is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
using var writer = WordWriter.CreateNew(destinationPath);
|
||||
write(writer);
|
||||
writer.Save();
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается создать новый документ Word, отредактировать его и прочитать результат в памяти.
|
||||
/// </summary>
|
||||
/// <param name="write">Действия для заполнения документа.</param>
|
||||
/// <param name="read">Действия для чтения полученного документа.</param>
|
||||
/// <returns><see langword="true"/> если операция выполнена успешно, иначе <see langword="false"/>.</returns>
|
||||
public static bool TryCreate(Action<IWordWriter> write, Action<IWordReader> read)
|
||||
{
|
||||
if (write is null || read is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
using var writer = WordWriter.CreateNew(); // без привязки к файлу
|
||||
write(writer);
|
||||
using var reader = writer.ToReader(); // преобразуем в read-only
|
||||
read(reader);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
285
QWERTYkez.WordProcessor/WordReader.cs
Normal file
285
QWERTYkez.WordProcessor/WordReader.cs
Normal file
@@ -0,0 +1,285 @@
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Предоставляет потокобезопасный процессор только для чтения документов Word (DOCX) формата.
|
||||
/// <para>Не поддерживает операции изменения документа.</para>
|
||||
/// </summary>
|
||||
internal class WordReader : IDisposable, IWordReader
|
||||
{
|
||||
protected MemoryStream _ms = null!;
|
||||
protected WordprocessingDocument _doc = null!;
|
||||
protected Body _body = null!;
|
||||
protected bool _disposed;
|
||||
protected readonly object _syncLock = new();
|
||||
protected string? _originalSourcePath;
|
||||
|
||||
public Body Body => _body;
|
||||
|
||||
internal WordReader() { }
|
||||
|
||||
#region Factory Methods
|
||||
|
||||
internal static WordReader? CreateInternal(FileInfo sourceFile)
|
||||
{
|
||||
if (sourceFile is null || !sourceFile.Exists)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Source file is null or does not exist: {sourceFile?.FullName}");
|
||||
#endif
|
||||
return null;
|
||||
}
|
||||
|
||||
MemoryStream? ms = null;
|
||||
WordprocessingDocument? doc = null;
|
||||
|
||||
try
|
||||
{
|
||||
ms = new MemoryStream();
|
||||
using (var file = new FileStream(sourceFile.FullName,
|
||||
FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
|
||||
{
|
||||
file.CopyTo(ms);
|
||||
}
|
||||
ms.Position = 0;
|
||||
|
||||
doc = WordprocessingDocument.Open(ms, isEditable: false,
|
||||
new OpenSettings { AutoSave = false });
|
||||
|
||||
if (doc.MainDocumentPart?.Document?.Body is not { } body)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine("[DEBUG] Document body is null or empty");
|
||||
#endif
|
||||
doc.Dispose();
|
||||
ms.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
var processor = new WordReader
|
||||
{
|
||||
_ms = ms,
|
||||
_doc = doc,
|
||||
_body = body,
|
||||
_originalSourcePath = sourceFile.FullName,
|
||||
FilePath = sourceFile.FullName
|
||||
};
|
||||
|
||||
return processor;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error creating read-only processor: {ex.GetType().Name}: {ex.Message}");
|
||||
#endif
|
||||
doc?.Dispose();
|
||||
ms?.Dispose();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal static WordReader? CreateFromData(ReadOnlyMemory<byte> data)
|
||||
{
|
||||
if (data.IsEmpty)
|
||||
return null;
|
||||
|
||||
var ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
ms.Write(data.ToArray(), 0, data.Length);
|
||||
ms.Position = 0;
|
||||
|
||||
var doc = WordprocessingDocument.Open(ms, false, new OpenSettings { AutoSave = false });
|
||||
if (doc.MainDocumentPart?.Document?.Body is not { } body)
|
||||
{
|
||||
doc.Dispose();
|
||||
ms.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
return new WordReader
|
||||
{
|
||||
_ms = ms,
|
||||
_doc = doc,
|
||||
_body = body,
|
||||
FilePath = null // из памяти – нет файла
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
ms?.Dispose();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Writers
|
||||
|
||||
public bool TryWrite(string destinationPath, Action<IWordWriter> action)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(destinationPath))
|
||||
throw new ArgumentException("Destination path cannot be null or empty", nameof(destinationPath));
|
||||
if (action is null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
|
||||
// Копируем данные из текущего потока
|
||||
byte[] data;
|
||||
lock (_syncLock)
|
||||
{
|
||||
_ms.Position = 0;
|
||||
data = _ms.ToArray();
|
||||
}
|
||||
|
||||
using var writable = WordWriter.CreateFromData(new ReadOnlyMemory<byte>(data), destinationPath);
|
||||
if (writable is null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
action(writable);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error in TryWrite action: {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryWrite(Action<IWordWriter> write, Action<IWordReader> read)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (write is null) throw new ArgumentNullException(nameof(write));
|
||||
if (read is null) throw new ArgumentNullException(nameof(read));
|
||||
|
||||
// Копируем текущие данные
|
||||
byte[] data;
|
||||
lock (_syncLock)
|
||||
{
|
||||
_ms.Position = 0;
|
||||
data = _ms.ToArray();
|
||||
}
|
||||
|
||||
WordWriter? writable = null;
|
||||
WordReader? resultReader = null;
|
||||
try
|
||||
{
|
||||
// Создаём редактируемую копию (без привязки к файлу)
|
||||
writable = WordWriter.CreateFromData(data);
|
||||
if (writable is null)
|
||||
return false;
|
||||
|
||||
// Применяем изменения
|
||||
write(writable);
|
||||
|
||||
// Сохраняем изменения в поток и создаём read-only процессор
|
||||
resultReader = writable.ToReader();
|
||||
|
||||
if (resultReader is null)
|
||||
return false;
|
||||
|
||||
// Работаем с изменённой копией
|
||||
read(resultReader);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Error in TryWrite(write, read): {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Гарантированно освобождаем созданные процессоры
|
||||
resultReader?.Dispose();
|
||||
writable?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>
|
||||
/// Получает путь к исходному файлу.
|
||||
/// </summary>
|
||||
public string? FilePath { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение, указывающее, находится ли процессор в допустимом состоянии для операций.
|
||||
/// </summary>
|
||||
public bool IsValid => !_disposed && _doc is not null && _body is not null && _ms is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Получает текущий размер документа в байтах.
|
||||
/// </summary>
|
||||
public long DocumentSize => _ms.Length;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Read Operations
|
||||
|
||||
/// <summary>
|
||||
/// Находит все уникальные плейсхолдеры в формате $...$ в документе.
|
||||
/// <para>Ищет только внутри параграфов. Игнорирует вхождения, которые пересекают границы параграфов.</para>
|
||||
/// </summary>
|
||||
/// <param name="comparisonType">Способ сравнения строк при поиске (по умолчанию: без учета регистра)</param>
|
||||
/// <returns>Коллекция уникальных найденных плейсхолдеров</returns>
|
||||
public ISet<string> FindPlaceholders()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
return PlaceholderFinder.FindInDocument(_doc, _body);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dispose Pattern
|
||||
|
||||
protected void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException(GetType().Name);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_doc.Dispose();
|
||||
_ms.Dispose();
|
||||
}
|
||||
|
||||
_doc = null!;
|
||||
_body = null!;
|
||||
_ms = null!;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
~WordReader()
|
||||
{
|
||||
Dispose(disposing: false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
626
QWERTYkez.WordProcessor/WordWriter.cs
Normal file
626
QWERTYkez.WordProcessor/WordWriter.cs
Normal file
@@ -0,0 +1,626 @@
|
||||
using QWERTYkez.WordProcessor.Builders;
|
||||
|
||||
namespace QWERTYkez.WordProcessor;
|
||||
|
||||
/// <summary>
|
||||
/// Предоставляет потокобезопасный процессор для чтения и записи документов Word (DOCX) формата.
|
||||
/// <para>Наследует от <see cref="WordReader"/> и добавляет операции изменения документа.</para>
|
||||
/// </summary>
|
||||
internal sealed class WordWriter : WordReader, IWordWriter
|
||||
{
|
||||
private bool _isModified = false;
|
||||
|
||||
internal WordWriter() { }
|
||||
|
||||
#region Factory Methods
|
||||
|
||||
internal static WordWriter? CreateFromData(ReadOnlyMemory<byte> data, string destinationPath)
|
||||
{
|
||||
if (data.IsEmpty || string.IsNullOrEmpty(destinationPath))
|
||||
return null;
|
||||
|
||||
var ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
// Копируем данные в MemoryStream
|
||||
ms.Write(data.ToArray(), 0, data.Length);
|
||||
ms.Position = 0;
|
||||
|
||||
var doc = WordprocessingDocument.Open(ms, true, new OpenSettings { AutoSave = false });
|
||||
if (doc.MainDocumentPart?.Document?.Body is { } body)
|
||||
{
|
||||
return new WordWriter
|
||||
{
|
||||
_ms = ms,
|
||||
_doc = doc,
|
||||
_body = body,
|
||||
FilePath = destinationPath,
|
||||
_originalSourcePath = null // нет исходного файла
|
||||
};
|
||||
}
|
||||
|
||||
doc.Dispose();
|
||||
}
|
||||
catch { }
|
||||
|
||||
ms?.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static new WordWriter? CreateFromData(ReadOnlyMemory<byte> data)
|
||||
{
|
||||
if (data.IsEmpty)
|
||||
return null;
|
||||
|
||||
var ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
ms.Write(data.ToArray(), 0, data.Length);
|
||||
ms.Position = 0;
|
||||
|
||||
var doc = WordprocessingDocument.Open(ms, true, new OpenSettings { AutoSave = false });
|
||||
if (doc.MainDocumentPart?.Document?.Body is { } body)
|
||||
{
|
||||
return new WordWriter
|
||||
{
|
||||
_ms = ms,
|
||||
_doc = doc,
|
||||
_body = body,
|
||||
FilePath = null, // нет привязки к файлу
|
||||
_originalSourcePath = null
|
||||
};
|
||||
}
|
||||
|
||||
doc.Dispose();
|
||||
}
|
||||
catch { }
|
||||
|
||||
ms.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static WordWriter? CreateInternal(FileInfo sourceFile, string? destinationPath = null!)
|
||||
{
|
||||
if (sourceFile is null || !sourceFile.Exists) return null;
|
||||
|
||||
var ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
using (var file = new FileStream(sourceFile.FullName,
|
||||
FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
|
||||
{
|
||||
file.CopyTo(ms);
|
||||
}
|
||||
ms.Position = 0;
|
||||
|
||||
var doc = WordprocessingDocument.Open(ms, isEditable: true,
|
||||
new OpenSettings { AutoSave = false });
|
||||
|
||||
if (doc.MainDocumentPart?.Document?.Body is { } body)
|
||||
{
|
||||
var processor = new WordWriter
|
||||
{
|
||||
_ms = ms,
|
||||
_doc = doc,
|
||||
_body = body,
|
||||
_originalSourcePath = sourceFile.FullName,
|
||||
FilePath = destinationPath ?? sourceFile.FullName
|
||||
};
|
||||
|
||||
return processor;
|
||||
}
|
||||
|
||||
doc?.Dispose();
|
||||
}
|
||||
catch { }
|
||||
|
||||
ms?.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создаёт новый пустой документ Word.
|
||||
/// </summary>
|
||||
/// <param name="destinationPath">Путь, по которому будет сохранён документ (необязательный).</param>
|
||||
/// <returns>Экземпляр <see cref="WordWriter"/> для редактирования нового документа.</returns>
|
||||
internal static WordWriter CreateNew(string? destinationPath = null)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
// Создаём документ, НЕ используем using
|
||||
var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
|
||||
var mainPart = doc.AddMainDocumentPart();
|
||||
mainPart.Document = new Document();
|
||||
var body = new Body();
|
||||
mainPart.Document.AppendChild(body);
|
||||
|
||||
var writer = new WordWriter
|
||||
{
|
||||
_ms = ms,
|
||||
_doc = doc,
|
||||
_body = body,
|
||||
FilePath = destinationPath,
|
||||
_originalSourcePath = null
|
||||
};
|
||||
return writer;
|
||||
}
|
||||
catch
|
||||
{
|
||||
ms.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение, указывающее, будет ли документ сохранен с перезаписью исходного файла.
|
||||
/// </summary>
|
||||
public bool WillOverwriteSource => FilePath == _originalSourcePath;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Replace text
|
||||
|
||||
public void ReplaceString(string oldValue, params string[] newValues) => ReplaceString(oldValue, (IEnumerable<string>)newValues);
|
||||
public void ReplaceString(string oldValue, IEnumerable<string> newValues)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(oldValue))
|
||||
throw new ArgumentException("Old value cannot be null or empty", nameof(oldValue));
|
||||
|
||||
if (newValues is null) return;
|
||||
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] [WordProcessor.Replace] START: '{oldValue}' -> [{string.Join(", ", newValues)}] (comparison: {StringComparison.OrdinalIgnoreCase})");
|
||||
#endif
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// 1. Основной текст
|
||||
_body.Replace(oldValue, newValues, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
TableTextProcessor.ReplaceInTables(_body, oldValue, newValues, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 3. Колонтитулы
|
||||
HeaderFooterProcessor.ReplaceInHeadersFooters(_doc, oldValue, newValues, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void ReplaceString(IDictionary<string, string> replacements) =>
|
||||
/* */ReplaceString((IEnumerable<KeyValuePair<string, string>>)replacements);
|
||||
public void ReplaceString(IEnumerable<KeyValuePair<string, string>> replacements)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (replacements is null) return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// 1. Основной текст
|
||||
_body.Replace(replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
foreach (var kvp in replacements)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key))
|
||||
{
|
||||
TableTextProcessor.ReplaceInTables(_body, kvp.Key, [kvp.Value ?? string.Empty], StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
HeaderFooterProcessor.ReplaceInHeadersFooters(_doc, replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void ReplaceString(IDictionary<string, IEnumerable<string>> replacements) =>
|
||||
/* */ReplaceString((IEnumerable<KeyValuePair<string, IEnumerable<string>>>)replacements);
|
||||
public void ReplaceString(IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (replacements is null) return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// 1. Основной текст
|
||||
_body.Replace(replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
TableTextProcessor.ReplaceInTables(_body, replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 3. Колонтитулы
|
||||
HeaderFooterProcessor.ReplaceInHeadersFooters(_doc, replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Replace ReplaceItem
|
||||
public void ReplaceItem(string oldValue, params ReplaceItem[] newValues) => ReplaceItem(oldValue, (IEnumerable<ReplaceItem>)newValues);
|
||||
public void ReplaceItem(string oldValue, IEnumerable<ReplaceItem> newValues)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(oldValue))
|
||||
throw new ArgumentException("Old value cannot be null or empty", nameof(oldValue));
|
||||
|
||||
if (newValues is null) return;
|
||||
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] [WordProcessor.Replace] START: '{oldValue}' -> [{string.Join(", ", newValues)}] (comparison: {StringComparison.OrdinalIgnoreCase})");
|
||||
#endif
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// 1. Основной текст
|
||||
_body.Replace(oldValue, newValues, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var texts = newValues.Select(val => val.Text).ToArray();
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
TableTextProcessor.ReplaceInTables(_body, oldValue, texts, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 3. Колонтитулы
|
||||
HeaderFooterProcessor.ReplaceInHeadersFooters(_doc, oldValue, texts, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void ReplaceItem(IDictionary<string, ReplaceItem> replacements) =>
|
||||
/* */ReplaceItem((IEnumerable<KeyValuePair<string, ReplaceItem>>)replacements);
|
||||
public void ReplaceItem(IEnumerable<KeyValuePair<string, ReplaceItem>> replacements)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (replacements is null) return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// 1. Основной текст
|
||||
_body.Replace(replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
|
||||
var texts = replacements.ToDictionary(val => val.Key, val => val.Value.Text);
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
foreach (var kvp in texts)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(kvp.Key))
|
||||
{
|
||||
TableTextProcessor.ReplaceInTables(_body, kvp.Key, kvp.Value, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Колонтитулы
|
||||
HeaderFooterProcessor.ReplaceInHeadersFooters(_doc, texts, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void ReplaceItem(IDictionary<string, IEnumerable<ReplaceItem>> replacements) =>
|
||||
/* */ReplaceItem((IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>)replacements);
|
||||
public void ReplaceItem(IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (replacements is null) return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// 1. Основной текст
|
||||
_body.Replace(replacements, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
|
||||
var texts = replacements.ToDictionary(val => val.Key, val => val.Value.Select(val => val.Text));
|
||||
|
||||
// 2. Таблицы в основном тексте
|
||||
TableTextProcessor.ReplaceInTables(_body, texts, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 3. Колонтитулы
|
||||
HeaderFooterProcessor.ReplaceInHeadersFooters(_doc, texts, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Добавляет новый параграф с указанным текстом в конец документа.
|
||||
/// </summary>
|
||||
public void AddParagraph(string text, bool preserveFormatting = true)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (_body is null)
|
||||
return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
var paragraph = new Paragraph();
|
||||
var run = new Run();
|
||||
|
||||
if (preserveFormatting && _body.Elements<Paragraph>().FirstOrDefault() is { } firstPara)
|
||||
{
|
||||
if (firstPara.ParagraphProperties is not null)
|
||||
{
|
||||
paragraph.ParagraphProperties = firstPara.ParagraphProperties.CloneNode(true) as ParagraphProperties;
|
||||
}
|
||||
|
||||
if (firstPara.Elements<Run>().FirstOrDefault()?.RunProperties is not null)
|
||||
{
|
||||
run.RunProperties = firstPara.Elements<Run>().First().RunProperties?.CloneNode(true) as RunProperties;
|
||||
}
|
||||
}
|
||||
|
||||
string processedText = text.Replace(' ', '\u00A0');
|
||||
run.AppendChild(new Text(processedText));
|
||||
paragraph.AppendChild(run);
|
||||
_body.AppendChild(paragraph);
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
#region Replace to table
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет параграф, содержащий указанный текст, на таблицу, созданную с помощью TableBuilder
|
||||
/// </summary>
|
||||
/// <param name="oldValue">Текст для поиска в параграфах</param>
|
||||
/// <param name="buildTable">Действие для настройки таблицы через TableBuilder</param>
|
||||
public void ReplaceToTable(string oldValue, Action<ITable> buildTable)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(oldValue))
|
||||
throw new ArgumentException("Old value cannot be null or empty", nameof(oldValue));
|
||||
|
||||
if (buildTable is null) return;
|
||||
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] [WordProcessor.ReplaceToTable] Looking for '{oldValue}' to replace with custom table");
|
||||
#endif
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// Используем метод расширения для Body с TableBuilder
|
||||
ReplaceToTableExt.ReplaceParagraphsContainingTextToTable(_body, oldValue, buildTable);
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Replace to text
|
||||
|
||||
/// <summary>
|
||||
/// Заменяет параграф, содержащий указанный текст, на таблицу, созданную с помощью TextBuilder
|
||||
/// </summary>
|
||||
/// <param name="oldValue">Текст для поиска в параграфах</param>
|
||||
/// <param name="buildText">Действие для настройки таблицы через TextBuilder</param>
|
||||
public void ReplaceToText(string oldValue, Action<IText> buildText)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(oldValue))
|
||||
throw new ArgumentException("Old value cannot be null or empty", nameof(oldValue));
|
||||
|
||||
if (buildText is null) return;
|
||||
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] [WordProcessor.ReplaceToText] Looking for '{oldValue}' to replace with custom text");
|
||||
#endif
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
// Используем метод расширения для Body с TextBuilder
|
||||
ReplaceToTextExt.ReplaceParagraphsContainingTextToText(_body, oldValue, buildText);
|
||||
_isModified = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Save Operations
|
||||
|
||||
/// <summary>
|
||||
/// Сохраняет документ в файл, указанный при создании процессора.
|
||||
/// </summary>
|
||||
public void Save()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(FilePath))
|
||||
throw new InvalidOperationException("Cannot save - no file path specified");
|
||||
|
||||
SaveTo(FilePath!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохраняет документ в указанный файл.
|
||||
/// </summary>
|
||||
public void SaveTo(string path)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(path))
|
||||
throw new ArgumentException("Path cannot be null or empty", nameof(path));
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_ms is not null)
|
||||
{
|
||||
_doc.Save();
|
||||
_ms.Position = 0;
|
||||
|
||||
using var fileStream = new FileStream(
|
||||
path,
|
||||
FileMode.Create,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
bufferSize: 65536);
|
||||
|
||||
_ms.CopyTo(fileStream);
|
||||
_isModified = false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new IOException($"Failed to save document to '{path}'", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
internal byte[] GetDocumentBytes()
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
_doc.Save();
|
||||
_ms.Position = 0;
|
||||
return _ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveTo(Stream outputStream)
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
_doc.Save();
|
||||
_ms.Position = 0;
|
||||
_ms.CopyTo(outputStream);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пытается сохранить документ в указанный файл.
|
||||
/// </summary>
|
||||
public bool TrySaveTo(string path, out Exception? error)
|
||||
{
|
||||
error = null;
|
||||
|
||||
if (!IsValid || string.IsNullOrEmpty(path))
|
||||
{
|
||||
error = new InvalidOperationException("Processor is not valid or path is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
SaveTo(path);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex;
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Failed to save to '{path}': {ex.Message}");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Асинхронно сохраняет документ в указанный файл.
|
||||
/// </summary>
|
||||
public async Task SaveToAsync(string path, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (string.IsNullOrEmpty(path))
|
||||
throw new ArgumentException("Path cannot be null or empty", nameof(path));
|
||||
|
||||
if (_ms is null)
|
||||
throw new InvalidOperationException("Memory stream is not available");
|
||||
|
||||
byte[] buffer;
|
||||
lock (_syncLock)
|
||||
{
|
||||
_doc.Save();
|
||||
_ms.Position = 0;
|
||||
buffer = _ms.ToArray();
|
||||
}
|
||||
|
||||
using var fileStream = new FileStream(
|
||||
path,
|
||||
FileMode.Create,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
bufferSize: 81920,
|
||||
useAsync: true);
|
||||
|
||||
await fileStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary> Создаёт read-only процессор из текущего документа. </summary>
|
||||
internal WordReader ToReader()
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
_doc.Save();
|
||||
_ms.Position = 0;
|
||||
var data = _ms.ToArray();
|
||||
return WordReader.CreateFromData(data) ?? throw new InvalidOperationException("Failed to create reader");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dispose Pattern
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
if (_isModified && !string.IsNullOrEmpty(FilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
_doc.Save();
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
|
||||
|
||||
_ms.Position = 0;
|
||||
using var fileStream = new FileStream(
|
||||
FilePath!,
|
||||
FileMode.Create,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
bufferSize: 81920);
|
||||
|
||||
_ms.CopyTo(fileStream);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
#if DEBUG
|
||||
Debug.WriteLine($"[DEBUG] Auto-save failed during Dispose: {ex.Message}");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
11
QWERTYkez.WordProcessor/globals.cs
Normal file
11
QWERTYkez.WordProcessor/globals.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
global using DocumentFormat.OpenXml;
|
||||
global using DocumentFormat.OpenXml.Packaging;
|
||||
global using DocumentFormat.OpenXml.Wordprocessing;
|
||||
global using System;
|
||||
global using System.Collections.Generic;
|
||||
global using System.Diagnostics;
|
||||
global using System.IO;
|
||||
global using System.Linq;
|
||||
global using System.Text;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
Reference in New Issue
Block a user