הכנס ונספח מסמכים

לפעמים צריך לשלב כמה מסמכים לאחד. אתה יכול לעשות את זה באופן ידני או שאתה יכול להשתמש Aspose.Words להוסיף או להוסיף תכונה.

ניתוח הכנס מאפשר לך להוסיף את התוכן של מסמכים שנוצרו בעבר לתוך חדש או קיים.

בתורו, התכונה Append מאפשר לך להוסיף מסמך רק בסוף מסמך אחר.

מאמר זה מסביר כיצד להוסיף או לאמת מסמך זה בדרכים שונות ולתאר את התכונות הנפוצות שאתה יכול ליישם בעת הוספת מסמכים או יישום.

הכנס מסמך

כאמור לעיל, Aspose.Words מסמך מיוצג כעץ של צמתים, ופעולת הוספת מסמך אחד לשני היא העתקת צמתים מן עץ המסמך הראשון אל השני.

ניתן להוסיף מסמכים במגוון מיקומים בדרכים שונות. לדוגמה, באפשרותך להוסיף מסמך באמצעות הפעלה חלופית, שדה מיזוג במהלך ניתוח מיזוג, או באמצעות סימן ספר.

אתה יכול גם להשתמש InsertDocument או InsertDocumentInline שיטה, אשר דומה להכניס מסמך Microsoft Word, להוסיף מסמך שלם בעמדה הנוכחית של cursor ללא כל יבוא קודם.

הדוגמה הבאה של הקוד מראה כיצד להוסיף מסמך באמצעות 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());

הקטעים הבאים מתארים את האפשרויות שבהן ניתן להכניס מסמך אחד לשני.

הכנס מסמך במהלך Find and Replace

ניתן להוסיף מסמכים בעת ביצוע חיפוש והחלפת פעולות. לדוגמה, מסמך יכול להכיל פסקאות עם הטקסט [המידע] ו[ההגדרה]. אבל במסמך הסופי, אתה צריך להחליף את פסקאות אלה עם התוכן המתקבל מסמך חיצוני אחר. כדי להשיג זאת, תצטרך ליצור מטפל לאירוע ההחלפה.

לדוגמה הקוד הבא מראה כיצד ליצור מטפל לאירוע ההחלפה כדי להשתמש בו מאוחר יותר בתהליך הכנס:

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

הכנס מסמך ב- Bookmark

אתה יכול לייבא קובץ טקסט לתוך מסמך ולהכניס אותו מיד לאחר סימן ספר שהגדרת במסמך. כדי לעשות זאת, ליצור סעיף מסומנים שבו אתה רוצה את המסמך להיות מוכנס.

הדוגמה הבאה מציגה כיצד להכניס את התוכן של מסמך אחד לסימן ספר במסמך אחר:

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

יבוא והכנסת Nodes באופן ידני

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 כפרמטרי קלט. The The The ImportFormatMode מאפשר לך לשלוט כיצד פורמט מסמך ממוזג כאשר אתה לייבא תוכן מ מסמך אחד למשנהו על ידי בחירת מצבי פורמט שונים כגון UseDestinationStyles, KeepSourceFormatting, ו KeepDifferentStyles. The The The ImportFormatOptions מאפשר לך לבחור אפשרויות ייבוא שונות כגון IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, ו SmartStyleBehavior.

Aspose.Words מאפשר לך להתאים את ויזואליזציה של מסמך וכתוצאה מכך כאשר שני מסמכים מתווספים יחד בפעולת כניסה או אפליקציה על ידי שימוש Section ו PageSetup תכונות. The The The 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");