Inserire e aggiungere documenti

A volte è necessario combinare più documenti in uno. Puoi farlo manualmente oppure puoi usare la funzione Inserisci o aggiungi Aspose.Words.

L’operazione Inserisci consente di inserire il contenuto dei documenti creati in precedenza in uno nuovo o esistente.

A sua volta, la funzione Aggiungi consente di aggiungere un documento solo alla fine di un altro documento.

Questo articolo spiega come inserire o aggiungere un documento a un altro in modi diversi e descrive le proprietà comuni che è possibile applicare durante l’inserimento o l’aggiunta di documenti.

Inserire 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 è la copia dei nodi dal primo albero del documento al secondo.

È possibile inserire documenti in una varietà di posizioni in modi diversi. Ad esempio, è possibile inserire un documento tramite un’operazione di sostituzione, un campo di unione durante un’operazione di unione o tramite un segnalibro.

È inoltre possibile utilizzare il metodo InsertDocument, 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-C.git.
auto srcDoc = MakeObject<Document>(MyDir + u"Document source.docx");
auto dstDoc = MakeObject<Document>(MyDir + u"Northwind traders.docx");
auto builder = MakeObject<DocumentBuilder>(dstDoc);
builder->MoveToDocumentEnd();
builder->InsertBreak(BreakType::PageBreak);
builder->InsertDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
builder->get_Document()->Save(ArtifactsDir + u"JoinAndAppendDocuments.InsertDocument.docx");

Le sottosezioni seguenti descrivono le opzioni durante le quali è possibile inserire un documento in un altro.

Inserire 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 ottenere ciò, è necessario creare un gestore per l’evento replace.

L’esempio di codice seguente mostra come creare un gestore per l’evento di sostituzione per utilizzarlo in seguito nel processo di inserimento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
class InsertDocumentAtReplaceHandler : public IReplacingCallback
{
private:
ReplaceAction Replacing(SharedPtr<ReplacingArgs> args) override
{
auto subDoc = MakeObject<Document>(MyDir + u"Document insertion 2.docx");
// Insert a document after the paragraph, containing the match text.
auto para = System::ExplicitCast<Paragraph>(args->get_MatchNode()->get_ParentNode());
InsertDocument(para, subDoc);
// Remove the paragraph with the match text.
para->Remove();
return ReplaceAction::Skip;
}
};

L’esempio di codice seguente 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-C.git.
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion 1.docx");
// Set find and replace options.
auto options = MakeObject<FindReplaceOptions>();
options->set_Direction(FindReplaceDirection::Backward);
options->set_ReplacingCallback(MakeObject<CloneAndCombineDocuments::InsertDocumentAtReplaceHandler>());
// Call the replace method.
mainDoc->get_Range()->Replace(MakeObject<System::Text::RegularExpressions::Regex>(u"\\[MY_DOCUMENT\\]"), u"", options);
mainDoc->Save(ArtifactsDir + u"CloneAndCombineDocuments.InsertDocumentAtReplace.docx");

Inserire un documento durante l’operazione Mail Merge

È possibile inserire un documento in un campo di 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 il contenuto ottenuto da un altro documento esterno in questo campo di unione. Per ottenere ciò, è necessario creare un gestore per l’evento di unione.

L’esempio di codice seguente mostra come creare un gestore per l’evento di fusione per utilizzarlo in seguito nel processo di inserimento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
class InsertDocumentAtMailMergeHandler : public IFieldMergingCallback
{
private:
void FieldMerging(SharedPtr<FieldMergingArgs> args) override
{
if (args->get_DocumentFieldName() == u"Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
auto builder = MakeObject<DocumentBuilder>(args->get_Document());
builder->MoveToMergeField(args->get_DocumentFieldName());
// The name of the document to load and insert is stored in the field value.
auto subDoc = MakeObject<Document>(System::ObjectExt::Unbox<String>(args->get_FieldValue()));
InsertDocument(builder->get_CurrentParagraph(), subDoc);
// The paragraph that contained the merge field might be empty now, and you probably want to delete it.
if (!builder->get_CurrentParagraph()->get_HasChildNodes())
{
builder->get_CurrentParagraph()->Remove();
}
// Indicate to the mail merge engine that we have inserted what we wanted.
args->set_Text(nullptr);
}
}
void ImageFieldMerging(SharedPtr<ImageFieldMergingArgs> args) override
{
ASPOSE_UNUSED(args);
// Do nothing.
}
};

