Сравнить документы

Сравнение документов - это процесс, который идентифицирует изменения между двумя документами и содержит изменения в виде изменений. Этот процесс сравнивает любые два документа, включая версии одного конкретного документа, затем изменения между обоими документами будут показаны как изменения в первом документе.

Метод сравнения достигается путем сравнения слов на уровне символов или на уровне слов. Если слово содержит изменение хотя бы одного символа, то в результате различие будет отображаться как изменение всего слова, а не символа. Этот процесс сравнения является обычной задачей в юридической и финансовой отраслях.

Вместо ручного поиска различий между документами или между различными их версиями вы можете использовать Aspose.Words для сравнения документов и получения изменений контента в форматировании, заголовке / футере, таблицах и многом другом.

В этой статье объясняется, как сравнивать документы и как указывать расширенные свойства сравнения.

Ограничения и поддерживаемые форматы файлов

Сравнение документов – очень сложная особенность. Существуют различные части комбинации контента, которые необходимо проанализировать, чтобы распознать все различия. Причина такой сложности заключается в том, что Aspose.Words стремится получить те же результаты сравнения, что и Microsoft Word алгоритм сравнения.

Общим ограничением для двух сравниваемых документов является то, что они не должны иметь пересмотра, прежде чем называть метод сравнения, поскольку это ограничение существует. Microsoft Word.

Сравните два документа

Когда вы сравниваете документы, отличия последнего документа от первого появляются в виде изменений к первому. При изменении документа каждое редактирование будет иметь свой собственный пересмотр после запуска метода сравнения.

Aspose.Words позволяет выявить отличия документов с помощью Compare метод – это аналогично Microsoft Word Особенность сравнения документов. Он позволяет проверять документы или версии документов, чтобы найти различия и изменения, включая изменения форматирования, такие как изменения шрифта, изменения интервала, добавление слов и абзацев.

В результате сравнения документы могут быть определены как равные или не равные. Термин “равные” документы означает, что метод сравнения не может представлять изменения в качестве пересмотров. Это означает, что и текст документа, и форматирование текста одинаковы. Между документами могут быть и другие различия. Например, Microsoft Word Поддерживает только изменения формата для стилей, и вы не можете представлять вставку / удаление стиля. Таким образом, документы могут иметь различный набор стилей, и Compare Метод до сих пор не производит никаких изменений.

Следующий пример кода показывает, как проверить, равны ли два документа:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
// DocA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now);
if (docA.Revisions.Count == 0)
Console.WriteLine("Documents are equal");
else
Console.WriteLine("Documents are not equal");

Следующий пример кода показывает, как просто применить Compare Способ до двух документов:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The source document doc1.
Document doc1 = new Document();
DocumentBuilder builder = new DocumentBuilder(doc1);
builder.Writeln("This is the original document.");
// The target document doc2.
Document doc2 = new Document();
builder = new DocumentBuilder(doc2);
builder.Writeln("This is the edited document.");
// If either document has a revision, an exception will be thrown.
if (doc1.Revisions.Count == 0 && doc2.Revisions.Count == 0)
doc1.Compare(doc2, "authorName", DateTime.Now);
// If doc1 and doc2 are different, doc1 now has some revisions after the comparison, which can now be viewed and processed.
Assert.AreEqual(2, doc1.Revisions.Count);
foreach (Revision r in doc1.Revisions)
{
Console.WriteLine($"Revision type: {r.RevisionType}, on a node of type \"{r.ParentNode.NodeType}\"");
Console.WriteLine($"\tChanged text: \"{r.ParentNode.GetText()}\"");
}
// All the revisions in doc1 are differences between doc1 and doc2, so accepting them on doc1 transforms doc1 into doc2.
doc1.Revisions.AcceptAll();
// doc1, when saved, now resembles doc2.
doc1.Save(dataDir + "Document.Compare.docx");
doc1 = new Document(dataDir + "Document.Compare.docx");
Assert.AreEqual(0, doc1.Revisions.Count);
Assert.AreEqual(doc2.GetText().Trim(), doc1.GetText().Trim());

Расширенные варианты сравнения

Существует множество различных свойств CompareOptions Класс, который вы можете применить, если хотите сравнить документы.

Например, Aspose.Words позволяет игнорировать изменения, внесенные в ходе операции сравнения для определенных типов объектов в исходном документе. Вы можете выбрать подходящее свойство для типа объекта, например: IgnoreHeadersAndFooters, IgnoreFormatting, IgnoreComments, и других, устанавливая их “true”.

Кроме того, Aspose.Words обеспечивает Granularity свойство, с помощью которого можно указать, отслеживать изменения по характеру или по слову.

Другим общим свойством является выбор, в котором документ показывает изменения сравнения. Например, “Сравнить документы диалогового окна” в Microsoft Word Имеется опция “Показать изменения” - это также влияет на результаты сравнения. Aspose.Words обеспечивает Target собственности, которая служит этой цели.

