Inserisci e aggiungi documenti
A volte è necessario combinare più documenti in uno solo. Puoi farlo manualmente oppure puoi utilizzare la funzione di inserimento o aggiunta Aspose.Words.
L’operazione di inserimento consente di inserire il contenuto di documenti precedentemente creati in uno nuovo o esistente.
A sua volta, la funzione di aggiunta ti consente di aggiungere un documento solo alla fine di un altro documento.
Questo articolo spiega come inserire o accodare un documento a un altro in diversi modi e descrive le proprietà comuni che è possibile applicare durante l’inserimento o l’accodamento di documenti.
Inserisci un documento
Come accennato in precedenza, in Aspose.Words un documento è rappresentato come un albero di nodi e l’operazione di inserimento di un documento in un altro consiste nel copiare i nodi dal primo albero del documento al secondo.
È possibile inserire documenti in diverse posizioni in modi diversi. Ad esempio, puoi inserire un documento tramite un’operazione di sostituzione, un campo di unione durante un’operazione di unione o tramite un segnalibro.
Puoi anche utilizzare il metodo InsertDocument o InsertDocumentInline, che è simile all’inserimento di un documento in Microsoft Word, per inserire un intero documento nella posizione corrente del cursore senza alcuna importazione precedente.
Il seguente esempio di codice mostra come inserire un documento utilizzando il metodo 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"); |
Il seguente esempio di codice mostra come inserire un documento utilizzando il metodo 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()); |
Le seguenti sottosezioni descrivono le opzioni durante le quali è possibile inserire un documento in un altro.
Inserisci un documento durante l’operazione Trova e sostituisci
È possibile inserire documenti durante l’esecuzione di operazioni di ricerca e sostituzione. Ad esempio, un documento può contenere paragrafi con il testo [INTRODUZIONE] e [CONCLUSIONE]. Ma nel documento finale è necessario sostituire quei paragrafi con il contenuto ottenuto da un altro documento esterno. Per raggiungere questo obiettivo, dovrai creare un gestore per l’evento di sostituzione.
Il seguente esempio di codice mostra come creare un gestore per l’evento di sostituzione per utilizzarlo successivamente nel processo di inserimento:
// 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; | |
} | |
} |
Il seguente esempio di codice mostra come inserire il contenuto di un documento in un altro durante un’operazione di ricerca e sostituzione:
// 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"); |
Inserisci un documento durante l’operazione Mail Merge
È possibile inserire un documento in un campo unione durante un’operazione mail merge. Ad esempio, un modello Mail Merge può contenere un campo di unione come [Riepilogo]. Ma nel documento finale, è necessario inserire in questo campo di unione il contenuto ottenuto da un altro documento esterno. Per raggiungere questo obiettivo, dovrai creare un gestore per l’evento di unione.
L’esempio di codice seguente mostra come creare un gestore per l’evento di unione per utilizzarlo successivamente nel processo di inserimento:
// 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. | |
} | |
} |
Il seguente esempio di codice mostra come inserire un documento nel campo di unione utilizzando il gestore creato:
// 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"); |
Inserisci un documento nel segnalibro
Puoi importare un file di testo in un documento e inserirlo subito dopo un segnalibro che hai definito nel documento. Per fare ciò, crea un paragrafo con segnalibro nel punto in cui desideri inserire il documento.
Il seguente esempio di codice mostra come inserire il contenuto di un documento in un segnalibro in un altro documento:
// 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"); |
Aggiungi un documento
Potresti avere un caso d’uso in cui devi includere pagine aggiuntive da un documento alla fine di un documento esistente. Per fare ciò, devi solo chiamare il metodo AppendDocument per aggiungere un documento alla fine di un altro.
L’esempio di codice seguente mostra come aggiungere un documento alla fine di un altro documento:
// 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"); |
Importa e inserisci manualmente i nodi
Aspose.Words ti consente di inserire e aggiungere documenti automaticamente senza alcun requisito di importazione precedente. Tuttavia, se devi inserire o aggiungere un nodo specifico del tuo documento, come una sezione o un paragrafo, devi prima importare questo nodo manualmente.
Quando devi inserire o accodare una sezione o un paragrafo a un altro, devi essenzialmente importare i nodi del primo albero dei nodi del documento nel secondo utilizzando il metodo ImportNode. Dopo aver importato i tuoi nodi, devi utilizzare il metodo InsertAfter/InsertBefore per inserire un nuovo nodo dopo/prima del nodo di riferimento. Ciò consente di personalizzare il processo di inserimento importando nodi da un documento e inserendolo in determinate posizioni.
Puoi anche utilizzare il metodo AppendChild per aggiungere un nuovo nodo specificato alla fine dell’elenco di nodi secondari, ad esempio, se desideri aggiungere contenuto a livello di paragrafo anziché a livello di sezione.
Il seguente esempio di codice mostra come importare manualmente i nodi e inserirli dopo un nodo specifico utilizzando il metodo 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."); | |
} | |
} |
Il contenuto viene importato nel documento di destinazione sezione per sezione, il che significa che le impostazioni, come l’impostazione della pagina e le intestazioni o i piè di pagina, vengono conservate durante l’importazione. È inoltre utile notare che è possibile definire le impostazioni di formattazione quando si inserisce o accoda un documento per specificare il modo in cui due documenti vengono uniti.
Proprietà comuni per inserire e aggiungere documenti
Entrambi i metodi InsertDocument e AppendDocument accettano ImportFormatMode e ImportFormatOptions come parametri di input. ImportFormatMode ti consente di controllare il modo in cui la formattazione del documento viene unita quando importi contenuto da un documento a un altro selezionando diverse modalità di formato come UseDestinationStyles, KeepSourceFormatting e KeepDifferentStyles. ImportFormatOptions ti consente di selezionare diverse opzioni di importazione come IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists e SmartStyleBehavior.
Aspose.Words consente di regolare la visualizzazione di un documento risultante quando due documenti vengono aggiunti insieme in un’operazione di inserimento o aggiunta utilizzando le proprietà Section e PageSetup. La proprietà PageSetup contiene tutti gli attributi di una sezione come SectionStart, RestartPageNumbering, PageStartingNumber, Orientation e altri. Il caso d’uso più comune è impostare la proprietà SectionStart per definire se il contenuto aggiunto verrà visualizzato sulla stessa pagina o suddiviso in una nuova.
L’esempio di codice seguente mostra come aggiungere un documento a un altro evitando che il contenuto venga suddiviso su due pagine:
// 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"); |