Документи

Іноді необхідно об’єднати кілька документів в одну. Ви можете зробити це вручну або ви можете використовувати 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");