81 lines
1.8 KiB
C#
81 lines
1.8 KiB
C#
using Microsoft.Office.Interop.Word;
|
||
using System.ComponentModel;
|
||
using WinFormsLibrary.NonVisualComponents.Helpers;
|
||
using Application = Microsoft.Office.Interop.Word.Application;
|
||
|
||
|
||
namespace WinFormsLibrary
|
||
{
|
||
public partial class WordText : Component
|
||
{
|
||
private Application? _wordApp;
|
||
private Document? _document;
|
||
|
||
public WordText()
|
||
{
|
||
InitializeComponent();
|
||
}
|
||
|
||
public WordText(IContainer container)
|
||
{
|
||
container.Add(this);
|
||
|
||
InitializeComponent();
|
||
}
|
||
public void CreateWordText(LongWordInfo textInfo)
|
||
{
|
||
if ((string.IsNullOrEmpty(textInfo.Path)) || (string.IsNullOrEmpty(textInfo.Title) || !CheckData(textInfo.Paragraphs)))
|
||
{
|
||
throw new ArgumentException("Не все данные заполнены");
|
||
}
|
||
_wordApp = new Application();
|
||
_document = _wordApp.Documents.Add();
|
||
|
||
try
|
||
{
|
||
AddText(textInfo);
|
||
_document.SaveAs2(textInfo.Path);
|
||
}
|
||
finally
|
||
{
|
||
_document.Close();
|
||
_wordApp.Quit();
|
||
}
|
||
}
|
||
private void AddText(LongWordInfo textInfo)
|
||
{
|
||
if (_document == null)
|
||
{
|
||
return;
|
||
}
|
||
AddParagraph(textInfo.Title, fontSize: 20, isBold: true);
|
||
foreach(var paragraph in textInfo.Paragraphs)
|
||
{
|
||
AddParagraph(paragraph, fontSize: 14, isBold: false);
|
||
}
|
||
}
|
||
private void AddParagraph(string text, int fontSize, bool isBold)
|
||
{
|
||
if (_document== null)
|
||
{
|
||
return;
|
||
}
|
||
var paragraph = _document.Content.Paragraphs.Add();
|
||
var range = paragraph.Range;
|
||
|
||
range.Text = text;
|
||
range.Font.Size = fontSize;
|
||
range.Font.Name = "Times New Roman";
|
||
range.Font.Bold = isBold ? 1 : 0;
|
||
|
||
paragraph.Alignment = WdParagraphAlignment.wdAlignParagraphJustify;
|
||
|
||
range.InsertParagraphAfter();
|
||
}
|
||
public bool CheckData(string[] data)
|
||
{
|
||
return data != null && data.Any() && data.All(dt => !String.IsNullOrEmpty(dt));
|
||
}
|
||
}
|
||
}
|