L’esempio di codice seguente mostra come inserire un documento nel campo Unione utilizzando il gestore creato:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion 1.docx");
mainDoc->get_MailMerge()->set_FieldMergingCallback(MakeObject<CloneAndCombineDocuments::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->get_MailMerge()->Execute(MakeArray<String>({u"Document_1"}),
MakeArray<SharedPtr<System::Object>>({System::ObjectExt::Box<String>(MyDir + u"Document insertion 2.docx")}));
mainDoc->Save(ArtifactsDir + u"CloneAndCombineDocuments.InsertDocumentAtMailMerge.doc");

Inserire un documento nel segnalibro

È possibile importare un file di testo in un documento e inserirlo subito dopo un segnalibro definito nel documento. A tale scopo, creare un paragrafo con segnalibro in cui si desidera inserire il documento.

Il seguente esempio di codifica 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-C.git.
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion 1.docx");
auto subDoc = MakeObject<Document>(MyDir + u"Document insertion 2.docx");
SharedPtr<Bookmark> bookmark = mainDoc->get_Range()->get_Bookmarks()->idx_get(u"insertionPlace");
InsertDocument(bookmark->get_BookmarkStart()->get_ParentNode(), subDoc);
mainDoc->Save(ArtifactsDir + u"CloneAndCombineDocuments.InsertDocumentAtBookmark.docx");

Aggiungere un documento

Si può avere un caso d’uso in cui è necessario includere pagine aggiuntive da un documento alla fine di un documento esistente. Per fare ciò, è sufficiente chiamare il metodo AppendDocument per aggiungere un documento alla fine di un altro.

Il seguente esempio di codice 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-C.git.
auto dstDoc = MakeObject<Document>();
dstDoc->get_FirstSection()->get_Body()->AppendParagraph(u"Destination document text. ");
auto srcDoc = MakeObject<Document>();
srcDoc->get_FirstSection()->get_Body()->AppendParagraph(u"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 + u"JoinAndAppendDocuments.KeepSourceFormatting.docx");

Importare e inserire manualmente i nodi

Aspose.Words consente di inserire e aggiungere documenti automaticamente senza alcun requisito di importazione precedente. Tuttavia, se è necessario inserire o aggiungere un nodo specifico del documento, ad esempio una sezione o un paragrafo, è necessario prima importare manualmente questo nodo.

Quando è necessario inserire o aggiungere una sezione o un paragrafo a un altro, è essenzialmente necessario importare i nodi del primo albero dei nodi del documento nel secondo utilizzando il metodo ImportNode. Dopo aver importato i nodi, è necessario 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.

È inoltre possibile utilizzare il metodo AppendChild per aggiungere un nuovo nodo specificato alla fine dell’elenco dei nodi figlio, ad esempio, se si desidera aggiungere il contenuto a livello di paragrafo anziché a livello di sezione.

L’esempio di codice seguente 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-C.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>
static void InsertDocument(SharedPtr<Node> insertionDestination, SharedPtr<Document> docToInsert)
{
if (insertionDestination->get_NodeType() == NodeType::Paragraph || insertionDestination->get_NodeType() == NodeType::Table)
{
SharedPtr<CompositeNode> destinationParent = insertionDestination->get_ParentNode();
auto importer = MakeObject<NodeImporter>(docToInsert, insertionDestination->get_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.
for (const auto& srcSection : System::IterateOver(docToInsert->get_Sections()->LINQ_OfType<SharedPtr<Section>>()))
{
for (const auto& srcNode : System::IterateOver(srcSection->get_Body()))
{
if (srcNode->get_NodeType() == NodeType::Paragraph)
{
auto para = System::ExplicitCast<Paragraph>(srcNode);
if (para->get_IsEndOfSection() && !para->get_HasChildNodes())
{
continue;
}
}
SharedPtr<Node> newNode = importer->ImportNode(srcNode, true);
destinationParent->InsertAfter(newNode, insertionDestination);
insertionDestination = newNode;
}
}
}
else
{
throw System::ArgumentException(u"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 piè di pagina, vengono conservate durante l’importazione. È anche utile notare che è possibile definire le impostazioni di formattazione quando si inserisce o si aggiunge un documento per specificare come due documenti vengono uniti insieme.

Proprietà comuni per Inserire e aggiungere documenti

Entrambi InsertDocument e AppendDocument i metodi accettano ImportFormatMode e ImportFormatOptions come parametri di input. Il ImportFormatMode consente di controllare il modo in cui la formattazione del documento viene unita quando si importa il contenuto da un documento in un altro selezionando diverse modalità di formato, ad esempio UseDestinationStyles, KeepSourceFormatting e KeepDifferentStyles. Il ImportFormatOptions 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 è quello di impostare la proprietà SectionStart per definire se il contenuto aggiunto apparirà sulla stessa pagina o diviso in una nuova.

L’esempio di codice seguente mostra come aggiungere un documento a un altro evitando che il contenuto si divida su due pagine:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto srcDoc = MakeObject<Document>(MyDir + u"Document source.docx");
auto dstDoc = MakeObject<Document>(MyDir + u"Northwind traders.docx");
// Set the source document to continue straight after the end of the destination document.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
// Restart the page numbering on the start of the source document.
srcDoc->get_FirstSection()->get_PageSetup()->set_RestartPageNumbering(true);
srcDoc->get_FirstSection()->get_PageSetup()->set_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->get_FirstSection()->get_PageSetup()->set_PageWidth(dstDoc->get_LastSection()->get_PageSetup()->get_PageWidth());
srcDoc->get_FirstSection()->get_PageSetup()->set_PageHeight(dstDoc->get_LastSection()->get_PageSetup()->get_PageHeight());
srcDoc->get_FirstSection()->get_PageSetup()->set_Orientation(dstDoc->get_LastSection()->get_PageSetup()->get_Orientation());
// Iterate through all sections in the source document.
for (const auto& para : System::IterateOver<Paragraph>(srcDoc->GetChildNodes(NodeType::Paragraph, true)))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
dstDoc->Save(ArtifactsDir + u"JoinAndAppendDocuments.DifferentPageSetup.docx");