Вмъкване и добавяне на документи
Понякога е необходимо да се комбинират няколко документа в един. Можете да направите това ръчно или можете да използвате 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-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"); |
Следният пример за код показва как да се въведе документ с помощта на 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()); |
Следните подраздели описват опциите, по време на които можете да поставите един документ в друг.
Вмъкване на документ по време на операция за намиране и замяна
Можете да поставите документи при извършване на намиране и замяна на операции. Например документът може да съдържа параграфи с текста [INTRODUCTION] и [CONCLUSION]. Но в окончателния документ трябва да замените тези параграфи със съдържанието, получено от друг външен документ. За да постигнете това, ще трябва да създадете наставник за заместващото събитие.
Следният пример за код показва как да се създаде наставник за заместващото събитие да го използва по-късно в процеса на вмъкване:
// 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; | |
} | |
} |
Следният пример за код показва как се вмъква съдържанието на един документ в друг по време на операция за намиране и замяна:
// 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"); |
Вмъкване на документ по време на Mail Merge Операция
Можете да поставите документ в сливане поле по време на Mail Merge операция. Например, Mail Merge шаблонът може да съдържа сливащо се поле като [Summary]. Но в последния документ трябва да вмъкнете съдържание, получено от друг външен документ в това поле за сливане. За да постигнете това, ще трябва да създадете отговорник за сливането.
Следният пример за код показва как да се създаде наставник за сливането събитие да го използва по-късно в процеса на вмъкване:
// 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. | |
} | |
} |
Следният пример за код показва как да се вмъкне документ в сливащото поле, като се използва създаденият свръзка:
// 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"); |
Вмъкване на документ в отметките
Можете да импортирате текстов файл в документ и да го поставите веднага след отметките, които сте определили в документа. За да направите това, създайте отметки, където искате да бъде поставен документът.
Следният пример за кодиране показва как да се вмъкне съдържанието на един документ в отметки в друг документ:
// 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"); |
Добавяне на документ
Може да имате случай на използване, в който трябва да включите допълнителни страници от документ до края на съществуващ документ. За да направите това, просто трябва да се обадите на AppendDocument метод за добавяне на документ към края на друг.
Следният пример с код показва как да се добави документ към края на друг документ:
// 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"); |
Импортиране и вмъкване на възлите ръчно
Aspose.Words позволява автоматично въвеждане и добавяне на документи без никакви предишни изисквания за внос. Въпреки това, ако трябва да въведете или да добавите конкретен възел на вашия документ, като например раздел или параграф, тогава първо трябва да внесете този възел ръчно.
Когато трябва да вмъкнете или да добавите един раздел или параграф в друг, по същество трябва да внесете възлите на първото дърво документно възел във втория, като използвате ImportNode метод. След внос на възлите, трябва да използвате InsertAfter метод за поставяне на нов възел след/преди референтния възел. Това ви позволява да персонализирате процеса на вмъкване чрез внос на възли от документ и поставяне му на дадени позиции.
Можете също така да използвате AppendChild метод за добавяне на нов определен възел към края на списъка на възлите за деца, например, ако искате да добавите съдържание на ниво параграф вместо на ниво раздел.
Следният пример с код показва как ръчно да се внасят възли и да се поставят след определен възел с помощта на 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."); | |
} | |
} |
Съдържание се внася в раздела по раздел на документа за местоназначение, което означава, че настройките, като например настройката на страниците, заглавните части или подметките, се запазват по време на вноса. Също така е полезно да се отбележи, че можете да дефинирате форматиране на настройките, когато вмъквате или добавяте документ, за да се уточни как се свързват два документа.
Общи свойства за вмъкване и добавяне на документи
И двете. InsertDocument както и AppendDocument методите се приемат ImportFormatMode както и ImportFormatOptions като входящи параметри. На ImportFormatMode позволява да контролирате как форматирането на документи се слива, когато внасяте съдържание от един документ в друг, като избирате различни режими на форматиране като UseDestinationStyles, KeepSourceFormatting, както и KeepDifferentStyles. На ImportFormatOptions позволява да изберете различни опции за внос като IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, както и SmartStyleBehavior.
Aspose.Words ви позволява да коригирате визуализацията на получения документ, когато два документа се добавят заедно в дадена вложка или операция, като използвате Section както и PageSetup имоти. На PageSetup имот съдържа всички атрибути на раздел като SectionStart, RestartPageNumbering, PageStartingNumber, Orientation, и други. Най- често използваният случай е да се определи SectionStart свойство за определяне дали добавеното съдържание ще се появи на същата страница или ще се раздели на нова.
Следният пример за код показва как да се добави един документ към друг, като същевременно съдържанието не се разделя на две страници:
// 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"); |