Wstaw i załącz dokumenty

Czasami wymagane jest połączenie kilku dokumentów w jedno. Możesz to zrobić ręcznie lub możesz użyć Aspose.Words wstawić lub dołączyć funkcję.

Operacja insert pozwala na dodanie zawartości wcześniej utworzonych dokumentów do nowej lub istniejącej.

Z kolei funkcja append pozwala na dodanie dokumentu tylko na końcu innego dokumentu.

Ten artykuł wyjaśnia, w jaki sposób wstawić lub dołączyć dokument do innego dokumentu na różne sposoby i opisuje wspólne właściwości, które można stosować podczas wprowadzania lub dodawania dokumentów.

Wstaw dokument

Jak wspomniano powyżej, w Aspose.Words dokument jest przedstawiany jako drzewo węzłów, a działanie wstawiania jednego dokumentu do drugiego polega na kopiowaniu węzłów od pierwszego drzewa dokumentów do drugiego.

Dokumenty można umieszczać w różnych miejscach na różne sposoby. Na przykład, można wstawić dokument poprzez operację wymiany, pole scalania podczas operacji łączenia lub poprzez zakładkę.

Można również użyć InsertDocument lub InsertDocumentInline metoda, która jest podobna do wstawiania dokumentu w Microsoft Word, wstawić cały dokument na bieżącej pozycji kursora bez wcześniejszego przywozu.

Poniższy przykład kodu pokazuje jak wstawić dokument używając InsertDocument Metoda:

// 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");

Poniższy przykład kodu pokazuje jak wstawić dokument używając InsertDocumentInline Metoda:

// 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());

Poniższe podsekcje opisują opcje, podczas których można umieścić jeden dokument w innym.

Wstaw dokument podczas wyszukiwania i zamiany operacji

Podczas wykonywania operacji znajdź i zastąp. Na przykład dokument może zawierać ustępy z tekstem [WPROWADZENIE] i [WNIOSEK]. Jednak w dokumencie końcowym należy zastąpić te ustępy treścią otrzymaną z innego dokumentu zewnętrznego. Aby to osiągnąć, trzeba będzie utworzyć opiekuna dla zdarzenia zastępczego.

Poniższy przykład kodu pokazuje, jak utworzyć opiekuna dla zdarzenia zastępującego, aby używać go później w procesie wprowadzania:

// 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;
}
}

Poniższy przykład kodu pokazuje, jak wstawić zawartość jednego dokumentu do drugiego podczas operacji wyszukiwania i zastępowania:

// 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");

Wstaw dokument podczas Mail Merge Działanie

Można umieścić dokument w polu połączenia podczas Mail Merge działanie. Na przykład Mail Merge szablon może zawierać pole scalania, takie jak [podsumowanie]. Jednak w dokumencie końcowym należy umieścić zawartość otrzymaną z innego dokumentu zewnętrznego w tym polu. Aby to osiągnąć, trzeba będzie utworzyć opiekuna dla zdarzenia połączenia.

Poniższy przykład kodu pokazuje, jak utworzyć opiekuna dla łączącego się zdarzenia do wykorzystania go później w procesie wprowadzania:

// 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.
}
}

Poniższy przykład kodu pokazuje, jak wstawić dokument do pola połączenia za pomocą utworzonego opiekuna:

// 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");

Wstaw dokument na zakładce

Możesz zaimportować plik tekstowy do dokumentu i wstawić go zaraz po zakładce zdefiniowanej w dokumencie. Aby to zrobić, należy utworzyć ustęp z zakładkami, w którym chcesz umieścić dokument.

Poniższy przykład kodowania pokazuje jak umieścić zawartość jednego dokumentu na zakładce w innym dokumencie:

// 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");

Dołącz dokument

Możesz mieć przypadek użycia, w którym musisz dołączyć dodatkowe strony od dokumentu do końca istniejącego dokumentu. Aby to zrobić, wystarczy zadzwonić do AppendDocument metoda dodawania dokumentu do końca innego dokumentu.

Poniższy przykład kodu pokazuje, jak dołączyć dokument do końca innego dokumentu:

// 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");

Importuj i wstaw węzły ręcznie

Aspose.Words pozwala na automatyczne wstawianie i uzupełnianie dokumentów bez żadnych wcześniejszych wymagań importowych. Jednakże, jeśli musisz wstawić lub dołączyć określony węzeł dokumentu, np. sekcję lub paragraf, najpierw musisz zaimportować ten węzeł ręcznie.

Gdy musisz wstawić lub dołączyć jedną sekcję lub paragraf do innej, musisz w zasadzie zaimportować węzły pierwszego drzewa węzłów dokumentu do drugiej z wykorzystaniem ImportNode Metoda. Po importowaniu węzłów, należy użyć InsertAfter metoda wprowadzania nowego węzła po / przed węzłem odniesienia. Pozwala to dostosować proces wprowadzania poprzez importowanie węzłów z dokumentu i wstawianie go na określonych pozycjach.

Można również użyć AppendChild metoda dodawania nowego określonego węzła do końca listy węzłów dziecięcych, na przykład, jeśli chcesz dołączyć zawartość na poziomie paragrafu zamiast na poziomie sekcji.

Poniższy przykład kodu pokazuje, jak ręcznie importować węzły i umieszczać je po określonym węźle za pomocą InsertAfter Metoda:

// 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.");
}
}

Zawartość jest importowana do sekcji dokumentu docelowego według sekcji, co oznacza, że ustawienia, takie jak konfiguracja strony i nagłówki lub stopki, są zachowane podczas importu. Warto również zauważyć, że można zdefiniować ustawienia formatowania przy wstawianiu lub dołączaniu dokumentu w celu określenia sposobu łączenia dwóch dokumentów.

Common Properties for insert and Append Documents

Oba InsertDocument oraz AppendDocument metody przyjęte ImportFormatMode oraz ImportFormatOptions jako parametry wejściowe. W ImportFormatMode pozwala kontrolować sposób łączenia formatowania dokumentów przy importowaniu treści z jednego dokumentu do drugiego poprzez wybór różnych trybów formatowania, takich jak: UseDestinationStyles, KeepSourceFormatting, oraz KeepDifferentStyles. W ImportFormatOptions pozwala wybrać różne opcje importu, takie jak IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, oraz SmartStyleBehavior.

Aspose.Words pozwala dostosować wizualizację otrzymanego dokumentu, gdy dwa dokumenty są dodawane do wstawić lub dołączyć operacji za pomocą Section oraz PageSetup nieruchomości. W PageSetup właściwość zawiera wszystkie atrybuty sekcji, takie jak SectionStart, RestartPageNumbering, PageStartingNumber, Orientation, I innych. Najczęstszym przypadkiem zastosowania jest ustawienie SectionStart właściwość do określenia, czy dodana zawartość pojawi się na tej samej stronie lub podzielony na nową.

Poniższy przykład kodu pokazuje, jak załączyć jeden dokument do drugiego, zachowując zawartość z podziałem na dwie strony:

// 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");