PIbd-32_Turner_I.A._COP_10/COP/VisualCompLib/Components/WordText.cs

124 lines
2.8 KiB
C#
Raw Normal View History

2023-10-11 17:32:36 +04:00
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System.ComponentModel;
using VisualCompLib.Components.SupportClasses;
namespace VisualCompLib.Components
{
public partial class WordText : Component
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
public WordText()
{
InitializeComponent();
}
public WordText(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateWordText(LargeText largeText)
{
if (string.IsNullOrEmpty(largeText.FilePath) || string.IsNullOrEmpty(largeText.DocumentTitle) || largeText.TextData.Length == 0)
{
return;
}
_wordDocument = WordprocessingDocument.Create(largeText.FilePath, WordprocessingDocumentType.Document);
//вытаскиваем главную часть из вордовского документа
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
//генерируем тело основной части документа
_docBody = mainPart.Document.AppendChild(new Body());
_wordDocument.Close();
AddText(largeText);
}
private void AddText(LargeText largeText)
{
using (var document = WordprocessingDocument.Open(largeText.FilePath, true))
{
var doc = document.MainDocumentPart.Document;
#region Создание заголовка
ParagraphProperties paragraphProperties = new();
paragraphProperties.AppendChild(new Justification
{
Val = JustificationValues.Center
});
paragraphProperties.AppendChild(new Indentation());
Paragraph header = new();
header.AppendChild(paragraphProperties);
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize
{
Val = "48"
});
properties.AppendChild(new Bold());
docRun.AppendChild(properties);
docRun.AppendChild(new Text(largeText.DocumentTitle));
header.AppendChild(docRun);
doc.Body.Append(header);
#endregion
#region Создание текста
for (int i = 0; i < largeText.TextData.Length; i++)
{
ParagraphProperties paragraphProperties2 = new();
paragraphProperties2.AppendChild(new Justification
{
Val = JustificationValues.Both
});
paragraphProperties2.AppendChild(new Indentation());
Paragraph text = new();
text.AppendChild(paragraphProperties2);
var docRun2 = new Run();
var properties2 = new RunProperties();
properties2.AppendChild(new FontSize
{
Val = "24"
});
docRun2.AppendChild(properties2);
docRun2.AppendChild(new Text(largeText.TextData[i]));
text.AppendChild(docRun2);
doc.Body.Append(text);
}
#endregion
doc.Save();
}
}
}
}