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 o InsertDocumentInline, 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-Java.git.
Document srcDoc = new Document(getMyDir() + "Document source.docx");
Document dstDoc = new Document(getMyDir() + "Northwind traders.docx");
DocumentBuilder builder = new DocumentBuilder(dstDoc);
builder.moveToDocumentEnd();
builder.insertBreak(BreakType.PAGE_BREAK);
builder.insertDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
builder.getDocument().save(getArtifactsDir() + "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-Java.git.
DocumentBuilder srcDoc = new DocumentBuilder();
srcDoc.write("[src content]");
// Create destination document.
DocumentBuilder dstDoc = new DocumentBuilder();
dstDoc.write("Before ");
dstDoc.insertNode(new BookmarkStart(dstDoc.getDocument(), "src_place"));
dstDoc.insertNode(new BookmarkEnd(dstDoc.getDocument(), "src_place"));
dstDoc.write(" after");
Assert.assertEquals("Before after", dstDoc.getDocument().getText().trim());
// Insert source document into destination inline.
dstDoc.moveToBookmark("src_place");
dstDoc.insertDocumentInline(srcDoc.getDocument(), ImportFormatMode.USE_DESTINATION_STYLES, new ImportFormatOptions());
Assert.assertEquals("Before [src content] after", dstDoc.getDocument().getText().trim());

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 [INTRODUCTION] e [CONCLUSION]. 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-Java.git.
private static class InsertDocumentAtReplaceHandler implements IReplacingCallback
{
public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception
{
Document subDoc = new Document(getMyDir() + "Document insertion 2.docx");
// Insert a document after the paragraph, containing the match text.
Paragraph para = (Paragraph)args.getMatchNode().getParentNode();
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-Java.git.
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx");
// Set find and replace options.
FindReplaceOptions options = new FindReplaceOptions();
{
options.setDirection(FindReplaceDirection.BACKWARD);
options.setReplacingCallback(new InsertDocumentAtReplaceHandler());
}
// Call the replace method.
mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options);
mainDoc.save(getArtifactsDir() + "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-Java.git.
private static class InsertDocumentAtMailMergeHandler implements 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.
public void /*IFieldMergingCallback.*/fieldMerging(FieldMergingArgs args) throws Exception
{
if ("Document_1".equals(args.getDocumentFieldName()))
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(args.getDocument());
builder.moveToMergeField(args.getDocumentFieldName());
// The name of the document to load and insert is stored in the field value.
Document subDoc = new Document((String)args.getFieldValue());
insertDocument(builder.getCurrentParagraph(), subDoc);
// The paragraph that contained the merge field might be empty now, and you probably want to delete it.
if (!builder.getCurrentParagraph().hasChildNodes())
builder.getCurrentParagraph().remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
args.setText(null);
}
}
public void /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs 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-Java.git.
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx");
mainDoc.getMailMerge().setFieldMergingCallback(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.getMailMerge().execute(new String[] { "Document_1" }, new Object[] { getMyDir() + "Document insertion 2.docx" });
mainDoc.save(getArtifactsDir() + "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-Java.git.
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx");
Document subDoc = new Document(getMyDir() + "Document insertion 2.docx");
Bookmark bookmark = mainDoc.getRange().getBookmarks().get("insertionPlace");
insertDocument(bookmark.getBookmarkStart().getParentNode(), subDoc);
mainDoc.save(getArtifactsDir() + "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-Java.git.
Document dstDoc = new Document();
dstDoc.getFirstSection().getBody().appendParagraph("Destination document text. ");
Document srcDoc = new Document();
srcDoc.getFirstSection().getBody().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.KEEP_SOURCE_FORMATTING);
dstDoc.save(getArtifactsDir() + "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 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-Java.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.getNodeType() == NodeType.PARAGRAPH || insertionDestination.getNodeType() == NodeType.TABLE)
{
CompositeNode destinationParent = insertionDestination.getParentNode();
NodeImporter importer =
new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);
// 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 (Section srcSection : docToInsert.getSections())
for (Node srcNode : srcSection.getBody())
{
if (srcNode.getNodeType() == 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 IllegalArgumentException("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 i metodi InsertDocument e AppendDocument 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-Java.git.
Document srcDoc = new Document(getMyDir() + "Document source.docx");
Document dstDoc = new Document(getMyDir() + "Northwind traders.docx");
// Set the source document to continue straight after the end of the destination document.
srcDoc.getFirstSection().getPageSetup().setSectionStart(SectionStart.CONTINUOUS);
// Restart the page numbering on the start of the source document.
srcDoc.getFirstSection().getPageSetup().setRestartPageNumbering(true);
srcDoc.getFirstSection().getPageSetup().setPageStartingNumber(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.getFirstSection().getPageSetup().setPageWidth(dstDoc.getLastSection().getPageSetup().getPageWidth());
srcDoc.getFirstSection().getPageSetup().setPageHeight(dstDoc.getLastSection().getPageSetup().getPageHeight());
srcDoc.getFirstSection().getPageSetup().setOrientation(dstDoc.getLastSection().getPageSetup().getOrientation());
// Iterate through all sections in the source document.
for (Paragraph para : (Iterable<Paragraph>) srcDoc.getChildNodes(NodeType.PARAGRAPH, true))
{
para.getParagraphFormat().setKeepWithNext(true);
}
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
dstDoc.save(getArtifactsDir() + "JoinAndAppendDocuments.DifferentPageSetup.docx");