יצירת תוכן בין נקודות במסמך
בעת עבודה עם מסמכים, חשוב להיות מסוגל בקלות להפיק תוכן מטווח מסוים בתוך מסמך. עם זאת, התוכן עשוי לכלול אלמנטים מורכבים כגון פסקאות, טבלאות, תמונות וכו ‘.
ללא קשר לשאלה איזה תוכן צריך להיות מופק, השיטה כדי לחלץ תוכן זה תמיד ייקבע על ידי אילו צמתים נבחרים כדי להפיק תוכן בין. אלה יכולים להיות גוף טקסט שלם או טקסט פשוט פועל.
ישנם מצבים רבים אפשריים ולכן סוגים שונים של צומת לשקול בעת תמצית התוכן. לדוגמה, ייתכן שתרצה להפיק תוכן בין:
- 2 סעיפים ספציפיים
- ריצה ספציפית של טקסט
- שדות מסוגים שונים, כגון שדות מתמזגים
- התחל וסיום טווחים של הערה או תגובה
- גופים שונים של טקסט הכלולים בחלקים נפרדים
במצבים מסוימים, ייתכן אפילו צריך לשלב סוגים שונים של צומת, כגון תמצית תוכן בין פסקה לשדה, או בין ריצה וסימן ספר.
מאמר זה מספק את יישום הקוד עבור תמצית טקסט בין צמתים שונים, כמו גם דוגמאות של תרחישים נפוצים.
למה לחלץ תוכן
לעתים קרובות המטרה של תמצית התוכן היא לשכפל או להציל אותו בנפרד במסמך חדש. לדוגמה, אתה יכול להפיק תוכן ו:
- העתק אותו לתוך מסמך נפרד
- להמיר חלק מסוים של מסמך ל- PDF או תמונה
- מחק את התוכן במסמך פעמים רבות
- עבודה עם תוכן מופק בנפרד משאר המסמך
ניתן להשיג זאת בקלות באמצעות Aspose.Words יישום הקוד למטה.
יצירת תוכן Algorithm
הקוד בסעיף זה מתייחס לכל המצבים האפשריים המתוארים לעיל עם שיטה אחת כללית וניתנת לזיהוי. קווי המתאר הכלליים של טכניקה זו כוללים:
1.1 1. איסוף הצמתים המכתיבים את תחום התוכן שיוציא מהמסמכים שלך. שחזור נקודות אלה מטופל על ידי המשתמש בקוד שלהם, בהתבסס על מה שהם רוצים להיות מופקים. 1.1 1. לעבור את הנקודות האלה אל ExtractContent השיטה סיפקה למטה. כמו כן, עליך לעבור פרמטר בולקטי שקובע אם נקודות אלה, הפועלות כסמן, יש לכלול במיצוי או לא. 1.1 1. החזרת רשימה של תוכן משובש (עמודים מאוישים) שצוין להיות מופק. אתה יכול להשתמש ברשימה זו של צמתים בכל דרך רלוונטית, למשל, יצירת מסמך חדש המכיל רק את התוכן שנבחר.
כיצד להפיק תוכן
אנו נפעל עם המסמך למטה במאמר זה. כפי שאתה יכול לראות זה מכיל מגוון של תוכן. כמו כן, המסמך מכיל סעיף שני שמתחיל באמצע העמוד הראשון. הערה והערה מופיעים גם במסמך אך אינם גלויים בתצלום המסך למטה.
כדי להפיק את התוכן מהמסמכים שלך אתה צריך להתקשר ExtractContent
שיטה למטה ולהעביר את הפרמטרים המתאימים.
הבסיס הבסיסי של שיטה זו כרוך במציאת בלוטות ברמת חסימת (סעיפים וטבלאות) ולהטיש אותם כדי ליצור עותקים זהים. אם צומת הסמן עבר הם ברמת בלוק, השיטה מסוגלת פשוט להעתיק את התוכן ברמה זו ולהוסיף אותו למערך.
עם זאת, אם הצמתים הם קו תחתון (ילד של פסקה) המצב הופך מורכב יותר, שכן יש צורך לפצל את פסקה בצומת קו, להיות זה ריצה, שדות סימן ספר וכו ‘. תוכן בבלוטות ההורות המשובחות אינו נוכח בין הסמן הוסר. תהליך זה משמש כדי להבטיח כי הצמתים באינטרנט עדיין ישמרו את התבנית של פסקת ההורים.
השיטה גם תרוץ בדיקות על הצמתים שעברו כפרמטרים וזרק יוצא מן הכלל אם הצומת אינו חוקי. הפרמטרים שיש לעבור בשיטה זו הם:
1.1 1. StartNode ו EndNode. שני הפרמטרים הראשונים הם המכשולים המגדירים איפה החילוץ של התוכן הוא להתחיל ולסיים בהתאמה. נקודות אלה יכולות להיות גם רמת בלוק (Paragraph , Table ) או רמת Inline (e.g Run , FieldStart , BookmarkStart וכו’): 1.לעבור שדה אתה צריך לעבור את המתאים FieldStart אובייקט 1.כדי להעביר הערות ספרים, BookmarkStart ו BookmarkEnd יש להעביר את הצמתים. 1.כדי להעביר הערות, CommentRangeStart ו CommentRangeEnd יש להשתמש במכשולים. 1.1 1. IsInclusive. Defines אם הסמן נכללים במיצוי או לא. אם אפשרות זו נקבעת false ואותה צומת או צמתים רצופים מועברים, ואז יוחזרו רשימה ריקה:
1 אם **FieldStart** הצומת מועבר אז אפשרות זו מגדירה אם כל השדה יש לכלול או לשלול.
1 אם **BookmarkStart** או **BookmarkEnd** Node מועבר, אפשרות זו מגדירה אם סימן הספר נכלל או רק את התוכן בין טווח הסימון.
1 אם **CommentRangeStart** או **CommentRangeEnd** Node מועבר, אפשרות זו מגדירה אם התגובה עצמה היא לכלול או רק את התוכן בטווח ההערה.
היישום של ExtractContent שיטה שאתה יכול למצוא כאן. שיטה זו תתייחס לתרחישים במאמר זה.
כמו כן, אנו מגדירים שיטה מותאמת ליצירת מסמך בקלות מנקודות מופקות. שיטה זו משמשת ברבים מהתרחישים הבאים ופשוט יוצרת מסמך חדש ומייבאת את התוכן המפלט אליו.
הדוגמה הבאה של הקוד מראה כיצד לקחת רשימה של צמתים ולהכניס אותם למסמך חדש:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
public static Document generateDocument(Document srcDoc, ArrayList<Node> nodes) throws Exception | |
{ | |
Document dstDoc = new Document(); | |
// Remove the first paragraph from the empty document. | |
dstDoc.getFirstSection().getBody().removeAllChildren(); | |
// Import each node from the list into the new document. Keep the original formatting of the node. | |
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
for (Node node : nodes) | |
{ | |
Node importNode = importer.importNode(node, true); | |
dstDoc.getFirstSection().getBody().appendChild(importNode); | |
} | |
return dstDoc; | |
} |
המונחים: Paragraphs
זה מדגים כיצד להשתמש בשיטה לעיל כדי להפיק תוכן בין סעיפים ספציפיים. במקרה זה, אנו רוצים לחלץ את הגוף של המכתב שנמצא במחצית הראשונה של המסמך. אנחנו יכולים לומר שזה בין הסעיפים השביעית וה-11.
הקוד הבא מבצע משימה זו. הסעיפים המתאימים מופקים באמצעות getChild שיטה על המסמך ועברת כתבי אישום המפורטים. לאחר מכן אנו עוברים את הנקודות האלה אל ExtractContent שיטה ומדינה כי אלה יש לכלול במיצוי. שיטה זו תחזיר את התוכן המועתק בין נקודות אלה אשר מוכנסות לתוך מסמך חדש.
הדוגמה הבאה של הקוד מראה כיצד להפיק את התוכן בין סעיפים ספציפיים באמצעות הסעיף ExtractContent
שיטה למעלה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
Paragraph startPara = (Paragraph) doc.getFirstSection().getBody().getChild(NodeType.PARAGRAPH, 6, true); | |
Paragraph endPara = (Paragraph) doc.getFirstSection().getBody().getChild(NodeType.PARAGRAPH, 10, true); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
ArrayList<Node> extractedNodes = ExtractContentHelper.extractContent(startPara, endPara, true); | |
Document dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodes); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenParagraphs.docx"); |
מסמך הפלט מכיל את שתי הסעיפים שהופקו.
המונחים: different Types of Nodes
אנו יכולים להפיק תוכן בין כל שילובים של צמתים ברמת בלוק או איליין. בתרחיש זה להלן נוציא את התוכן בין הסעיף הראשון לשולחן בחלק השני באופן בלעדי. אנחנו מקבלים את הסמן על ידי קריאה getFirstParagraph ו getChild שיטה על החלק השני של המסמך כדי לשחזר את המתאים Paragraph ו Table צומת עבור וריאציות קלות בואו לשכפל את התוכן ולהכניס אותו מתחת למקור.
הדוגמה הבאה של הקוד מראה כיצד להפיק את התוכן בין פסקה ושולחן באמצעות הסעיף ExtractContent שיטה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
Paragraph startPara = (Paragraph) doc.getLastSection().getChild(NodeType.PARAGRAPH, 2, true); | |
Table endTable = (Table) doc.getLastSection().getChild(NodeType.TABLE, 0, true); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
ArrayList<Node> extractedNodes = ExtractContentHelper.extractContent(startPara, endTable, true); | |
// Let's reverse the array to make inserting the content back into the document easier. | |
Collections.reverse(extractedNodes); | |
for (Node extractedNode : extractedNodes) | |
// Insert the last node from the reversed list. | |
endTable.getParentNode().insertAfter(extractedNode, endTable); | |
doc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenBlockLevelNodes.docx"); |
התוכן בין הסעיף והשולחן משוכפל למטה הוא התוצאה.
המונחים: Paragraphs מבוסס על סגנון
ייתכן שיהיה עליך להפיק את התוכן בין פסקאות של אותו סגנון או שונה, כגון בין פסקאות המסומנים עם סגנונות כותרת.
הקוד הבא מראה כיצד להשיג זאת. זוהי דוגמה פשוטה שתוציא את התוכן בין הדוגמה הראשונה של סגנונות “Heading 1” ו-“Header 3” מבלי להוציא גם את הכותרות. כדי לעשות זאת, אנו מציבים את הפרמטר האחרון false, אשר מציין כי לא צריך לכלול את הסמן.
ביישום ראוי, זה צריך להיות מופעל בלולאה כדי לחלץ תוכן בין כל פסקאות של סגנונות אלה מן המסמך. התוכן מופק מועתק במסמך חדש.
הדוגמה הבאה של הקוד מראה כיצד להפיק תוכן בין פסקאות עם סגנונות ספציפיים באמצעות הפורמט ExtractContent שיטה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
// Gather a list of the paragraphs using the respective heading styles. | |
ArrayList<Paragraph> parasStyleHeading1 = paragraphsByStyleName(doc, "Heading 1"); | |
ArrayList<Paragraph> parasStyleHeading3 = paragraphsByStyleName(doc, "Heading 3"); | |
// Use the first instance of the paragraphs with those styles. | |
Node startPara1 = parasStyleHeading1.get(0); | |
Node endPara1 = parasStyleHeading3.get(0); | |
// Extract the content between these nodes in the document. Don't include these markers in the extraction. | |
ArrayList<Node> extractedNodes = ExtractContentHelper.extractContent(startPara1, endPara1, false); | |
Document dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodes); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenParagraphStyles.docx"); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
public static ArrayList<Paragraph> paragraphsByStyleName(Document doc, String styleName) | |
{ | |
// Create an array to collect paragraphs of the specified style. | |
ArrayList<Paragraph> paragraphsWithStyle = new ArrayList<Paragraph>(); | |
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true); | |
// Look through all paragraphs to find those with the specified style. | |
for (Paragraph paragraph : (Iterable<Paragraph>) paragraphs) | |
{ | |
if (paragraph.getParagraphFormat().getStyle().getName().equals(styleName)) | |
paragraphsWithStyle.add(paragraph); | |
} | |
return paragraphsWithStyle; | |
} |
להלן התוצאה של הפעולה הקודמת.
המונחים: Specific Runs
אתה יכול להפיק תוכן בין בלוטות אינטרנט כגון Run גם. Runs מסעיפים שונים ניתן לעבור כסמן. הקוד להלן מראה כיצד להפיק טקסט ספציפי בין אותו הדבר Paragraph צומת.
הדוגמה הבאה של הקוד מראה כיצד להפיק תוכן בין ריצות ספציפיות של אותה פסקה באמצעות אותה פסקה באמצעות הסעיף ExtractContent שיטה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
Paragraph para = (Paragraph) doc.getChild(NodeType.PARAGRAPH, 7, true); | |
Run startRun = para.getRuns().get(1); | |
Run endRun = para.getRuns().get(4); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
ArrayList<Node> extractedNodes = ExtractContentHelper.extractContent(startRun, endRun, true); | |
for (Node extractedNode : extractedNodes) | |
System.out.println(extractedNode.toString(SaveFormat.TEXT)); |
הטקסט מופק מוצג על הקונסולה
יצירת תוכן באמצעות שדה
להשתמש בשדה כסמן, FieldStart
צריך לעבור את הצומת. הפרמטר האחרון ל ExtractContent
השיטה תגדיר אם כל השדה ייכלל או לא. בואו נוציא את התוכן בין שדה המיזוג המלא לפסקה במסמך. אנחנו משתמשים moveToMergeField שיטת DocumentBuilder מעמד. זה ישוב FieldStart משמו של שדה המיזוג עבר אליו.
במקרה שלנו, נגדיר את הפרמטר האחרון שעבר ExtractContent שיטה false להוציא את השדה מהמיצוי. אנו נעביר את התוכן המופץ ל- PDF.
הדוגמה הבאה של הקוד מראה כיצד להפיק תוכן בין שדה ספציפי לפסקה במסמך באמצעות השימוש בתוכן ExtractContent שיטה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
DocumentBuilder builder = new 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("Fullname", false, false); | |
// The builder cursor should be positioned at the start of the field. | |
FieldStart startField = (FieldStart) builder.getCurrentNode(); | |
Paragraph endPara = (Paragraph) doc.getFirstSection().getChild(NodeType.PARAGRAPH, 5, true); | |
// Extract the content between these nodes in the document. Don't include these markers in the extraction. | |
ArrayList<Node> extractedNodes = ExtractContentHelper.extractContent(startField, endPara, false); | |
Document dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodes); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentUsingField.docx"); |
התוכן המוציא בין השדה לפסקה, ללא שדה וסימן פסקאות שניתנו ל- PDF.
צילום: a Bookmark
במסמך, התוכן שמוגדר בתוך סימן ספר מוזנח על ידי BookmarkStart
שם הספר: End nodes התוכן נמצא בין שני צמתים אלה מעלה את סימן הספר. אתה יכול לעבור את הצומתים האלה כמו כל סימן, אפילו אלה מסימנים שונים, כל עוד הסימן מתחיל מופיע לפני הסמן הסופי במסמך.
במסמך המדגם שלנו, יש לנו סימן אחד בשם “Bookmark1”. התוכן של הערה זו מודגש תוכן במסמך שלנו:
אנו נוציא את התוכן הזה במסמך חדש באמצעות הקוד להלן. The The The IsInclusive אפשרות פרמטר מראה כיצד לשמור או למחוק את סימן הספר.
הדוגמה הבאה של הקוד מראה כיצד לחלץ את התוכן המתייחס לסימן ספר באמצעות הסימן ExtractContent שיטה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
Bookmark bookmark = doc.getRange().getBookmarks().get("Bookmark1"); | |
BookmarkStart bookmarkStart = bookmark.getBookmarkStart(); | |
BookmarkEnd bookmarkEnd = bookmark.getBookmarkEnd(); | |
// Firstly, extract the content between these nodes, including the bookmark. | |
ArrayList<Node> extractedNodesInclusive = ExtractContentHelper.extractContent(bookmarkStart, bookmarkEnd, true); | |
Document dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodesInclusive); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenBookmark.IncludingBookmark.docx"); | |
// Secondly, extract the content between these nodes this time without including the bookmark. | |
ArrayList<Node> extractedNodesExclusive = ExtractContentHelper.extractContent(bookmarkStart, bookmarkEnd, false); | |
dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodesExclusive); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenBookmark.WithoutBookmark.docx"); |
הפלט מופק עם IsInclusive
פרמטר true. גם העותק ישמר את סימן הספר.
הפלט מופק עם IsInclusive פרמטר false. העותק מכיל את התוכן, אך ללא סימן הספר.
יצירת תוכן מתוך A Comment
תגובה מורכבת מ- CommentRangeStart, CommentRange End and Comment nodes. כל הצומתים האלה הם פנימיים. שני הצומת הראשונים מבססים את התוכן במסמך אשר מתייחס על ידי ההערה, כפי שנראה בתמונה למטה.
The The The Comment צומת עצמו הוא InlineStory זה יכול להכיל פסקאות וריצה. זה מייצג את המסר של התגובה כפי שנראה כמו בועה תגובה במחבת הביקורת. מכיוון שצומת זה הוא קו פנימי וצאצא של גוף אתה יכול גם לחלץ את התוכן מבפנים הודעה זו.
במסמך שלנו יש תגובה אחת. בואו להציג את זה על ידי הצגת סימון בכרטיסיה:
ההערה מעלה את הכותרת, הסעיף הראשון והשולחן בחלק השני. בואו נוציא את ההערה הזו למסמך חדש. The The The IsInclusive אפשרות תכתיב אם התגובה עצמה נשמרת או נמחקה.
דוגמה לקוד הבא מראה כיצד לעשות זאת היא למטה:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
CommentRangeStart commentStart = (CommentRangeStart) doc.getChild(NodeType.COMMENT_RANGE_START, 0, true); | |
CommentRangeEnd commentEnd = (CommentRangeEnd) doc.getChild(NodeType.COMMENT_RANGE_END, 0, true); | |
// Firstly, extract the content between these nodes including the comment as well. | |
ArrayList<Node> extractedNodesInclusive = ExtractContentHelper.extractContent(commentStart, commentEnd, true); | |
Document dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodesInclusive); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenCommentRange.IncludingComment.docx"); | |
// Secondly, extract the content between these nodes without the comment. | |
ArrayList<Node> extractedNodesExclusive = ExtractContentHelper.extractContent(commentStart, commentEnd, false); | |
dstDoc = ExtractContentHelper.generateDocument(doc, extractedNodesExclusive); | |
dstDoc.save(getArtifactsDir() + "ExtractContent.ExtractContentBetweenCommentRange.WithoutComment.docx"); |
ראשית, הפלט המפלט עם IsInclusive
פרמטר true. העותק יכלול גם את ההערה.
שנית, הפלט מופק עם כולל להגדיר false. העותק מכיל את התוכן אך ללא התגובה.
ערכת תוכן באמצעות DocumentVisitor
Aspose.Words ניתן להשתמש לא רק ליצירת Microsoft Word מסמכים על ידי בנייתם באופן דינמי או מיזוג תבניות עם נתונים, אבל גם עבור מסמכים כדי לחלץ אלמנטים מסמך נפרדים כגון ראשים, רגלים, פסקאות, טבלאות, תמונות ואחרים. משימה אפשרית נוספת היא למצוא את כל הטקסט של פורמט או סגנון ספציפי.
השתמש DocumentVisitor שיעור ליישום תרחיש שימוש זה. מחלקה זו תואמת את דפוס עיצוב המבקרים הידוע. עם DocumentVisitorאתה יכול להגדיר ולבצע פעולות מותאמות אישית הדורשות הארה על עץ המסמך.
DocumentVisitor מספק קבוצה VisitXXX שיטות אשר מופעלות כאשר רכיב מסמך מסוים (node) נתקל. לדוגמה, VisitParagraphStart נקרא כאשר תחילת פסקת טקסט נמצאת ו VisitParagraphEnd הוא נקרא כשסיומו של סעיף טקסט נמצא. כל אחד DocumentVisitor.VisitXXX השיטה מקבלת את האובייקט המתאים שהוא נתקל בו כך שתוכל להשתמש בו כנדרש (לדוגמא לאחזר את הפורמט), למשל. VisitParagraphStart ו VisitParagraphEnd קבל Paragraph אובייקט
כל אחד DocumentVisitor.VisitXXX שיטה מחזירה VisitorAction ערך השולט בהארה של צמתים. אתה יכול לבקש להמשיך את האמרה, לדלג על הצומת הנוכחי (אך להמשיך את האמרה), או לעצור את האמרה של צמתים.
אלה הם השלבים שאתה צריך לעקוב כדי לקבוע וליישם חלקים שונים של מסמך:
- יצירת מעמד נגזר DocumentVisitor.
- להתגבר ולספק יישום עבור חלק או את כל DocumentVisitor.VisitXXX שיטות לביצוע פעולות מותאמות אישית.
- Call Node.accept על הצומת מאיפה אתה רוצה להתחיל את האמרה. לדוגמה, אם ברצונך למנות את כל המסמך, השתמש accept(DocumentVisitor).
DocumentVisitor מספק יישום ברירת מחדל עבור כל DocumentVisitor.VisitXXX שיטות. זה הופך את זה קל יותר ליצור מבקרים חדשים מסמך רק את השיטות הנדרשות עבור מבקר מסוים צריך להיות overridden. אין צורך לעקוף את כל שיטות המבקרים.
הדוגמה הבאה מראה כיצד להשתמש בדפוס המבקרים כדי להוסיף פעולות חדשות Aspose.Words מודל אובייקט במקרה זה, אנו יוצרים מסמך פשוט להמיר לתבנית טקסט:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Extract content.docx"); | |
ConvertDocToTxt convertToPlainText = new 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. | |
System.out.println(convertToPlainText.getText()); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
/// <summary> | |
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor. | |
/// </summary> | |
static class ConvertDocToTxt extends DocumentVisitor { | |
public ConvertDocToTxt() { | |
mIsSkipText = false; | |
mBuilder = new StringBuilder(); | |
} | |
/// <summary> | |
/// Gets the plain text of the document that was accumulated by the visitor. | |
/// </summary> | |
public String getText() { | |
return mBuilder.toString(); | |
} | |
/// <summary> | |
/// Called when a Run node is encountered in the document. | |
/// </summary> | |
public int visitRun(Run run) { | |
appendText(run.getText()); | |
// Let the visitor continue visiting other nodes. | |
return VisitorAction.CONTINUE; | |
} | |
/// <summary> | |
/// Called when a FieldStart node is encountered in the document. | |
/// </summary> | |
public int visitFieldStart(FieldStart 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> | |
public int visitFieldSeparator(FieldSeparator 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> | |
public int visitFieldEnd(FieldEnd 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> | |
public int visitParagraphEnd(Paragraph paragraph) { | |
// When outputting to plain text we output Cr+Lf characters. | |
appendText(ControlChar.CR_LF); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitBodyStart(Body 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("*** Body Started ***\r\n"); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitBodyEnd(Body body) { | |
mBuilder.append("*** Body Ended ***\r\n"); | |
return VisitorAction.CONTINUE; | |
} | |
/// <summary> | |
/// Called when a HeaderFooter node is encountered in the document. | |
/// </summary> | |
public int visitHeaderFooterStart(HeaderFooter 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.SKIP_THIS_NODE; | |
} | |
/// <summary> | |
/// Adds text to the current output. Honors the enabled/disabled output flag. | |
/// </summary> | |
private void appendText(String text) { | |
if (!mIsSkipText) | |
mBuilder.append(text); | |
} | |
private StringBuilder mBuilder; | |
private boolean mIsSkipText; | |
} |
צילום טקסט רק רק רק
הדרכים להחזיר טקסט מן המסמך הן:
- שימוש Document.save עם SaveFormat כדי לשמור טקסט רגיל לתוך קובץ או זרם
- שימוש Node.toString ולהעביר את
SaveFormat.Text
פרמטר באופן פנימי, זה הופך את הטקסט לזרם זיכרון ומחזיר את המחרוזת וכתוצאה מכך - שימוש Node.getText לשלוח טקסט עם הכל Microsoft Word דמויות בקרה כולל קודים שדה
- יישום מותאם אישית DocumentVisitor ביצוע מיצוי מותאם אישית
שימוש Node.GetText
ו Node.ToString
A A A מסמך Word יכול להכיל דמויות שליטה המתכנן אלמנטים מיוחדים כגון שדה, סוף התא, סוף סעיף וכו ‘. הרשימה המלאה של דמויות בקרת מילים אפשריות מוגדרת ב ControlChar מעמד. The The The GetText השיטה מחזירה טקסט עם כל דמויות הדמות השולטות הקיימות בצומת.
קריאה לString מחזירה את ייצוג הטקסט הפשוט של המסמך רק ללא דמויות שליטה. למידע נוסף על ייצוא כטקסט רגיל Using SaveFormat.Text.
הדוגמה הבאה מציגה את ההבדל בין קריאה GetText ו ToString שיטות על צומת:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertField("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. | |
System.out.println("ToString() Result: " + doc.toString(SaveFormat.TEXT)); |
שימוש SaveFormat.Text
דוגמה זו מצילה את המסמך כדלקמן:
- מסננים החוצה דמויות שדה וקודי שדה, צורה, הערה, הערות והערות
- סוף סעיף ControlChar.Cr דמויות עם ControlChar.CrLf שילוב
- שימוש ב UTF8 encoding
דוגמה לקוד הבא מראה כיצד לשמור מסמך בפורמט TXT:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Document.docx"); | |
doc.save(getArtifactsDir() + "BaseConversions.DocxToTxt.txt"); |
צילום: Shapes
ייתכן שתצטרך להפיק תמונות מסמך כדי לבצע משימות מסוימות. Aspose.Words מאפשר לך לעשות זאת גם.
לדוגמה הקוד הבא מראה כיצד להפיק תמונות ממסמכים:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Images.docx"); | |
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true); | |
int imageIndex = 0; | |
for (Shape shape : (Iterable<Shape>) shapes) { | |
if (shape.hasImage()) { | |
String imageFileName = | |
MessageFormat.format("Image.ExportImages.{0}_{1}", imageIndex, FileFormatUtil.imageTypeToExtension(shape.getImageData().getImageType())); | |
// 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.getImageData().save(getArtifactsDir() + imageFileName); | |
imageIndex++; | |
} | |
} |