Включить и добавить документы
Иногда требуется объединить несколько документов в один. Вы можете сделать это вручную или использовать Aspose.Words Вставить или добавить функцию.
Операция вставки позволяет вставить содержимое ранее созданных документов в новый или существующий.
В свою очередь, функция приложения позволяет добавлять документ только в конце другого документа.
Эта статья объясняет, как вставить или добавить документ к другому по-разному и описывает общие свойства, которые вы можете применить при вставке или добавлении документов.
Включить документ
Как упоминалось выше, в Aspose.Words документ представлен как дерево узлов, а операция вставки одного документа в другой заключается в копировании узлов от первого дерева документов ко второму.
Вы можете вставлять документы в различных местах по-разному. Например, вы можете вставить документ через операцию замены, поле слияния во время операции слияния или через закладку.
Вы также можете использовать InsertDocument или InsertDocumentInline метод, аналогичный вставке документа в Microsoft Word, Вставить весь документ в текущую позицию курсора без предварительного импорта.
Следующий пример кода показывает, как вставить документ, используя InsertDocument метод:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document srcDoc = new Document(MyDir + "Document source.docx"); | |
Document dstDoc = new Document(MyDir + "Northwind traders.docx"); | |
DocumentBuilder builder = new DocumentBuilder(dstDoc); | |
builder.MoveToDocumentEnd(); | |
builder.InsertBreak(BreakType.PageBreak); | |
builder.InsertDocument(srcDoc, ImportFormatMode.KeepSourceFormatting); | |
builder.Document.Save(ArtifactsDir + "JoinAndAppendDocuments.InsertDocument.docx"); |
Следующий пример кода показывает, как вставить документ, используя InsertDocumentInline метод:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
DocumentBuilder srcDoc = new DocumentBuilder(); | |
srcDoc.Write("[src content]"); | |
// Create destination document. | |
DocumentBuilder dstDoc = new DocumentBuilder(); | |
dstDoc.Write("Before "); | |
dstDoc.InsertNode(new BookmarkStart(dstDoc.Document, "src_place")); | |
dstDoc.InsertNode(new BookmarkEnd(dstDoc.Document, "src_place")); | |
dstDoc.Write(" after"); | |
Assert.AreEqual("Before after", dstDoc.Document.GetText().TrimEnd()); | |
// Insert source document into destination inline. | |
dstDoc.MoveToBookmark("src_place"); | |
dstDoc.InsertDocumentInline(srcDoc.Document, ImportFormatMode.UseDestinationStyles, new ImportFormatOptions()); | |
Assert.AreEqual("Before [src content] after", dstDoc.Document.GetText().TrimEnd()); |
Следующие подразделы описывают варианты, в течение которых вы можете вставить один документ в другой.
Вставьте документ во время поиска и замены операции
Вы можете вставлять документы при выполнении операций поиска и замены. Например, документ может содержать пункты с текстом [Введение] и [Заключение]. Но в итоговом документе нужно заменить эти абзацы содержанием, полученным из другого внешнего документа. Для этого вам нужно будет создать обработчик для замены события.
Следующий пример кода показывает, как создать обработчик для замены события, чтобы использовать его позже в процессе вставки:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
private class InsertDocumentAtReplaceHandler : IReplacingCallback | |
{ | |
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args) | |
{ | |
Document subDoc = new Document(MyDir + "Document insertion 2.docx"); | |
// Insert a document after the paragraph, containing the match text. | |
Paragraph para = (Paragraph)args.MatchNode.ParentNode; | |
InsertDocument(para, subDoc); | |
// Remove the paragraph with the match text. | |
para.Remove(); | |
return ReplaceAction.Skip; | |
} | |
} |
Следующий пример кода показывает, как вставить содержимое одного документа в другой во время операции поиска и замены:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document mainDoc = new Document(MyDir + "Document insertion 1.docx"); | |
FindReplaceOptions options = new FindReplaceOptions | |
{ | |
Direction = FindReplaceDirection.Backward, | |
ReplacingCallback = new InsertDocumentAtReplaceHandler() | |
}; | |
mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options); | |
mainDoc.Save(ArtifactsDir + "CloneAndCombineDocuments.InsertDocumentAtReplace.docx"); |
Вставить документ во время Mail Merge Операция
Вы можете вставить документ в поле слияния во время Mail Merge Операция. Например, a Mail Merge Шаблон может содержать поле слияния, такое как [Summary]. Но в итоговый документ нужно вставить в это поле слияния контент, полученный из другого внешнего документа. Чтобы достичь этого, вам нужно будет создать обработчик для события слияния.
Следующий пример кода показывает, как создать обработчик для события слияния, чтобы использовать его позже в процессе вставки:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
private class InsertDocumentAtMailMergeHandler : IFieldMergingCallback | |
{ | |
// This handler makes special processing for the "Document_1" field. | |
// The field value contains the path to load the document. | |
// We load the document and insert it into the current merge field. | |
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args) | |
{ | |
if (args.DocumentFieldName == "Document_1") | |
{ | |
// Use document builder to navigate to the merge field with the specified name. | |
DocumentBuilder builder = new DocumentBuilder(args.Document); | |
builder.MoveToMergeField(args.DocumentFieldName); | |
// The name of the document to load and insert is stored in the field value. | |
Document subDoc = new Document((string)args.FieldValue); | |
InsertDocument(builder.CurrentParagraph, subDoc); | |
// The paragraph that contained the merge field might be empty now, and you probably want to delete it. | |
if (!builder.CurrentParagraph.HasChildNodes) | |
builder.CurrentParagraph.Remove(); | |
// Indicate to the mail merge engine that we have inserted what we wanted. | |
args.Text = null; | |
} | |
} | |
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args) | |
{ | |
// Do nothing. | |
} | |
} |
Следующий пример кода показывает, как вставить документ в поле слияния с помощью созданного обработчика:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document mainDoc = new Document(MyDir + "Document insertion 1.docx"); | |
mainDoc.MailMerge.FieldMergingCallback = new InsertDocumentAtMailMergeHandler(); | |
// The main document has a merge field in it called "Document_1". | |
// The corresponding data for this field contains a fully qualified path to the document. | |
// That should be inserted to this field. | |
mainDoc.MailMerge.Execute(new[] { "Document_1" }, new object[] { MyDir + "Document insertion 2.docx" }); | |
mainDoc.Save(ArtifactsDir + "CloneAndCombineDocuments.InsertDocumentAtMailMerge.doc"); |
Вставить документ в Bookmark
Вы можете импортировать текстовый файл в документ и вставлять его сразу после закладки, которую вы определили в документе. Для этого создайте закладку, где вы хотите, чтобы документ был вставлен.
Следующий пример кодирования показывает, как вставить содержимое одного документа в закладку в другом документе:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document mainDoc = new Document(MyDir + "Document insertion 1.docx"); | |
Document subDoc = new Document(MyDir + "Document insertion 2.docx"); | |
Bookmark bookmark = mainDoc.Range.Bookmarks["insertionPlace"]; | |
InsertDocument(bookmark.BookmarkStart.ParentNode, subDoc); | |
mainDoc.Save(ArtifactsDir + "CloneAndCombineDocuments.InsertDocumentAtBookmark.docx"); |
Добавить документ
У вас может быть случай использования, когда вам нужно включить дополнительные страницы из документа в конец существующего документа. Для этого нужно просто позвонить в AppendDocument Способ добавления документа в конец другого документа.
Следующий пример кода показывает, как добавить документ к концу другого документа:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document dstDoc = new Document(); | |
dstDoc.FirstSection.Body.AppendParagraph("Destination document text. "); | |
Document srcDoc = new Document(); | |
srcDoc.FirstSection.Body.AppendParagraph("Source document text. "); | |
// Append the source document to the destination document. | |
// Pass format mode to retain the original formatting of the source document when importing it. | |
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting); | |
dstDoc.Save(ArtifactsDir + "JoinAndAppendDocuments.KeepSourceFormatting.docx"); |
Импорт и вставка узлов вручную
Aspose.Words позволяет автоматически вставлять и добавлять документы без каких-либо предварительных требований к импорту. Однако, если вам нужно вставить или добавить конкретный узел вашего документа, например, раздел или абзац, то сначала вам нужно импортировать этот узел вручную.
Когда вам нужно вставить или добавить один раздел или абзац к другому, вам, по сути, нужно импортировать узлы первого дерева узла документа во второй, используя ImportNode метод. После импорта ваших узлов, вы должны использовать InsertAfter / InsertBefore Способ вставки нового узла после/до опорного узла. Это позволяет настроить процесс вставки, импортируя узлы из документа и вставляя его в заданные позиции.
Вы также можете использовать AppendChild способ добавления нового указанного узла в конец списка дочерних узлов, например, если вы хотите добавить контент на уровне абзаца вместо уровня раздела.
Следующий пример кода показывает, как вручную импортировать узлы и вставлять их после конкретного узла с помощью InsertAfter метод:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
/// <summary> | |
/// Inserts content of the external document after the specified node. | |
/// Section breaks and section formatting of the inserted document are ignored. | |
/// </summary> | |
/// <param name="insertionDestination">Node in the destination document after which the content | |
/// Should be inserted. This node should be a block level node (paragraph or table).</param> | |
/// <param name="docToInsert">The document to insert.</param> | |
private static void InsertDocument(Node insertionDestination, Document docToInsert) | |
{ | |
if (insertionDestination.NodeType == NodeType.Paragraph || insertionDestination.NodeType == NodeType.Table) | |
{ | |
CompositeNode destinationParent = insertionDestination.ParentNode; | |
NodeImporter importer = | |
new NodeImporter(docToInsert, insertionDestination.Document, ImportFormatMode.KeepSourceFormatting); | |
// Loop through all block-level nodes in the section's body, | |
// then clone and insert every node that is not the last empty paragraph of a section. | |
foreach (Section srcSection in docToInsert.Sections.OfType<Section>()) | |
foreach (Node srcNode in srcSection.Body) | |
{ | |
if (srcNode.NodeType == NodeType.Paragraph) | |
{ | |
Paragraph para = (Paragraph)srcNode; | |
if (para.IsEndOfSection && !para.HasChildNodes) | |
continue; | |
} | |
Node newNode = importer.ImportNode(srcNode, true); | |
destinationParent.InsertAfter(newNode, insertionDestination); | |
insertionDestination = newNode; | |
} | |
} | |
else | |
{ | |
throw new ArgumentException("The destination node should be either a paragraph or table."); | |
} | |
} |
Контент импортируется в раздел документа назначения по разделам, что означает, что настройки, такие как настройка страницы и заголовки или нижние колонтитулы, сохраняются во время импорта. Также полезно отметить, что вы можете определить параметры форматирования при вставке или добавлении документа, чтобы указать, как два документа соединены вместе.
Общие свойства для включения и добавления документов
Оба InsertDocument и AppendDocument Методы принимают ImportFormatMode и ImportFormatOptions в качестве входных параметров. The ImportFormatMode позволяет контролировать процесс объединения форматирования документов при импорте контента из одного документа в другой путем выбора различных режимов форматирования, таких как: UseDestinationStyles, KeepSourceFormatting, и KeepDifferentStyles. The ImportFormatOptions позволяет выбрать различные варианты импорта, такие как: IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, и SmartStyleBehavior.
Aspose.Words позволяет настроить визуализацию полученного документа, когда два документа добавляются вместе в операцию вставки или добавления, используя Section и PageSetup свойств. The PageSetup свойство содержит все атрибуты раздела, такие как SectionStart, RestartPageNumbering, PageStartingNumber, Orientation, и другие. Наиболее распространенным вариантом использования является установка SectionStart свойство определять, появится ли добавленный контент на той же странице или разделится на новый.
Следующий пример кода показывает, как добавить один документ к другому, сохраняя при этом контент от разделения на две страницы:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document srcDoc = new Document(MyDir + "Document source.docx"); | |
Document dstDoc = new Document(MyDir + "Northwind traders.docx"); | |
// Set the source document to continue straight after the end of the destination document. | |
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous; | |
// Restart the page numbering on the start of the source document. | |
srcDoc.FirstSection.PageSetup.RestartPageNumbering = true; | |
srcDoc.FirstSection.PageSetup.PageStartingNumber = 1; | |
// To ensure this does not happen when the source document has different page setup settings, make sure the | |
// settings are identical between the last section of the destination document. | |
// If there are further continuous sections that follow on in the source document, | |
// this will need to be repeated for those sections. | |
srcDoc.FirstSection.PageSetup.PageWidth = dstDoc.LastSection.PageSetup.PageWidth; | |
srcDoc.FirstSection.PageSetup.PageHeight = dstDoc.LastSection.PageSetup.PageHeight; | |
srcDoc.FirstSection.PageSetup.Orientation = dstDoc.LastSection.PageSetup.Orientation; | |
// Iterate through all sections in the source document. | |
foreach (Paragraph para in srcDoc.GetChildNodes(NodeType.Paragraph, true)) | |
{ | |
para.ParagraphFormat.KeepWithNext = true; | |
} | |
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting); | |
dstDoc.Save(ArtifactsDir + "JoinAndAppendDocuments.DifferentPageSetup.docx"); |