חלץ תוכן בין צמתים במסמך
בעבודה עם מסמכים, חשוב להיות מסוגלים לחלץ תוכן בקלות מטווח ספציפי בתוך מסמך. עם זאת, התוכן עשוי להיות מורכב מאלמנטים מורכבים כגון פסקאות, טבלאות, תמונות וכו'.
לא משנה איזה תוכן צריך לחלץ, השיטה לחלץ את התוכן הזה תמיד תיקבע על ידי אילו צמתים נבחרים לחלץ תוכן בין. אלה יכולים להיות גופי טקסט שלמים או ריצות טקסט פשוטות.
ישנם מצבים אפשריים רבים ולכן סוגים רבים ושונים של צמתים שיש לקחת בחשבון בעת חילוץ תוכן. לדוגמה, ייתכן שתרצה לחלץ תוכן בין:
- שתי פסקאות ספציפיות
- ריצות טקסט ספציפיות
- שדות מסוגים שונים, כגון שדות מיזוג
- טווחי התחלה וסיום של סימניה או תגובה
- גופי טקסט שונים הכלולים בסעיפים נפרדים
במצבים מסוימים, ייתכן שתצטרך אפילו לשלב סוגי צמתים שונים, כגון חילוץ תוכן בין פסקה לשדה, או בין ריצה לסימניה.
מאמר זה מספק את יישום הקוד לחילוץ טקסט בין צמתים שונים, כמו גם דוגמאות לתרחישים נפוצים.
למה לחלץ תוכן
לעתים קרובות המטרה של חילוץ התוכן היא לשכפל או לשמור אותו בנפרד במסמך חדש. לדוגמה, אתה יכול לחלץ תוכן ו:
- העתק אותו למסמך נפרד
- המרת חלק מסוים של מסמך ל PDF או תמונה
- שכפל את התוכן במסמך פעמים רבות
- עבודה עם תוכן שחולץ בנפרד משאר המסמך
ניתן להשיג זאת בקלות באמצעות Aspose.Words ויישום הקוד למטה.
חילוץ אלגוריתם תוכן
הקוד בסעיף זה מתייחס לכל המצבים האפשריים שתוארו לעיל בשיטה אחת כללית וניתנת לשימוש חוזר. המתאר הכללי של טכניקה זו כרוך:
- איסוף הצמתים המכתיבים את שטח התוכן שיופק מהמסמך שלך. החזרת הצמתים האלה מטופלת על ידי המשתמש בקוד שלהם, בהתבסס על מה שהם רוצים להוציא.
- העברת הצמתים האלה לשיטת ExtractContent המוצגת להלן. אתה חייב גם לעבור פרמטר בוליאני אשר קובע אם צמתים אלה, מתנהג כמו סמנים, צריך להיכלל החילוץ או לא.
- אחזור רשימה של תוכן משובט (צמתים מועתקים) שצוין לחילוץ. אתה יכול להשתמש ברשימת צמתים זו בכל דרך ישימה, למשל, ליצור מסמך חדש המכיל רק את התוכן שנבחר.
כיצד לחלץ תוכן
כדי לחלץ את התוכן מהמסמך שלך עליך להתקשר לשיטת ExtractContent
למטה ולהעביר את הפרמטרים המתאימים. הבסיס הבסיסי של שיטה זו כולל מציאת צמתים ברמת הבלוק (פסקאות וטבלאות) ושיבוטם ליצירת עותקים זהים. אם נקודות הסמן שעברו הן ברמת הבלוק, השיטה מסוגלת פשוט להעתיק את התוכן ברמה זו ולהוסיף אותו למערך.
עם זאת, אם נקודות הסמן הן בשורה (ילד של פסקה) אז המצב הופך מורכב יותר, שכן יש צורך לפצל את הפסקה בנקודה בשורה, בין אם זה ריצה, שדות סימניות וכו'. תוכן בצמתים האב המשובטים שאינם קיימים בין הסמנים מוסר. תהליך זה משמש כדי להבטיח שהצמתים המוטבעים עדיין ישמרו על העיצוב של פסקת האב. השיטה גם תפעיל בדיקות על הצמתים שהועברו כפרמטרים וזורקת חריג אם אחד הצמתים אינו חוקי. הפרמטרים שיש להעביר לשיטה זו הם:
-
StartNode ו EndNode. שני הפרמטרים הראשונים הם הצמתים המגדירים היכן מיצוי התוכן אמור להתחיל ולסיים בהתאמה. הצמתים האלה יכולים להיות גם ברמת בלוק (פסקה, טבלה ) וגם ברמת קו (למשל ריצה, FieldStart, BookmarkStart וכו').):
- כדי להעביר שדה עליך להעביר את האובייקט FieldStart המתאים.
- כדי להעביר סימניות, יש להעביר את הצמתים BookmarkStart ו - BookmarkEnd.
- כדי להעביר הערות, יש להשתמש בצמתים CommentRangeStart ו - CommentRangeEnd.
-
IsInclusive. מגדיר אם הסמנים כלולים בחילוץ או לא. אם אפשרות זו מוגדרת כשקר ואותו צומת או צמתים עוקבים מועברים, תוחזר רשימה ריקה:
- אם צומת FieldStart עובר אז אפשרות זו מגדירה אם כל השדה צריך להיות כלול או לא נכלל.
- אם מועבר צומת BookmarkStart או BookmarkEnd, אפשרות זו מגדירה אם הסימניה כלולה או רק את התוכן בין טווח הסימניות.
- אם מועבר צומת CommentRangeStart או CommentRangeEnd, אפשרות זו מגדירה אם יש לכלול את ההערה עצמה או רק את התוכן בטווח ההערות.
יישום השיטה ExtractContent אתה יכול למצוא כאן. שיטה זו תופנה בתרחישים במאמר זה.
אנו גם להגדיר שיטה מותאמת אישית כדי ליצור בקלות מסמך מן הצמתים שחולצו. שיטה זו משמשת ברבים מהתרחישים שלהלן ופשוט יוצרת מסמך חדש ומייבאת לתוכו את התוכן שחולץ.
דוגמת הקוד הבאה מראה כיצד לקחת רשימה של צמתים ולהכניס אותם למסמך חדש.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
static SharedPtr<Document> GenerateDocument(SharedPtr<Document> srcDoc, SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> nodes) | |
{ | |
auto dstDoc = MakeObject<Document>(); | |
// Remove the first paragraph from the empty document. | |
dstDoc->get_FirstSection()->get_Body()->RemoveAllChildren(); | |
// Import each node from the list into the new document. Keep the original formatting of the node. | |
auto importer = MakeObject<NodeImporter>(srcDoc, dstDoc, ImportFormatMode::KeepSourceFormatting); | |
for (const auto& node : nodes) | |
{ | |
SharedPtr<Node> importNode = importer->ImportNode(node, true); | |
dstDoc->get_FirstSection()->get_Body()->AppendChild(importNode); | |
} | |
return dstDoc; | |
} |
חלץ תוכן בין פסקאות
זה מדגים כיצד להשתמש בשיטה לעיל כדי לחלץ תוכן בין פסקאות ספציפיות. במקרה זה, אנחנו רוצים לחלץ את הגוף של המכתב נמצא במחצית הראשונה של המסמך. אנו יכולים לומר שזה בין הפסקאות 7 ל -11.
הקוד הבא מבצע משימה זו. הפסקאות המתאימות מופקות בשיטת GetChild במסמך ומעבירות את המדדים שצוינו. לאחר מכן אנו מעבירים את הצמתים הללו לשיטת ExtractContent ומצהירים כי יש לכלול אותם בחילוץ. שיטה זו תחזיר את התוכן המועתק בין צמתים אלה אשר מוכנסים לאחר מכן למסמך חדש.
דוגמת הקוד הבאה מראה כיצד לחלץ את התוכן בין פסקאות ספציפיות בשיטת ExtractContent
לעיל:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
auto startPara = System::ExplicitCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 6, true)); | |
auto endPara = System::ExplicitCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 10, true)); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodes = ExtractContentHelper::ExtractContent(startPara, endPara, true); | |
SharedPtr<Document> dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodes); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenParagraphs.docx"); |
חלץ תוכן בין סוגים שונים של צמתים
אנו יכולים לחלץ תוכן בין כל שילוב של צמתים ברמת בלוק או מוטבעים. בתרחיש זה להלן נחלץ את התוכן בין הפסקה הראשונה לטבלה בחלק השני באופן כולל. אנו מקבלים את צמתי הסמנים על ידי קריאה Body.FirstParagraph
ו GetChild שיטה בחלק השני של המסמך כדי לאחזר את צמתי הפסקה והטבלה המתאימים. עבור וריאציה קלה בואו במקום לשכפל את התוכן ולהכניס אותו מתחת המקורי.
דוגמת הקוד הבאה מראה כיצד לחלץ את התוכן בין פסקה לטבלה בשיטת ExtractContent
:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
auto startPara = System::ExplicitCast<Paragraph>(doc->get_LastSection()->GetChild(NodeType::Paragraph, 2, true)); | |
auto endTable = System::ExplicitCast<Table>(doc->get_LastSection()->GetChild(NodeType::Table, 0, true)); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodes = ExtractContentHelper::ExtractContent(startPara, endTable, true); | |
// Let's reverse the array to make inserting the content back into the document easier. | |
extractedNodes->Reverse(); | |
for (SharedPtr<Node> extractedNode : extractedNodes) | |
// Insert the last node from the reversed list. | |
endTable->get_ParentNode()->InsertAfter(extractedNode, endTable); | |
doc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenBlockLevelNodes.docx"); |
חלץ תוכן בין פסקאות על בסיס סגנון
ייתכן שיהיה עליך לחלץ את התוכן בין פסקאות של סגנונות זהים או שונים, כגון בין פסקאות המסומנות בסגנונות כותרת. הקוד שלהלן מראה כיצד להשיג זאת. זוהי דוגמה פשוטה שתוציא את התוכן בין הדוגמה הראשונה של סגנונות “Heading 1” ו “כותרת 3” מבלי להוציא גם את הכותרות. לשם כך אנו מגדירים את הפרמטר האחרון לשקר, המציין כי אין לכלול את צמתי הסמן.
ביישום נכון, יש להפעיל זאת בלולאה כדי לחלץ תוכן בין כל הפסקאות של סגנונות אלה מהמסמך. התוכן שחולץ מועתק למסמך חדש.
דוגמת הקוד הבאה מראה כיצד לחלץ תוכן בין פסקאות עם סגנונות ספציפיים בשיטת ExtractContent
:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
// Gather a list of the paragraphs using the respective heading styles. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Paragraph>>> parasStyleHeading1 = ParagraphsByStyleName(doc, u"Heading 1"); | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Paragraph>>> parasStyleHeading3 = ParagraphsByStyleName(doc, u"Heading 3"); | |
// Use the first instance of the paragraphs with those styles. | |
SharedPtr<Node> startPara1 = parasStyleHeading1->idx_get(0); | |
SharedPtr<Node> endPara1 = parasStyleHeading3->idx_get(0); | |
// Extract the content between these nodes in the document. Don't include these markers in the extraction. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodes = ExtractContentHelper::ExtractContent(startPara1, endPara1, false); | |
SharedPtr<Document> dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodes); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenParagraphStyles.docx"); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
static SharedPtr<System::Collections::Generic::List<SharedPtr<Paragraph>>> ParagraphsByStyleName(SharedPtr<Document> doc, System::String styleName) | |
{ | |
// Create an array to collect paragraphs of the specified style. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Paragraph>>> paragraphsWithStyle = | |
MakeObject<System::Collections::Generic::List<SharedPtr<Paragraph>>>(); | |
SharedPtr<NodeCollection> paragraphs = doc->GetChildNodes(NodeType::Paragraph, true); | |
// Look through all paragraphs to find those with the specified style. | |
for (const auto& paragraph : System::IterateOver<Paragraph>(paragraphs)) | |
{ | |
if (paragraph->get_ParagraphFormat()->get_Style()->get_Name() == styleName) | |
{ | |
paragraphsWithStyle->Add(paragraph); | |
} | |
} | |
return paragraphsWithStyle; | |
} |
חלץ תוכן בין ריצות ספציפיות
ניתן לחלץ תוכן בין צמתים מוטבעים כגון Run גם כן. Runs מפסקאות שונות ניתן להעביר כסמנים. הקוד שלהלן מראה כיצד לחלץ טקסט ספציפי בין אותו צומת Paragraph.
דוגמת הקוד הבאה מראה כיצד לחלץ תוכן בין ריצות ספציפיות של אותה פסקה בשיטת ExtractContent:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
auto para = System::ExplicitCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 7, true)); | |
SharedPtr<Run> startRun = para->get_Runs()->idx_get(1); | |
SharedPtr<Run> endRun = para->get_Runs()->idx_get(4); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodes = ExtractContentHelper::ExtractContent(startRun, endRun, true); | |
for (SharedPtr<Node> extractedNode : extractedNodes) | |
std::cout << extractedNode->ToString(SaveFormat::Text) << std::endl; |
חלץ תוכן באמצעות שדה
כדי להשתמש בשדה כסמן, יש להעביר את הצומת FieldStart
. הפרמטר האחרון לשיטת ExtractContent
יגדיר אם יש לכלול את כל השדה או לא. בואו נחלץ את התוכן בין שדה המיזוג “FullName " לפסקה במסמך. אנו משתמשים בשיטת MoveToMergeField של DocumentBuilder כיתה. פעולה זו תחזיר את הצומת FieldStart משם שדה המיזוג שהועבר אליו.
במקרה שלנו, בואו נקבע את הפרמטר האחרון שהועבר לשיטת ExtractContent לא נכון כדי להוציא את השדה מהחילוץ. אנו נעביר את התוכן שחולץ ל PDF.
דוגמת הקוד הבאה מראה כיצד לחלץ תוכן בין שדה מסוים לפסקה במסמך באמצעות שיטת ExtractContent:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field. | |
// We could also get FieldStarts of a field using GetChildNode method as in the other examples. | |
builder->MoveToMergeField(u"Fullname", false, false); | |
// The builder cursor should be positioned at the start of the field. | |
auto startField = System::ExplicitCast<FieldStart>(builder->get_CurrentNode()); | |
auto endPara = System::ExplicitCast<Paragraph>(doc->get_FirstSection()->GetChild(NodeType::Paragraph, 5, true)); | |
// Extract the content between these nodes in the document. Don't include these markers in the extraction. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodes = ExtractContentHelper::ExtractContent(startField, endPara, false); | |
SharedPtr<Document> dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodes); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentUsingField.docx"); |
חלץ תוכן מסימניה
במסמך, התוכן המוגדר בתוך סימניה מכוסה על ידי הצמתים BookmarkStart
ו - BookmarkEnd. התוכן שנמצא בין שני הצמתים הללו מהווה את הסימנייה. אתה יכול להעביר את אחד הצמתים האלה כמו כל סמן, אפילו אלה מסימניות שונות, כל עוד סמן ההתחלה מופיע לפני סמן הסיום במסמך. אנו נחלץ תוכן זה למסמך חדש באמצעות הקוד שלהלן. האפשרות IsInclusive פרמטר מראה כיצד לשמור או לבטל את הסימנייה.
דוגמת הקוד הבאה מראה כיצד לחלץ את התוכן שהופנה לסימניה באמצעות שיטת ExtractContent:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
SharedPtr<Bookmark> bookmark = doc->get_Range()->get_Bookmarks()->idx_get(u"Bookmark1"); | |
SharedPtr<BookmarkStart> bookmarkStart = bookmark->get_BookmarkStart(); | |
SharedPtr<BookmarkEnd> bookmarkEnd = bookmark->get_BookmarkEnd(); | |
// Firstly, extract the content between these nodes, including the bookmark. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodesInclusive = | |
ExtractContentHelper::ExtractContent(bookmarkStart, bookmarkEnd, true); | |
SharedPtr<Document> dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodesInclusive); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenBookmark.IncludingBookmark.docx"); | |
// Secondly, extract the content between these nodes this time without including the bookmark. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodesExclusive = | |
ExtractContentHelper::ExtractContent(bookmarkStart, bookmarkEnd, false); | |
dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodesExclusive); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenBookmark.WithoutBookmark.docx"); |
חלץ תוכן מתוך תגובה
הערה מורכבת מהצמתים CommentRangeStart, CommentRangeEnd והערות. כל הצמתים האלה מוטבעים. שני הצמתים הראשונים מכסים את התוכן במסמך שאליו מתייחסת ההערה, כפי שניתן לראות בצילום המסך למטה.
הצומת Comment עצמה היא InlineStory שיכולה להכיל פסקאות וריצות. הוא מייצג את המסר של ההערה כפי שנראה כבועת תגובה בחלונית התצוגה המקדימה. כמו הצומת הזה הוא מוטבע צאצא של גוף אתה יכול גם לחלץ את התוכן מתוך הודעה זו גם כן.
ההערה מכסה את הכותרת, הפסקה הראשונה והטבלה בחלק השני. בואו נחלץ את ההערה הזו למסמך חדש. האפשרות IsInclusive קובעת אם ההערה עצמה נשמרת או מושלכת.
דוגמת הקוד הבאה מראה כיצד לעשות זאת:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
auto commentStart = System::ExplicitCast<CommentRangeStart>(doc->GetChild(NodeType::CommentRangeStart, 0, true)); | |
auto commentEnd = System::ExplicitCast<CommentRangeEnd>(doc->GetChild(NodeType::CommentRangeEnd, 0, true)); | |
// Firstly, extract the content between these nodes including the comment as well. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodesInclusive = | |
ExtractContentHelper::ExtractContent(commentStart, commentEnd, true); | |
SharedPtr<Document> dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodesInclusive); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenCommentRange.IncludingComment.docx"); | |
// Secondly, extract the content between these nodes without the comment. | |
SharedPtr<System::Collections::Generic::List<SharedPtr<Node>>> extractedNodesExclusive = | |
ExtractContentHelper::ExtractContent(commentStart, commentEnd, false); | |
dstDoc = ExtractContentHelper::GenerateDocument(doc, extractedNodesExclusive); | |
dstDoc->Save(ArtifactsDir + u"ExtractContent.ExtractContentBetweenCommentRange.WithoutComment.docx"); |
כיצד לחלץ תוכן באמצעות DocumentVisitor
השתמש בכיתה DocumentVisitor כדי ליישם תרחיש שימוש זה. מחלקה זו תואמת את דפוס עיצוב המבקרים הידוע. באמצעות DocumentVisitor, ניתן להגדיר ולבצע פעולות מותאמות אישית הדורשות ספירה מעל עץ המסמך.
DocumentVisitor
כל שיטה DocumentVisitor.VisitXXX מחזירה ערך VisitorAction השולט בספירת הצמתים. אתה יכול לבקש להמשיך את הספירה, לדלג על הצומת הנוכחי (אבל להמשיך את הספירה), או להפסיק את ספירת הצמתים.
אלה השלבים שעליך לבצע כדי לקבוע ולחלץ באופן פרוגרמטי חלקים שונים במסמך:
- צור מחלקה הנגזרת מ DocumentVisitor
- לעקוף ולספק יישומים עבור חלק או את כל DocumentVisitor.VisitXXX שיטות לבצע כמה פעולות מותאמות אישית
- התקשר
Node.Accept
בצומת שממנו ברצונך להתחיל את הספירה. לדוגמה, אם ברצונך למנות את המסמך כולו, השתמש בDocument.Accept
DocumentVisitor
דוגמה זו מראה כיצד להשתמש בתבנית המבקר כדי להוסיף פעולות חדשות למודל האובייקט Aspose.Words. במקרה זה, אנו יוצרים ממיר מסמכים פשוט לפורמט טקסט:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Extract content.docx"); | |
auto convertToPlainText = MakeObject<ExtractContent::ConvertDocToTxt>(); | |
// Note that every node in the object model has the accept method so the visiting | |
// can be executed not only for the whole document, but for any node in the document. | |
doc->Accept(convertToPlainText); | |
// Once the visiting is complete, we can retrieve the result of the operation, | |
// That in this example, has accumulated in the visitor. | |
std::cout << convertToPlainText->GetText() << std::endl; |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
/// <summary> | |
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor. | |
/// </summary> | |
class ConvertDocToTxt : public DocumentVisitor | |
{ | |
public: | |
ConvertDocToTxt() : mIsSkipText(false) | |
{ | |
mIsSkipText = false; | |
mBuilder = MakeObject<System::Text::StringBuilder>(); | |
} | |
/// <summary> | |
/// Gets the plain text of the document that was accumulated by the visitor. | |
/// </summary> | |
String GetText() | |
{ | |
return mBuilder->ToString(); | |
} | |
/// <summary> | |
/// Called when a Run node is encountered in the document. | |
/// </summary> | |
VisitorAction VisitRun(SharedPtr<Run> run) override | |
{ | |
AppendText(run->get_Text()); | |
// Let the visitor continue visiting other nodes. | |
return VisitorAction::Continue; | |
} | |
/// <summary> | |
/// Called when a FieldStart node is encountered in the document. | |
/// </summary> | |
VisitorAction VisitFieldStart(SharedPtr<FieldStart> fieldStart) override | |
{ | |
ASPOSE_UNUSED(fieldStart); | |
// In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows | |
// after a field start character. We want to skip field codes and output field. | |
// Result only, therefore we use a flag to suspend the output while inside a field code. | |
// Note this is a very simplistic implementation and will not work very well. | |
// If you have nested fields in a document. | |
mIsSkipText = true; | |
return VisitorAction::Continue; | |
} | |
/// <summary> | |
/// Called when a FieldSeparator node is encountered in the document. | |
/// </summary> | |
VisitorAction VisitFieldSeparator(SharedPtr<FieldSeparator> fieldSeparator) override | |
{ | |
ASPOSE_UNUSED(fieldSeparator); | |
// Once reached a field separator node, we enable the output because we are | |
// now entering the field result nodes. | |
mIsSkipText = false; | |
return VisitorAction::Continue; | |
} | |
/// <summary> | |
/// Called when a FieldEnd node is encountered in the document. | |
/// </summary> | |
VisitorAction VisitFieldEnd(SharedPtr<FieldEnd> fieldEnd) override | |
{ | |
ASPOSE_UNUSED(fieldEnd); | |
// Make sure we enable the output when reached a field end because some fields | |
// do not have field separator and do not have field result. | |
mIsSkipText = false; | |
return VisitorAction::Continue; | |
} | |
/// <summary> | |
/// Called when visiting of a Paragraph node is ended in the document. | |
/// </summary> | |
VisitorAction VisitParagraphEnd(SharedPtr<Paragraph> paragraph) override | |
{ | |
ASPOSE_UNUSED(paragraph); | |
// When outputting to plain text we output Cr+Lf characters. | |
AppendText(ControlChar::CrLf()); | |
return VisitorAction::Continue; | |
} | |
VisitorAction VisitBodyStart(SharedPtr<Body> body) override | |
{ | |
ASPOSE_UNUSED(body); | |
// We can detect beginning and end of all composite nodes such as Section, Body, | |
// Table, Paragraph etc and provide custom handling for them. | |
mBuilder->Append(u"*** Body Started ***\r\n"); | |
return VisitorAction::Continue; | |
} | |
VisitorAction VisitBodyEnd(SharedPtr<Body> body) override | |
{ | |
ASPOSE_UNUSED(body); | |
mBuilder->Append(u"*** Body Ended ***\r\n"); | |
return VisitorAction::Continue; | |
} | |
/// <summary> | |
/// Called when a HeaderFooter node is encountered in the document. | |
/// </summary> | |
VisitorAction VisitHeaderFooterStart(SharedPtr<HeaderFooter> headerFooter) override | |
{ | |
ASPOSE_UNUSED(headerFooter); | |
// Returning this value from a visitor method causes visiting of this | |
// Node to stop and move on to visiting the next sibling node | |
// The net effect in this example is that the text of headers and footers | |
// Is not included in the resulting output | |
return VisitorAction::SkipThisNode; | |
} | |
private: | |
SharedPtr<System::Text::StringBuilder> mBuilder; | |
bool mIsSkipText; | |
/// <summary> | |
/// Adds text to the current output. Honors the enabled/disabled output flag. | |
/// </summary> | |
void AppendText(String text) | |
{ | |
if (!mIsSkipText) | |
{ | |
mBuilder->Append(text); | |
} | |
} | |
}; |
כיצד לחלץ טקסט בלבד
הדרכים לאחזור טקסט מהמסמך הן:
- השתמש Document.Save עם SaveFormat.Text כדי לשמור כטקסט רגיל בקובץ או בזרם
- השתמש Node.ToString והעביר את הפרמטר SaveFormat.Text. באופן פנימי, זה קורא לשמור כטקסט לזרם זיכרון ומחזיר את המחרוזת שהתקבלה
- השתמש Node.GetText כדי לאחזר טקסט עם כל תווי הבקרה Microsoft Word כולל קודי שדה
- יישום מותאם אישית DocumentVisitor לביצוע מיצוי מותאם אישית
באמצעות Node.GetText
ו Node.ToString
מסמך Word יכול להכיל תווי בקרה המייעדים אלמנטים מיוחדים כגון שדה, סוף התא, סוף הקטע וכו'. הרשימה המלאה של תווי הבקרה האפשריים Word מוגדרת בכיתה ControlChar. השיטה Node.GetText מחזירה טקסט עם כל תווי תווי הבקרה הקיימים בצומת.
קריאה ToString מחזירה את ייצוג הטקסט הרגיל של המסמך רק ללא תווי בקרה.
דוגמת הקוד הבאה מראה את ההבדל בין קריאת השיטות GetText ו - ToString בצומת:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
builder->InsertField(u"MERGEFIELD Field"); | |
// When converted to text it will not retrieve fields code or special characters, | |
// but will still contain some natural formatting characters such as paragraph markers etc. | |
// This is the same as "viewing" the document as if it was opened in a text editor. | |
std::cout << (String(u"ToString() Result: ") + doc->ToString(SaveFormat::Text)) << std::endl; |
שימוש SaveFormat.Text
דוגמה זו שומרת את המסמך באופן הבא:
- מסנן את תווי שדה וקודי שדה, צורה, הערת שוליים, הערת סיום והפניות תגובה
- מחליף סוף פסקה ControlChar.Cr תווים עם ControlChar.CrLf שילובים
- משתמש UTF8 קידוד
דוגמת הקוד הבאה מראה כיצד לשמור מסמך בפורמט TXT:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Document.docx"); | |
doc->Save(ArtifactsDir + u"BaseConversions.DocxToTxt.txt"); |
חלץ תמונות מצורות
ייתכן שיהיה עליך לחלץ תמונות מסמך כדי לבצע משימות מסוימות. Aspose.Words מאפשר לך לעשות זאת גם כן.
דוגמת הקוד הבאה מראה כיצד לחלץ תמונות ממסמך:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Images.docx"); | |
SharedPtr<NodeCollection> shapes = doc->GetChildNodes(NodeType::Shape, true); | |
int imageIndex = 0; | |
for (const auto& shape : System::IterateOver<Shape>(shapes)) | |
{ | |
if (shape->get_HasImage()) | |
{ | |
String imageFileName = | |
String::Format(u"Image.ExportImages.{0}_{1}", imageIndex, FileFormatUtil::ImageTypeToExtension(shape->get_ImageData()->get_ImageType())); | |
// Note, if you have only an image (not a shape with a text and the image), | |
// you can use shape->GetShapeRenderer()->Save(...) method to save the image. | |
shape->get_ImageData()->Save(ArtifactsDir + imageFileName); | |
imageIndex++; | |
} | |
} |