Следующий пример кода показывает, как установить расширенные свойства сравнения:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create the original document.
Document docOriginal = new Document();
DocumentBuilder builder = new DocumentBuilder(docOriginal);
// Insert paragraph text with an endnote.
builder.Writeln("Hello world! This is the first paragraph.");
builder.InsertFootnote(FootnoteType.Endnote, "Original endnote text.");
// Insert a table.
builder.StartTable();
builder.InsertCell();
builder.Write("Original cell 1 text");
builder.InsertCell();
builder.Write("Original cell 2 text");
builder.EndTable();
// Insert a textbox.
Shape textBox = builder.InsertShape(ShapeType.TextBox, 150, 20);
builder.MoveTo(textBox.FirstParagraph);
builder.Write("Original textbox contents");
// Insert a DATE field.
builder.MoveTo(docOriginal.FirstSection.Body.AppendParagraph(""));
builder.InsertField(" DATE ");
// Insert a comment.
Comment newComment = new Comment(docOriginal, "John Doe", "J.D.", DateTime.Now);
newComment.SetText("Original comment.");
builder.CurrentParagraph.AppendChild(newComment);
// Insert a header.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Original header contents.");
// Create a clone of our document, which we will edit and later compare to the original.
Document docEdited = (Document)docOriginal.Clone(true);
Paragraph firstParagraph = docEdited.FirstSection.Body.FirstParagraph;
// Change the formatting of the first paragraph, change casing of original characters and add text.
firstParagraph.Runs[0].Text = "hello world! this is the first paragraph, after editing.";
firstParagraph.ParagraphFormat.Style = docEdited.Styles[StyleIdentifier.Heading1];
// Edit the footnote.
Footnote footnote = (Footnote)docEdited.GetChild(NodeType.Footnote, 0, true);
footnote.FirstParagraph.Runs[1].Text = "Edited endnote text.";
// Edit the table.
Table table = (Table)docEdited.GetChild(NodeType.Table, 0, true);
table.FirstRow.Cells[1].FirstParagraph.Runs[0].Text = "Edited Cell 2 contents";
// Edit the textbox.
textBox = (Shape)docEdited.GetChild(NodeType.Shape, 0, true);
textBox.FirstParagraph.Runs[0].Text = "Edited textbox contents";
// Edit the DATE field.
FieldDate fieldDate = (FieldDate)docEdited.Range.Fields[0];
fieldDate.UseLunarCalendar = true;
// Edit the comment.
Comment comment = (Comment)docEdited.GetChild(NodeType.Comment, 0, true);
comment.FirstParagraph.Runs[0].Text = "Edited comment.";
// Edit the header.
docEdited.FirstSection.HeadersFooters[HeaderFooterType.HeaderPrimary].FirstParagraph.Runs[0].Text = "Edited header contents.";
// Apply different comparing options.
CompareOptions compareOptions = new CompareOptions();
compareOptions.IgnoreFormatting = false;
compareOptions.IgnoreCaseChanges = false;
compareOptions.IgnoreComments = false;
compareOptions.IgnoreTables = false;
compareOptions.IgnoreFields = false;
compareOptions.IgnoreFootnotes = false;
compareOptions.IgnoreTextboxes = false;
compareOptions.IgnoreHeadersAndFooters = false;
compareOptions.Target = ComparisonTargetType.New;
// compare both documents.
docOriginal.Compare(docEdited, "John Doe", DateTime.Now, compareOptions);
docOriginal.Save(dataDir + "Document.CompareOptions.docx");
docOriginal = new Document(dataDir + "Document.CompareOptions.docx");
// If you set compareOptions to ignore certain types of changes,
// then revisions done on those types of nodes will not appear in the output document.
// You can tell what kind of node a revision was done on by looking at the NodeType of the revision's parent nodes.
Assert.AreNotEqual(compareOptions.IgnoreFormatting, docOriginal.Revisions.Any(rev => rev.RevisionType == RevisionType.FormatChange));
Assert.AreNotEqual(compareOptions.IgnoreCaseChanges, docOriginal.Revisions.Any(s => s.ParentNode.GetText().Contains("hello")));
Assert.AreNotEqual(compareOptions.IgnoreComments, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Comment)));
Assert.AreNotEqual(compareOptions.IgnoreTables, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Table)));
Assert.AreNotEqual(compareOptions.IgnoreFields, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.FieldStart)));
Assert.AreNotEqual(compareOptions.IgnoreFootnotes, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Footnote)));
Assert.AreNotEqual(compareOptions.IgnoreTextboxes, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Shape)));
Assert.AreNotEqual(compareOptions.IgnoreHeadersAndFooters, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.HeaderFooter)));