Esempio n. 1
0
        //ExStart
        //ExFor:Font.Hidden
        //ExFor:Paragraph.Accept
        //ExFor:DocumentVisitor.VisitParagraphStart(Aspose.Words.Paragraph)
        //ExFor:DocumentVisitor.VisitFormField(Aspose.Words.Fields.FormField)
        //ExFor:DocumentVisitor.VisitTableEnd(Aspose.Words.Tables.Table)
        //ExFor:DocumentVisitor.VisitCellEnd(Aspose.Words.Tables.Cell)
        //ExFor:DocumentVisitor.VisitRowEnd(Aspose.Words.Tables.Row)
        //ExFor:DocumentVisitor.VisitSpecialChar(Aspose.Words.SpecialChar)
        //ExFor:DocumentVisitor.VisitGroupShapeStart(Aspose.Words.Drawing.GroupShape)
        //ExFor:DocumentVisitor.VisitShapeStart(Aspose.Words.Drawing.Shape)
        //ExFor:DocumentVisitor.VisitCommentStart(Aspose.Words.Comment)
        //ExFor:DocumentVisitor.VisitFootnoteStart(Aspose.Words.Footnote)
        //ExFor:SpecialChar
        //ExFor:Node.Accept
        //ExFor:Paragraph.ParagraphBreakFont
        //ExFor:Table.Accept
        //ExSummary:Implements the Visitor Pattern to remove all content formatted as hidden from the document.
        public void RemoveHiddenContentFromDocument()
        {
            // Open the document we want to remove hidden content from.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Font.Hidden.doc");

            // Create an object that inherits from the DocumentVisitor class.
            RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

            // This is the well known Visitor pattern. Get the model to accept a visitor.
            // The model will iterate through itself by calling the corresponding methods
            // on the visitor object (this is called visiting).

            // We can run it over the entire the document like so:
            doc.Accept(hiddenContentRemover);

            // Or we can run it on only a specific node.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 4, true);

            para.Accept(hiddenContentRemover);

            // Or over a different type of node like below.
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

            table.Accept(hiddenContentRemover);

            doc.Save(MyDir + "Font.Hidden Out.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);      //ExSkip
        }
Esempio n. 2
0
        public void DeleteAllImagesPreOrder()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Image.SampleImages.doc");
            Assert.AreEqual(6, doc.GetChildNodes(NodeType.Shape, true).Count);

            //ExStart
            //ExFor:Node.NextPreOrder
            //ExSummary:Shows how to delete all images from a document using pre-order tree traversal.
            Aspose.Words.Node curNode = doc;
            while (curNode != null)
            {
                Aspose.Words.Node nextNode = curNode.NextPreOrder(doc);

                if (curNode.NodeType.Equals(NodeType.Shape))
                {
                    Shape shape = (Shape)curNode;

                    // Several shape types can have an image including image shapes and OLE objects.
                    if (shape.HasImage)
                    {
                        shape.Remove();
                    }
                }

                curNode = nextNode;
            }
            //ExEnd

            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Shape, true).Count);
            doc.Save(MyDir + "Image.DeleteAllImagesPreOrder Out.doc");
        }
Esempio n. 3
0
        private void ParseDoc(ref FileObject fo, string filePath)
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(filePath);
            Aspose.Words.Properties.BuiltInDocumentProperties dp = doc.BuiltInDocumentProperties;
            fo.wordCount      = dp.Words;
            fo.characterCount = dp.CharactersWithSpaces;
            fo.pageCount      = dp.Pages;
            fo.hasPassword    = dp.Security == Aspose.Words.Properties.DocumentSecurity.PasswordProtected;

            NodeCollection shapes     = doc.GetChildNodes(NodeType.Shape, true);
            int            NoOfImages = 0;

            foreach (Aspose.Words.Drawing.Shape shape in shapes)
            {
                if (shape.HasImage)
                {
                    NoOfImages++;
                }
            }
            fo.imageCount = NoOfImages;

            NodeCollection embeddedDocs = doc.GetChildNodes(NodeType.SubDocument, true);

            fo.embeddedDocsCount = embeddedDocs.Count;
        }
        public void StretchImagefitSizeLim()
        {
            Aspose.Words.Document doc = DocumentHelper.CreateTemplateDocumentWithDrawObjects("<<image [src.ImageStream] -fitSizeLim>>", ShapeType.TextBox);

            ImageTestClass imageStream = new ImageTestBuilder().WithImageStream(new FileStream(this.mImage, FileMode.Open, FileAccess.Read)).Build();

            BuildReport(doc, imageStream, "src", ReportBuildOptions.None);

            MemoryStream dstStream = new MemoryStream();

            doc.Save(dstStream, SaveFormat.Docx);

            doc = new Aspose.Words.Document(dstStream);
            NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

            foreach (Shape shape in shapes)
            {
                // Assert that the image is really insert in textbox
                Assert.IsTrue(shape.ImageData.HasImage);

                // Assert that textbox size are equal image size
                Assert.AreEqual(346.35, shape.Height);
                Assert.AreEqual(258.54, shape.Width);
            }

            dstStream.Dispose();
        }
Esempio n. 5
0
        public void ChangeStyleIdentifier()
        {
            //ExStart
            //ExFor:Font.StyleIdentifier
            //ExFor:StyleIdentifier
            //ExSummary:Shows how to use style identifier to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Font.StyleIdentifier.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that using StyleIdentifier we can identify a built-in style regardless
                // of the language of Microsoft Word used to create the document.
                if (run.Font.StyleIdentifier.Equals(StyleIdentifier.Emphasis))
                {
                    run.Font.StyleIdentifier = StyleIdentifier.Strong;
                }
            }

            doc.Save(MyDir + "Font.StyleIdentifier Out.doc");
            //ExEnd
        }
Esempio n. 6
0
        public void ChangeStyleName()
        {
            //ExStart
            //ExFor:Font.StyleName
            //ExSummary:Shows how to use style name to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Font.StyleName.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that names of built in styles could be different in documents
                // created by Microsoft Word versions for different languages.
                if (run.Font.StyleName.Equals("Emphasis"))
                {
                    run.Font.StyleName = "Strong";
                }
            }

            doc.Save(MyDir + "Font.StyleName Out.doc");
            //ExEnd
        }
Esempio n. 7
0
        public void ChangeTOCTabStops()
        {
            //ExStart
            //ExFor:TabStop
            //ExFor:ParagraphFormat.TabStops
            //ExFor:Style.StyleIdentifier
            //ExFor:TabStopCollection.RemoveByPosition
            //ExFor:TabStop.Alignment
            //ExFor:TabStop.Position
            //ExFor:TabStop.Leader
            //ExId:ChangeTOCTabStops
            //ExSummary:Shows how to modify the position of the right tab stop in TOC related paragraphs.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.TableOfContents.doc");

            // Iterate through all paragraphs in the document
            foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
            {
                // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
                if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 && para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
                {
                    // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
                    TabStop tab = para.ParagraphFormat.TabStops[0];
                    // Remove the old tab from the collection.
                    para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
                    // Insert a new tab using the same properties but at a modified position.
                    // We could also change the separators used (dots) by passing a different Leader type
                    para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
                }
            }

            doc.Save(MyDir + "Document.TableOfContentsTabStops Out.doc");
            //ExEnd
        }
Esempio n. 8
0
        public void GetAllFonts()
        {
            //ExStart
            //ExFor:Run
            //ExSummary:Gets all fonts used in a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Font.Names.doc");

            // Select all runs in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Use a hashtable so we will keep only unique font names.
            Hashtable fontNames = new Hashtable();

            foreach (Run run in runs)
            {
                // This adds an entry into the hashtable.
                // The key is the font name. The value is null, we don't need the value.
                fontNames[run.Font.Name] = null;
            }

            // There are two fonts used in this document.
            Console.WriteLine("Font Count: " + fontNames.Count);
            //ExEnd

            // Verify the font count is correct.
            Assert.AreEqual(2, fontNames.Count);
        }
Esempio n. 9
0
        /// <summary>
        /// Извлечение текста из документа
        /// </summary>
        /// <param name="bytes">Файл</param>
        /// <param name="extension">Расширение файла</param>
        /// <returns></returns>
        protected override DocumentContent ExtractTextInternal(byte[] bytes, string extension)
        {
            var content = new StringBuilder();
            var result  = new DocumentContent();

            try {
                using (var ms = new MemoryStream(bytes)) {
                    var doc        = new Document(ms, new LoadOptions(GetLoadFormat(extension), null, null));
                    var paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);

                    //NOTE: Не всегда получает только первую страницу. Довольно часто цепляет еще несколько
                    foreach (var node in paragraphs)
                    {
                        var text = node.GetText();

                        if (text.Contains(ControlChar.PageBreak))
                        {
                            var index = text.IndexOf(ControlChar.PageBreak, StringComparison.Ordinal);
                            content.Append(text.Substring(0, index + 1));
                            break;
                        }

                        content.Append(text);
                    }
                }
            } catch (Exception ex) {
                _logger.Error(ex, $"При обработке {extension} возникло исключение");
            }

            result.Content = content.ToString();
            return(result);
        }
Esempio n. 10
0
        public void ChangeTOCTabStops()
        {
            //ExStart
            //ExFor:TabStop
            //ExFor:ParagraphFormat.TabStops
            //ExFor:Style.StyleIdentifier
            //ExFor:TabStopCollection.RemoveByPosition
            //ExFor:TabStop.Alignment
            //ExFor:TabStop.Position
            //ExFor:TabStop.Leader
            //ExId:ChangeTOCTabStops
            //ExSummary:Shows how to modify the position of the right tab stop in TOC related paragraphs.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.TableOfContents.doc");

            // Iterate through all paragraphs in the document
            foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
            {
                // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
                if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 && para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
                {
                    // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
                    TabStop tab = para.ParagraphFormat.TabStops[0];
                    // Remove the old tab from the collection.
                    para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
                    // Insert a new tab using the same properties but at a modified position.
                    // We could also change the separators used (dots) by passing a different Leader type
                    para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
                }
            }

            doc.Save(ExDir + "Document.TableOfContentsTabStops Out.doc");
            //ExEnd
        }
Esempio n. 11
0
        //ExStart
        //ExFor:Node.GetAncestor(NodeType)
        //ExFor:Table.NodeType
        //ExFor:Cell.Tables
        //ExFor:TableCollection
        //ExFor:NodeCollection.Count
        //ExSummary:Shows how to find out if a table contains another table or if the table itself is nested inside another table.
        public void CalcuateDepthOfNestedTables()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.NestedTables.doc");
            int tableIndex            = 0;

            foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
            {
                // First lets find if any cells in the table have tables themselves as children.
                int count = GetChildTableCount(table);
                Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

                // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
                int tableDepth = GetNestedDepthOfTable(table);

                if (tableDepth > 0)
                {
                    Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex, tableDepth);
                }
                else
                {
                    Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);
                }

                tableIndex++;
            }
        }
Esempio n. 12
0
 private List <NavigationPaneItem> PrepareNavigationPaneList(Document doc, LayoutCollector lc)
 {
     try
     {
         var lst = new List <NavigationPaneItem>();
         foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
         {
             switch (para.ParagraphFormat.StyleIdentifier)
             {
             case StyleIdentifier.Subtitle:
             case StyleIdentifier.Title:
             case StyleIdentifier.Heading3:
             case StyleIdentifier.Heading2:
             case StyleIdentifier.Heading1:
                 var text = para.Range.Text;
                 if (text.Count(char.IsLetterOrDigit) > 0)
                 {
                     lst.Add(new NavigationPaneItem(text, para.ParagraphFormat.StyleIdentifier, lc.GetStartPageIndex(para)));
                 }
                 break;
             }
         }
         return(lst);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(null);
     }
 }
Esempio n. 13
0
        public void Style()
        {
            //ExStart
            //ExFor:Font.Style
            //ExFor:Style.BuiltIn
            //ExSummary:Applies double underline to all runs in a document that are formatted with custom character styles.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Font.Style.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                Aspose.Words.Style charStyle = run.Font.Style;

                // If the style of the run is not a built-in character style, apply double underline.
                if (!charStyle.BuiltIn)
                {
                    run.Font.Underline = Underline.Double;
                }
            }

            doc.Save(MyDir + "Font.Style Out.doc");
            //ExEnd
        }
        //ExEnd

        private void TestResourceLoadingCallback(Document doc)
        {
            foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
            {
                Assert.IsTrue(shape.HasImage);
                Assert.IsNotEmpty(shape.ImageData.ImageBytes);
            }

            TestUtil.VerifyWebResponseStatusCode(HttpStatusCode.OK, "http://www.google.com/images/logos/ps_logo2.png");
        }
Esempio n. 15
0
        protected void rptCampaign_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Export")
            {
                var             campaignId = Convert.ToInt32(e.CommandArgument);
                var             campaign   = GoldenDayListCampaignBLL.CampaginGetById(campaignId);
                MemoryStream    mem        = new MemoryStream();
                var             document   = new Aspose.Words.Document(Server.MapPath("/Modules/Sails/Admin/ExportTemplates/Golden_Days_Form.doc"));
                DocumentBuilder builder    = new DocumentBuilder(document);
                document.Range.Replace("{Month}", campaign.Month.ToString("0#"), false, false);
                document.Range.Replace("{Year}", campaign.Year.ToString(), false, false);
                NodeCollection tables = document.GetChildNodes(NodeType.Table, true);
                var            table  = tables[0] as Aspose.Words.Tables.Table;
                for (var i = table.Rows.Count - 1; i > 1; i--)
                {
                    table.Rows.RemoveAt(i);
                }

                foreach (var goldenDay in campaign.GoldenDays)
                {
                    var cloneOfRow = (Row)table.Rows[1].Clone(true);
                    cloneOfRow.Cells[0].RemoveAllChildren();
                    cloneOfRow.Cells[0].AppendChild(new Paragraph(document));
                    cloneOfRow.Cells[0].FirstParagraph.AppendChild(new Run(document, goldenDay.Date.ToString("dd MMM")));
                    cloneOfRow.Cells[1].RemoveAllChildren();
                    cloneOfRow.Cells[1].AppendChild(new Paragraph(document));
                    cloneOfRow.Cells[1].FirstParagraph.AppendChild(new Run(document, goldenDay.Policy != null ? goldenDay.Policy.Replace("\n", ControlChar.LineBreak) : ""));
                    table.Rows.Insert(table.Rows.Count, cloneOfRow);
                }
                table.Rows.RemoveAt(1);
                document.Save(mem, Aspose.Words.SaveFormat.Docx);
                Response.Clear();
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.ContentType     = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                var fileName = string.Format("\"{0}.docx\"", campaign.Name);
                Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
                mem.Position = 0;
                byte[] buffer = mem.ToArray();
                Response.BinaryWrite(buffer);
                Response.End();
            }
            if (e.CommandName == "Delete")
            {
                var campaignId = 0;
                try
                {
                    campaignId = Convert.ToInt32(e.CommandArgument);
                }
                catch { }
                var campaign = GoldenDayListCampaignBLL.CampaginGetById(campaignId);
                GoldenDayListCampaignBLL.CampaignDelete(campaign);
                Response.Redirect(Request.RawUrl);
            }
        }
Esempio n. 16
0
        private static void RemoveTableOfContents(Aspose.Words.Document doc, int index)
        {
            // Store the FieldStart nodes of TOC fields in the document for quick access.
            ArrayList fieldStarts = new ArrayList();
            // This is a list to store the nodes found inside the specified TOC. They will be removed
            // at the end of this method.
            ArrayList nodeList = new ArrayList();

            foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true))
            {
                if (start.FieldType == FieldType.FieldTOC)
                {
                    // Add all FieldStarts which are of type FieldTOC.
                    fieldStarts.Add(start);
                }
            }

            // Ensure the TOC specified by the passed index exists.
            if (index > fieldStarts.Count - 1)
            {
                throw new ArgumentOutOfRangeException("TOC index is out of range");
            }

            bool isRemoving = true;
            // Get the FieldStart of the specified TOC.
            Node currentNode = (Node)fieldStarts[index];

            while (isRemoving)
            {
                // It is safer to store these nodes and delete them all at once later.
                nodeList.Add(currentNode);
                currentNode = currentNode.NextPreOrder(doc);

                // Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end
                // of the current TOC and we can stop here.
                if (currentNode.NodeType == NodeType.FieldEnd)
                {
                    FieldEnd fieldEnd = (FieldEnd)currentNode;
                    if (fieldEnd.FieldType == FieldType.FieldTOC)
                    {
                        isRemoving = false;
                    }
                }
            }

            // Remove all nodes found in the specified TOC.
            foreach (Node node in nodeList)
            {
                node.Remove();
            }
        }
Esempio n. 17
0
        public void DisplayContentOfTables()
        {
            //ExStart
            //ExFor:Table
            //ExFor:Row.Cells
            //ExFor:Table.Rows
            //ExFor:Cell
            //ExFor:Row
            //ExFor:RowCollection
            //ExFor:CellCollection
            //ExFor:NodeCollection.IndexOf(Node)
            //ExSummary:Shows how to iterate through all tables in the document and display the content from each cell.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.Document.doc");

            // Here we get all tables from the Document node. You can do this for any other composite node
            // which can contain block level nodes. For example you can retrieve tables from header or from a cell
            // containing another table (nested tables).
            NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

            // Iterate through all tables in the document
            foreach (Table table in tables)
            {
                // Get the index of the table node as contained in the parent node of the table
                int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
                Console.WriteLine("Start of Table {0}", tableIndex);

                // Iterate through all rows in the table
                foreach (Row row in table.Rows)
                {
                    int rowIndex = table.Rows.IndexOf(row);
                    Console.WriteLine("\tStart of Row {0}", rowIndex);

                    // Iterate through all cells in the row
                    foreach (Cell cell in row.Cells)
                    {
                        int cellIndex = row.Cells.IndexOf(cell);
                        // Get the plain text content of this cell.
                        string cellText = cell.ToString(SaveFormat.Text).Trim();
                        // Print the content of the cell.
                        Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
                    }
                    //Console.WriteLine();
                    Console.WriteLine("\tEnd of Row {0}", rowIndex);
                }
                Console.WriteLine("End of Table {0}", tableIndex);
                Console.WriteLine();
            }
            //ExEnd

            Assert.Greater(tables.Count, 0);
        }
Esempio n. 18
0
        public void DeleteAllShapes()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Shape.DeleteAllShapes.doc");

            //ExStart
            //ExFor:Shape
            //ExSummary:Shows how to delete all shapes from a document.
            // Here we get all shapes from the document node, but you can do this for any smaller
            // node too, for example delete shapes from a single section or a paragraph.
            NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

            shapes.Clear();

            // There could also be group shapes, they have different node type, remove them all too.
            NodeCollection groupShapes = doc.GetChildNodes(NodeType.GroupShape, true);

            groupShapes.Clear();
            //ExEnd

            Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);
            Assert.AreEqual(0, doc.GetChildNodes(NodeType.GroupShape, true).Count);
            doc.Save(MyDir + "Shape.DeleteAllShapes Out.doc");
        }
Esempio n. 19
0
        public void ReplaceTextboxesWithImages()
        {
            //ExStart
            //ExFor:WrapSide
            //ExFor:ShapeBase.WrapSide
            //ExFor:NodeCollection
            //ExFor:CompositeNode.InsertAfter(Node, Node)
            //ExFor:NodeCollection.ToArray
            //ExSummary:Shows how to replace all textboxes with images.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

            // This gets a live collection of all shape nodes in the document.
            NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

            // Since we will be adding/removing nodes, it is better to copy all collection
            // into a fixed size array, otherwise iterator will be invalidated.
            Aspose.Words.Node[] shapes = shapeCollection.ToArray();

            foreach (Shape shape in shapes)
            {
                // Filter out all shapes that we don't need.
                if (shape.ShapeType.Equals(ShapeType.TextBox))
                {
                    // Create a new shape that will replace the existing shape.
                    Shape image = new Shape(doc, ShapeType.Image);

                    // Load the image into the new shape.
                    image.ImageData.SetImage(MyDir + "Hammer.wmf");

                    // Make new shape's position to match the old shape.
                    image.Left   = shape.Left;
                    image.Top    = shape.Top;
                    image.Width  = shape.Width;
                    image.Height = shape.Height;
                    image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
                    image.RelativeVerticalPosition   = shape.RelativeVerticalPosition;
                    image.HorizontalAlignment        = shape.HorizontalAlignment;
                    image.VerticalAlignment          = shape.VerticalAlignment;
                    image.WrapType = shape.WrapType;
                    image.WrapSide = shape.WrapSide;

                    // Insert new shape after the old shape and remove the old shape.
                    shape.ParentNode.InsertAfter(image, shape);
                    shape.Remove();
                }
            }

            doc.Save(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
            //ExEnd
        }
Esempio n. 20
0
        public void DeleteAllImages()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Image.SampleImages.doc");
            Assert.AreEqual(6, doc.GetChildNodes(NodeType.Shape, true).Count);

            //ExStart
            //ExFor:Shape.HasImage
            //ExFor:Node.Remove
            //ExSummary:Shows how to delete all images from a document.
            // Here we get all shapes from the document node, but you can do this for any smaller
            // node too, for example delete shapes from a single section or a paragraph.
            NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

            // We cannot delete shape nodes while we enumerate through the collection.
            // One solution is to add nodes that we want to delete to a temporary array and delete afterwards.
            ArrayList shapesToDelete = new ArrayList();

            foreach (Shape shape in shapes)
            {
                // Several shape types can have an image including image shapes and OLE objects.
                if (shape.HasImage)
                {
                    shapesToDelete.Add(shape);
                }
            }

            // Now we can delete shapes.
            foreach (Shape shape in shapesToDelete)
            {
                shape.Remove();
            }
            //ExEnd

            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Shape, true).Count);
            doc.Save(MyDir + "Image.DeleteAllImages Out.doc");
        }
Esempio n. 21
0
        /// <summary>
        /// 追加表格
        /// </summary>
        /// <param name="tableIndex"></param>
        /// <param name="dt"></param>
        /// <param name="widthLst"></param>
        /// <returns></returns>
        public bool AddTable(int tableIndex, System.Data.DataTable dt, List <double> widthLst)
        {
            NodeCollection allTables = _Doc.GetChildNodes(NodeType.Table, true);                  //拿到所有表格

            Aspose.Words.Tables.Table table = allTables[tableIndex] as Aspose.Words.Tables.Table; //拿到第tableIndex个表格
            for (int row = 0; row < dt.Rows.Count; row++)
            {
                Aspose.Words.Tables.Row r = new Aspose.Words.Tables.Row(_Doc);
                var newRow = CreateRow(dt.Columns.Count, dt.Rows[row].ItemArray, _Doc, widthLst); //创建一行

                table.Rows.Add(newRow);                                                           //添加一行
            }

            return(true);
        }
Esempio n. 22
0
        /// <summary>
        /// Извлечение текста из картинок в документе
        /// </summary>
        /// <param name="bytes">Файл</param>
        /// <param name="extension">Расширение файла</param>
        /// <returns></returns>
        protected override async Task <DocumentContent> ExtractImageTextInternal(byte[] bytes, string extension)
        {
            var content = new StringBuilder();
            var result  = new DocumentContent();

            try {
                using (var ms = new MemoryStream(bytes)) {
                    var doc = new Document(ms, new LoadOptions(GetLoadFormat(extension), null, null));

                    foreach (var node in doc.GetChildNodes(NodeType.Shape, true))
                    {
                        var shape = (Shape)node;
                        if (!shape.HasImage || shape.ImageData.ImageBytes == null || shape.ImageData.ImageBytes.Length == 8818)
                        {
                            continue;
                        }

                        string extractTextImage;
                        if (shape.ImageData.ImageType == ImageType.Emf)
                        {
                            using (var imageBytes = new MemoryStream()) {
                                shape.GetShapeRenderer().Save(imageBytes, new ImageSaveOptions(SaveFormat.Png));
                                extractTextImage = await _imageExtractor.ExtractTextImage(imageBytes.ToArray());
                            }
                        }
                        else
                        {
                            extractTextImage = await _imageExtractor.ExtractTextImage(shape.ImageData.ImageBytes);
                        }

                        if (string.IsNullOrWhiteSpace(extractTextImage))
                        {
                            var image = shape.ImageData.ToImage();
                            extractTextImage = await _imageExtractor.ExtractTextImage(image.Bytes);
                        }

                        content.Append(extractTextImage);
                        result.HasImageContent = true;
                    }
                }
            } catch (Exception ex) {
                _logger.Error(ex, $"При обработке {extension} возникло исключение");
            }

            result.Content = content.ToString();
            return(result);
        }
Esempio n. 23
0
        public static ArrayList RunsByStyleName(Aspose.Words.Document doc, string styleName)
        {
            // Create an array to collect runs of the specified style.
            ArrayList runsWithStyle = new ArrayList();
            // Get all runs from the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Look through all runs to find those with the specified style.
            foreach (Run run in runs)
            {
                if (run.Font.Style.Name == styleName)
                {
                    runsWithStyle.Add(run);
                }
            }
            return(runsWithStyle);
        }
Esempio n. 24
0
        public static ArrayList ParagraphsByStyleName(Aspose.Words.Document doc, string styleName)
        {
            // Create an array to collect paragraphs of the specified style.
            ArrayList paragraphsWithStyle = new ArrayList();
            // Get all paragraphs from the document.
            NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);

            // Look through all paragraphs to find those with the specified style.
            foreach (Paragraph paragraph in paragraphs)
            {
                if (paragraph.ParagraphFormat.Style.Name == styleName)
                {
                    paragraphsWithStyle.Add(paragraph);
                }
            }
            return(paragraphsWithStyle);
        }
Esempio n. 25
0
        /// <summary>
        /// doc清洁方法
        /// </summary>
        /// <param name="srcBytes">doc源二进制数据</param>
        /// <param name="extension"></param>
        /// <returns></returns>
        public static byte[] CleanDoc(byte[] srcBytes, string extension)
        {
            // 参数验证
            if (srcBytes == null)
            {
                throw new InvalidDataException();
            }
            if (string.IsNullOrEmpty(extension))
            {
                throw new InvalidDataException();
            }

            byte[] result    = null;
            Stream docStream = new System.IO.MemoryStream(srcBytes);

            Aspose.Words.Document doc = new Aspose.Words.Document(docStream);

            // 接受全部修订
            doc.AcceptAllRevisions();

            //StyleCollection styleCollection=

            //清除批注
            NodeCollection nodeCollection = doc.GetChildNodes(NodeType.Comment, true);

            foreach (Node comment in nodeCollection)
            {
                nodeCollection.Remove(comment);
            }

            //二进制另存
            using (MemoryStream ms = new MemoryStream())
            {
                if (extension == ".docx" || extension == "docx")
                {
                    doc.Save(ms, SaveFormat.Docx);
                    result = ms.ToArray();
                }
                if (extension == ".doc" || extension == "doc")
                {
                    doc.Save(ms, SaveFormat.Doc);
                    result = ms.ToArray();
                }
            }
            return(result);
        }
        public void RenameMergeFields()
        {
            // Specify your document name here.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "RenameMergeFields.doc");

            // Select all field start nodes so we can find the merge fields.
            NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
            foreach (FieldStart fieldStart in fieldStarts)
            {
                if (fieldStart.FieldType.Equals(FieldType.FieldMergeField))
                {
                    MergeField mergeField = new MergeField(fieldStart);
                    mergeField.Name = mergeField.Name + "_Renamed";
                }
            }

            doc.Save(MyDir + "RenameMergeFields Out.doc");
        }
Esempio n. 27
0
        [Test] //ExSkip
        public void ExtractImagesToFiles()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Image.SampleImages.doc");

            NodeCollection shapes     = doc.GetChildNodes(NodeType.Shape, true);
            int            imageIndex = 0;

            foreach (Shape shape in shapes)
            {
                if (shape.HasImage)
                {
                    string imageFileName = string.Format(
                        "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
                    shape.ImageData.Save(MyDir + imageFileName);
                    imageIndex++;
                }
            }
        }
Esempio n. 28
0
        public static ArrayList GetNodesByPage(int page, Aspose.Words.Document document)
        {
            ArrayList nodes = new ArrayList();

            LayoutCollector lc = new LayoutCollector(document);



            foreach (Paragraph para in document.GetChildNodes(NodeType.Paragraph, true))
            {
                if (lc.GetStartPageIndex(para) == page)
                {
                    nodes.Add(para);
                }
            }

            return(nodes);
        }
Esempio n. 29
0
        //ExStart
        //ExId:TextboxToTable
        //ExSummary:Shows how to convert a textbox to a table and retain almost identical formatting. This is useful for HTML export.
        public void ConvertTextboxToTable()
        {
            // Open the document
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Shape.Textbox.doc");

            // Convert all shape nodes which contain child nodes.
            // We convert the collection to an array as static "snapshot" because the original textboxes will be removed after conversion which will
            // invalidate the enumerator.
            foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).ToArray())
            {
                if (shape.HasChildNodes)
                {
                    ConvertTextboxToTable(shape);
                }
            }

            doc.Save(MyDir + "Table.ConvertTextboxToTable Out.html");
        }
Esempio n. 30
0
        [Test] //ExSkip
        public void RenameMergeFields()
        {
            // Specify your document name here.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "RenameMergeFields.doc");

            // Select all field start nodes so we can find the merge fields.
            NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);

            foreach (FieldStart fieldStart in fieldStarts)
            {
                if (fieldStart.FieldType.Equals(FieldType.FieldMergeField))
                {
                    MergeField mergeField = new MergeField(fieldStart);
                    mergeField.Name = mergeField.Name + "_Renamed";
                }
            }

            doc.Save(MyDir + "RenameMergeFields Out.doc");
        }
        [Test] //ExSkip
        public void ResourceLoadingCallback()
        {
            Document doc = new Document();

            doc.ResourceLoadingCallback = new ImageNameHandler();

            DocumentBuilder builder = new DocumentBuilder(doc);

            // Images usually are inserted using a URI, or a byte array.
            // Every instance of a resource load will call our callback's ResourceLoading method.
            builder.InsertImage("Google logo");
            builder.InsertImage("Aspose logo");
            builder.InsertImage("Watermark");

            Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

            doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
            TestResourceLoadingCallback(new Document(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx")); //ExSkip
        }
Esempio n. 32
0
        public void SplitTable()
        {
            //ExStart
            //ExId:SplitTableAtRow
            //ExSummary:Shows how to split a table into two tables a specific row.
            // Load the document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.SimpleTable.doc");

            // Get the first table in the document.
            Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true);

            // We will split the table at the third row (inclusive).
            Row row = firstTable.Rows[2];

            // Create a new container for the split table.
            Table table = (Table)firstTable.Clone(false);

            // Insert the container after the original.
            firstTable.ParentNode.InsertAfter(table, firstTable);

            // Add a buffer paragraph to ensure the tables stay apart.
            firstTable.ParentNode.InsertAfter(new Paragraph(doc), firstTable);

            Row currentRow;

            do
            {
                currentRow = firstTable.LastRow;
                table.PrependChild(currentRow);
            }while (currentRow != row);

            doc.Save(MyDir + "Table.SplitTable Out.doc");
            //ExEnd

            doc = new Aspose.Words.Document(MyDir + "Table.SplitTable Out.doc");
            // Test we are adding the rows in the correct order and the
            // selected row was also moved.
            Assert.AreEqual(row, table.FirstRow);

            Assert.AreEqual(2, firstTable.Rows.Count);
            Assert.AreEqual(2, table.Rows.Count);
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count);
        }
Esempio n. 33
0
        public void CheckShapeInline()
        {
            //ExStart
            //ExFor:ShapeBase.IsInline
            //ExSummary:Shows how to test if a shape in the document is inline or floating.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Shape.DeleteAllShapes.doc");

            foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
            {
                if(shape.IsInline)
                    Console.WriteLine("Shape is inline.");
                else
                    Console.WriteLine("Shape is floating.");
            }

            //ExEnd

            // Verify that the first shape in the document is not inline.
            Assert.False(((Shape)doc.GetChild(NodeType.Shape, 0, true)).IsInline);
        }
Esempio n. 34
0
        public void AddComment()
        {
            //ExStart
            //ExFor:Comment
            //ExFor:InlineStory
            //ExFor:InlineStory.Paragraphs
            //ExFor:InlineStory.FirstParagraph
            //ExFor:Comment.#ctor(DocumentBase, String, String, DateTime)
            //ExSummary:Shows how to add a comment to a paragraph in the document.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.Write("Some text is added.");

            Aspose.Words.Comment comment = new Aspose.Words.Comment(doc, "Amy Lee", "AL", DateTime.Today);
            builder.CurrentParagraph.AppendChild(comment);
            comment.Paragraphs.Add(new Paragraph(doc));
            comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
            //ExEnd

            Assert.AreEqual("Comment text.\r", (doc.GetChildNodes(NodeType.Comment, true)[0]).GetText());
        }
Esempio n. 35
0
        public void AddFootnote()
        {
            //ExStart
            //ExFor:Footnote
            //ExFor:InlineStory
            //ExFor:InlineStory.Paragraphs
            //ExFor:InlineStory.FirstParagraph
            //ExFor:FootnoteType
            //ExFor:Footnote.#ctor
            //ExSummary:Shows how to add a footnote to a paragraph in the document.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.Write("Some text is added.");

            Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
            builder.CurrentParagraph.AppendChild(footnote);
            footnote.Paragraphs.Add(new Paragraph(doc));
            footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
            //ExEnd

            Assert.AreEqual("Footnote text.", doc.GetChildNodes(NodeType.Footnote, true)[0].ToString(SaveFormat.Text).Trim());
        }
Esempio n. 36
0
        //ExStart
        //ExFor:Node.GetAncestor(NodeType)
        //ExFor:Table.NodeType
        //ExFor:Cell.Tables
        //ExFor:TableCollection
        //ExFor:NodeCollection.Count
        //ExSummary:Shows how to find out if a table contains another table or if the table itself is nested inside another table.
        public void CalcuateDepthOfNestedTables()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.NestedTables.doc");
            int tableIndex = 0;

            foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
            {
                // First lets find if any cells in the table have tables themselves as children.
                int count = GetChildTableCount(table);
                Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

                // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
                int tableDepth = GetNestedDepthOfTable(table);

                if (tableDepth > 0)
                    Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex, tableDepth);
                else
                    Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);

                tableIndex++;
            }
        }
Esempio n. 37
0
        public void GetIndexOfTableElements()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.Document.doc");

            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
            //ExStart
            //ExFor:NodeCollection.IndexOf
            //ExId:IndexOfTable
            //ExSummary:Retrieves the index of a table in the document.
            NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
            int tableIndex = allTables.IndexOf(table);
            //ExEnd

            Row row = table.Rows[2];
            //ExStart
            //ExFor:Row
            //ExFor:CompositeNode.IndexOf
            //ExId:IndexOfRow
            //ExSummary:Retrieves the index of a row in a table.
            int rowIndex = table.IndexOf(row);
            //ExEnd

            Cell cell = row.LastCell;
            //ExStart
            //ExFor:Cell
            //ExFor:CompositeNode.IndexOf
            //ExId:IndexOfCell
            //ExSummary:Retrieves the index of a cell in a row.
            int cellIndex = row.IndexOf(cell);
            //ExEnd

            Assert.AreEqual(0, tableIndex);
            Assert.AreEqual(2, rowIndex);
            Assert.AreEqual(4, cellIndex);
        }
Esempio n. 38
0
        //ExStart
        //ExId:TextboxToTable
        //ExSummary:Shows how to convert a textbox to a table and retain almost identical formatting. This is useful for HTML export.
        public void ConvertTextboxToTable()
        {
            // Open the document
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Shape.Textbox.doc");

            // Convert all shape nodes which contain child nodes.
            // We convert the collection to an array as static "snapshot" because the original textboxes will be removed after conversion which will
            // invalidate the enumerator.
            foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).ToArray())
            {
                if (shape.HasChildNodes)
                {
                    ConvertTextboxToTable(shape);
                }
            }

            doc.Save(ExDir + "Table.ConvertTextboxToTable Out.html");
        }
Esempio n. 39
0
        public void JoinRunsWithSameFormatting()
        {
            //ExStart
            //ExFor:Document.JoinRunsWithSameFormatting
            //ExSummary:Shows how to join runs in a document to reduce unneeded runs.
            // Let's load this particular document. It contains a lot of content that has been edited many times.
            // This means the document will most likely contain a large number of runs with duplicate formatting.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            // This is for illustration purposes only, remember how many run nodes we had in the original document.
            int runsBefore = doc.GetChildNodes(NodeType.Run, true).Count;

            // Join runs with the same formatting. This is useful to speed up processing and may also reduce redundant
            // tags when exporting to HTML which will reduce the output file size.
            int joinCount = doc.JoinRunsWithSameFormatting();

            // This is for illustration purposes only, see how many runs are left after joining.
            int runsAfter = doc.GetChildNodes(NodeType.Run, true).Count;

            Console.WriteLine("Number of runs before:{0}, after:{1}, joined:{2}", runsBefore, runsAfter, joinCount);

            // Save the optimized document to disk.
            doc.Save(MyDir + "Document.JoinRunsWithSameFormatting Out.html");
            //ExEnd

            // Verify that runs were joined in the document.
            Assert.Less(runsAfter, runsBefore);
            Assert.AreNotEqual(0, joinCount);
        }
Esempio n. 40
0
        public void SplitTable()
        {
            //ExStart
            //ExId:SplitTableAtRow
            //ExSummary:Shows how to split a table into two tables a specific row.
            // Load the document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.SimpleTable.doc");

            // Get the first table in the document.
            Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true);

            // We will split the table at the third row (inclusive).
            Row row = firstTable.Rows[2];

            // Create a new container for the split table.
            Table table = (Table)firstTable.Clone(false);

            // Insert the container after the original.
            firstTable.ParentNode.InsertAfter(table, firstTable);

            // Add a buffer paragraph to ensure the tables stay apart.
            firstTable.ParentNode.InsertAfter(new Paragraph(doc), firstTable);

            Row currentRow;

            do
            {
                currentRow = firstTable.LastRow;
                table.PrependChild(currentRow);
            }
            while (currentRow != row);

            doc.Save(ExDir + "Table.SplitTable Out.doc");
            //ExEnd

            doc = new Aspose.Words.Document(ExDir + "Table.SplitTable Out.doc");
            // Test we are adding the rows in the correct order and the
            // selected row was also moved.
            Assert.AreEqual(row, table.FirstRow);

            Assert.AreEqual(2, firstTable.Rows.Count);
            Assert.AreEqual(2, table.Rows.Count);
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count);
        }
Esempio n. 41
0
        public void Style()
        {
            //ExStart
            //ExFor:Font.Style
            //ExFor:Style.BuiltIn
            //ExSummary:Applies double underline to all runs in a document that are formatted with custom character styles.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Style.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                Aspose.Words.Style charStyle = run.Font.Style;

                // If the style of the run is not a built-in character style, apply double underline.
                if (!charStyle.BuiltIn)
                    run.Font.Underline = Underline.Double;
            }

            doc.Save(ExDir + "Font.Style Out.doc");
            //ExEnd
        }
        static void Main(string[] args)
        {
            stopwatch.Start();

            writeToLog("Application PDBOT Started...");
            Console.WriteLine("Application PDBOT Started...");

            //license details
            Aspose.Words.License asposeWordsLicense = new Aspose.Words.License();
            asposeWordsLicense.SetLicense("Aspose.Words.lic");
            Aspose.Pdf.License asposePdfLisence = new Aspose.Pdf.License();
            asposePdfLisence.SetLicense("Aspose.Pdf.lic");

            string hflDocumentPath = null;
            string path = @"C:\Users\51210\Desktop\Customers\SG Finans\Oppgraderings Prosjekt SG Finans\BL0019\pdbot_control.xml";
            XmlDocument controlXMl = null;
            XmlNamespaceManager nsmngr = null;

            //Lists for saving values from control xml
            List<string> documentKeyswordsList = null;
            List<string> globalsKeywordsList = null;
            Aspose.Words.Document docTemplate = null;
            //load xml document
            try
            {
                controlXMl = new XmlDocument();
                controlXMl.Load(path);
                nsmngr = new XmlNamespaceManager(controlXMl.NameTable);
                nsmngr.AddNamespace("pdbot", "www.canon.no/pdbot");

                writeToLog("Control xml loaded successfuly");
            }
            catch (Exception e)
            {
                Console.WriteLine("Application PDBOT failed with error " + e.StackTrace);
                writeToLog("Error loading control xml " + e.StackTrace);
                Console.ReadKey();
            }
            //----------------------------------------------------------------------------------------------------------------------------------

            //get information from control xml nodes
            if (controlXMl != null)
            {
                try
                {
                    //get global document keys and value
                    //select Globals/Keys/Key
                   globalsKeywordsList = new List<string>();
                   XmlNodeList keyNodes = controlXMl.SelectNodes("//pdbot:Globals//pdbot:Keys//pdbot:Key", nsmngr);

                   if (keyNodes.Count != 0)
                   {
                       foreach (XmlNode KeyNode in keyNodes)
                       {
                           string keyword = KeyNode["Keyword"].InnerText;
                           string value = KeyNode["Value"].InnerText;
                           string KeywordAndValue = keyword + "|" + value;
                           globalsKeywordsList.Add(KeywordAndValue);

                       }
                       writeToLog("Global keywords and value read");
                   }
                    //---------------------------------------------------------------------------------------------------------------------------

                    //get Global sections
                    //select Globals/Sections/section
                    List<string> sectionsList = new List<string>();
                    XmlNodeList sectionNodes = controlXMl.SelectNodes("//pdbot:Globals//pdbot:Sections//pdbot:Section", nsmngr);
                    if (sectionNodes.Count != 0)
                    {
                        foreach (XmlNode sectionNode in sectionNodes)
                        {
                            string name = sectionNode["Name"].InnerText;
                            sectionsList.Add(name);

                        }
                        writeToLog("Global Section names read");
                    }
                    //---------------------------------------------------------------------------------------------------------------------------

                    //get all documents in the control xml
                    XmlNodeList documentNodes = controlXMl.SelectNodes("//pdbot:Docs//pdbot:Doc", nsmngr);

                    //get all document information
                    //get document content - Fields, Keys, paragraphkeywords, sections, copies and pagewatermarkings
                    foreach (XmlNode documentNode in documentNodes)
                    {
                       //get document template information
                        List<string> documentFieldsList = new List<string>();
                        string templateFormat = documentNode["TemplateFormat"].InnerText;
                        string repositoryTemplate = documentNode["RepositoryTemplate"].InnerText;
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document field names and value
                        //select Docs/Doc/DocContent/Fields
                        XmlNodeList fieldNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Fields//pdbot:Field", nsmngr);
                        if (fieldNodes.Count != 0)
                        {
                            foreach (XmlNode fieldNode in fieldNodes)
                            {
                                string fieldName = fieldNode["FieldName"].InnerText;
                                string fieldNameValue = fieldNode["Value"].InnerText;

                                string fieldNameWithValue = fieldName + "|" + fieldNameValue;
                                documentFieldsList.Add(fieldNameWithValue);

                            }
                            writeToLog("Document archive fields read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document keywords and value
                        //select Docs/Doc/DocContent/Keys
                        documentKeyswordsList = new List<string>();
                        XmlNodeList docKeyNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Keys//pdbot:Key", nsmngr);
                        if (docKeyNodes.Count != 0)
                        {
                            foreach (XmlNode docKeyNode in docKeyNodes)
                            {
                                string keyword = docKeyNode["Keyword"].InnerText;
                                string value = docKeyNode["Value"].InnerText;
                                string keywordWithValue = keyword + "|" + value;

                                documentKeyswordsList.Add(keywordWithValue);

                            }
                            writeToLog("Document keys read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document paragraphs and value
                        //select Docs/Doc/DocContent/ParagraphKeywords/Paragraph
                        List<string> paragraphKeywordsList = new List<string>();
                        XmlNodeList paragraphNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:ParagraphKeywords//pdbot:Paragraph", nsmngr);
                        if (paragraphNodes.Count != 0)
                        {
                            foreach (XmlNode paragraphNode in paragraphNodes)
                            {
                                string keyword = paragraphNode["Keyword"].InnerText;
                                string value = paragraphNode["Value"].InnerText;
                                string keywordWithValue = keyword + "|" + value;
                                paragraphKeywordsList.Add(keywordWithValue);

                            }
                            writeToLog("Document paragragh keys read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document sections
                        //select Docs/Doc/DocContent/Sections/Section
                        XmlNodeList docSectionNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Sections//pdbot:Section", nsmngr);
                        if (docSectionNodes.Count != 0)
                        {
                            foreach (XmlNode docSectionNode in docSectionNodes)
                            {
                                string name = docSectionNode["Name"].InnerText;

                                if (!sectionsList.Contains(name))
                                {
                                    sectionsList.Add(name);
                                }

                            }
                            writeToLog("Document sections read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get PageWatermarkings
                        //select Docs/Doc/PageWatermarkings/PageWatermarking
                        XmlNode hflPageWatermarkingsNodes = documentNode.SelectSingleNode("pdbot:PageWatermarkings//pdbot:PageWatermarking", nsmngr);
                        hflDocumentPath = hflPageWatermarkingsNodes["ResourceFile"].InnerText;

                        //select Docs/Doc/PageWatermarkings/PageWatermarking/Watermark
                        XmlNodeList pageWatermarkingsNodes = documentNode.SelectNodes("pdbot:PageWatermarkings//pdbot:PageWatermarking//pdbot:Watermark", nsmngr);

                        List<string> waterMarkings = new List<string>();
                        //get watermark values
                        if (pageWatermarkingsNodes.Count != 0)
                        {
                            foreach (XmlNode watermarkNode in pageWatermarkingsNodes)
                            {
                                string wmark = watermarkNode.InnerText;

                                waterMarkings.Add(wmark);
                            }
                            writeToLog("PageWatermarkings dokument variables read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get PageInserts
                        //select Docs/Doc/PageInserts/Inserts
                        XmlNode PageInsertNodes = documentNode.SelectSingleNode("pdbot:PageInserts//pdbot:Inserts", nsmngr);
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get copies information
                        //select Docs/Doc/Copies/Copy
                        List<string> copiesList = new List<string>();
                        XmlNodeList copyNodes = documentNode.SelectNodes("pdbot:Copies//pdbot:Copy", nsmngr);
                        if (copyNodes.Count != 0)
                        {
                            foreach (XmlNode copyNode in copyNodes)
                            {
                                string name = copyNode["Name"].InnerText;
                                string stampText = copyNode["StampText"].InnerText;
                                string flatten = copyNode["Flatten"].InnerText;
                                string outputFile = copyNode["OutputFile"].InnerText;

                                string copyValues = name + "|" + stampText + "|" + flatten + "|" + outputFile;
                                copiesList.Add(copyValues);

                            }
                            writeToLog("Copies document variables read.");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //replace variables from word template with keywords and values
                        //loop through all the fields in the document and replace content with values from control xml:
                        //load word document template
                        try
                        {
                            //Read RepositoryTemplate
                            string keyword = null;
                            string value = null;
                            repositoryTemplate = repositoryTemplate.Replace("xml", "docx");
                            docTemplate = new Aspose.Words.Document(repositoryTemplate);
                            writeToLog("Document template " + docTemplate.OriginalFileName.ToString() + " loaded succesfully");
                            //--------------------------------------------------------------------------------------------------------------------------

                            if (docTemplate != null)
                            {
                                //Remove content controls/sections which will not be used
                                if (sectionsList.Count != 0)
                                {
                                    var ccntrls = docTemplate.GetChildNodes(NodeType.StructuredDocumentTag, true);
                                    foreach (var ccntrl in ccntrls)
                                    {

                                        var sdt = ccntrl as StructuredDocumentTag;
                                        var section = sdt.Title;
                                        if (!sectionsList.Contains(section))
                                        {
                                            sdt.Remove();
                                        }
                                    }
                                    writeToLog("Sections which will not be used in the document removed from template");
                                }
                                //--------------------------------------------------------------------------------------------------------------------------

                                //loop through all the fields in the document and replace content with values from control xml:
                                //replace word template variables/keywords with document values
                                if (documentKeyswordsList.Count != 0)
                                {
                                    foreach (var key in documentKeyswordsList)
                                    {
                                        //split keywords and value
                                        string[] keywordWithValues = key.Split('|');

                                        keyword = keywordWithValues[keywordWithValues.Length - 2];
                                        value = keywordWithValues[keywordWithValues.Length - 1];

                                        //loop through all the fields in the document and replace content with values from control xml:
                                        docTemplate.Range.Replace(keyword, value, false, false);
                                    }
                                    writeToLog("Document template variables replaced with document keywords and values");
                                    //---------------------------------------------------------------------------------------------------------------------------
                                 }

                                //replace word template variables/keywords with global document values
                                if (globalsKeywordsList.Count != 0)
                                {
                                    foreach (var key in globalsKeywordsList)
                                    {
                                        //split keywords and value
                                        string[] keywordWithValues = key.Split('|');

                                        keyword = keywordWithValues[keywordWithValues.Length - 2];
                                        value = keywordWithValues[keywordWithValues.Length - 1];

                                        docTemplate.Range.Replace(keyword, value, false, false);
                                    }
                                    writeToLog("Document template variables replaced with global keywords and values");
                                }
                                //---------------------------------------------------------------------------------------------------------------------------

                                //replace word template paragraphs variables/keywords with document paragraphs values from control xml
                                if (paragraphKeywordsList.Count != 0)
                                {
                                    foreach (var key in paragraphKeywordsList)
                                    {
                                        //split keywords and value
                                        string[] keywordWithValues = key.Split('|');

                                        keyword = keywordWithValues[keywordWithValues.Length - 2];
                                        value = keywordWithValues[keywordWithValues.Length - 1];

                                        //add a line break in paragraphs with line breaks
                                        if (value.Contains(@"\n"))
                                        {
                                            string[] paragraphLines = value.Split('\n');
                                            foreach (var line in paragraphLines)
                                            {
                                                string paragraphText = value.Replace(@"\n", ControlChar.LineBreak);
                                                docTemplate.Range.Replace(keyword, paragraphText, false, false);
                                            }
                                     }
                                        else
                                        {
                                            docTemplate.Range.Replace(keyword, value, false, false);
                                        }
                                    }
                                    writeToLog("Document template paragraph variables replaced with paragraoh keywords and values");
                                }
                                //---------------------------------------------------------------------------------------------------------------------------

                                //Table building!!!!------------------------------------

                               //NB! THIS WILL ONLY WORK WITH TEMPLATE THAT HAS ONLY ONE TABLES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                                //select Docs/Doc/DocContent/table/Row
                                List<string> tableCellKeyList = new List<string>();
                                XmlNodeList rowNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Table//pdbot:Row", nsmngr);
                                if (rowNodes.Count != 0)
                                {
                                    Aspose.Words.Tables.Table table = null;
                                    Aspose.Words.Tables.Row firstRow = null;
                                    foreach (XmlNode rowNode in rowNodes)
                                    {
                                        //select the table to insert rows. 1 represents table no.
                                         table = (Aspose.Words.Tables.Table)docTemplate.GetChild(NodeType.Table, 1, true);
                                        //clone the first table row
                                         firstRow = (Aspose.Words.Tables.Row)table.LastRow.Clone(true);
                                        XmlNodeList cellKeyNodes = rowNode.SelectNodes("pdbot:CellKey", nsmngr);

                                        foreach (XmlNode cellKeyNode in cellKeyNodes)
                                        {
                                            string cellKey = cellKeyNode["Key"].InnerText;
                                            string cellValue = cellKeyNode["Value"].InnerText;

                                            docTemplate.Range.Replace(cellKey, cellValue, false, false);
                                        }
                                        //Insert a new table row after the current row (template row):
                                        table.AppendChild(firstRow);
                                    }
                                    //Delete the last template table row after the table is created
                                    table.LastRow.Remove();

                                }
                                writeToLog("Tabel cell keys and keywords read from control xml and replaced in the document template");
                                //---------------------------------------------------------------------------------------------------------------------------

                                //produce document copies
                                foreach (var copy in copiesList)
                                {
                                    //split copy values
                                    string[] copyValues = copy.Split('|');

                                    string name = copyValues[copyValues.Length - 4];
                                    string stampText = copyValues[copyValues.Length - 3];
                                    string slatten = copyValues[copyValues.Length - 2];
                                    outputFile = copyValues[copyValues.Length - 1];

                                    //manage pagebreaks problem - remove pagebreak and insert sectionbreak - new page
                                    RemovePageBreaks(docTemplate);

                                    ////save document
                                    saveDoc(docTemplate, outputFile);

                                    ////watermark and stamp final document
                                    WaterMarkDocument(outputFile, hflDocumentPath, stampText, waterMarkings);

                                }
                                //---------------------------------------------------------------------------------------------------------------------------

                            }

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Application failed with error " + e.Message + "." + e.StackTrace);
                            writeToLog("Error loading document template " + docTemplate.OriginalFileName.ToString() + "," + e.StackTrace);
                            Console.ReadKey();
                        }

                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine("Application failed with error: " + e.Message + "." + e.StackTrace);
                    writeToLog("Error reading control xml " + e.StackTrace);
                    Console.ReadKey();
                }

                //save pdbot control xml in the same temp folder as the produced documents
                string outputfilename = outputFile.Remove(outputFile.Remove(outputFile.Length - 1).LastIndexOf('\\') + 1);
                outputfilename = outputfilename + "pdbot_control.xml";

                controlXMl.Save(outputfilename);
            }
            controlXMl = null;

            //stopwatch.Stop();
            //Console.WriteLine("Time used: " + stopwatch.Elapsed.Seconds + " Seconds");
            //Console.ReadKey();
            //---------------------------------------------------------------------------------------------------------------------------------------------
        }
Esempio n. 43
0
        public void GetListLabels()
        {
            //ExStart
            //ExFor:Document.UpdateListLabels()
            //ExFor:Node.ToString(SaveFormat)
            //ExFor:ListLabel
            //ExFor:Paragraph.ListLabel
            //ExFor:ListLabel.LabelValue
            //ExFor:ListLabel.LabelString
            //ExSummary:Shows how to extract the label of each paragraph in a list as a value or a string.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Lists.PrintOutAllLists.doc");
            doc.UpdateListLabels();
            int listParaCount = 1;

            foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true))
            {
                // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
                // which start at three and ends at six.
                if (paragraph.ListFormat.IsListItem)
                {
                    Console.WriteLine("Paragraph #{0}", listParaCount);

                    // This is the text we get when actually getting when we output this node to text format.
                    // The list labels are not included in this text output. Trim any paragraph formatting characters.
                    string paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
                    Console.WriteLine("Exported Text: " + paragraphText);

                    ListLabel label = paragraph.ListLabel;
                    // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
                    // will tell us what position it is on that particular level.
                    Console.WriteLine("Numerical Id: " + label.LabelValue);

                    // Combine them together to include the list label with the text in the output.
                    Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

                    listParaCount++;
                }

            }
            //ExEnd
        }
Esempio n. 44
0
        public void NestedTablesUsingNodeConstructors()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // Create the outer table with three rows and four columns.
            Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
            // Add it to the document body.
            doc.FirstSection.Body.AppendChild(outerTable);

            // Create another table with two rows and two columns.
            Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
            // Add this table to the first cell of the outer table.
            outerTable.FirstRow.FirstCell.AppendChild(innerTable);

            doc.Save(ExDir + "Table.CreateNestedTable Out.doc");

            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
            Assert.AreEqual(1, outerTable.FirstRow.FirstCell.Tables.Count); //ExSkip
            Assert.AreEqual(16, outerTable.GetChildNodes(NodeType.Cell, true).Count); //ExSkip
            Assert.AreEqual(4, innerTable.GetChildNodes(NodeType.Cell, true).Count); //ExSkip
        }
Esempio n. 45
0
        public void CloneTable()
        {
            //ExStart
            //ExId:CloneTable
            //ExSummary:Shows how to make a clone of a table in the document and insert it after the original table.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.SimpleTable.doc");

            // Retrieve the first table in the document.
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

            // Create a clone of the table.
            Table tableClone = (Table)table.Clone(true);

            // Insert the cloned table into the document after the original
            table.ParentNode.InsertAfter(tableClone, table);

            // Insert an empty paragraph between the two tables or else they will be combined into one
            // upon save. This has to do with document validation.
            table.ParentNode.InsertAfter(new Paragraph(doc), table);

            doc.Save(ExDir + "Table.CloneTableAndInsert Out.doc");
            //ExEnd

            // Verify that the table was cloned and inserted properly.
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count);
            Assert.AreEqual(table.Range.Text, tableClone.Range.Text);

            //ExStart
            //ExId:CloneTableRemoveContent
            //ExSummary:Shows how to remove all content from the cells of a cloned table.
            foreach (Cell cell in tableClone.GetChildNodes(NodeType.Cell, true))
                cell.RemoveAllChildren();
            //ExEnd

            Assert.AreEqual(String.Empty, tableClone.ToString(SaveFormat.Text).Trim());
        }
Esempio n. 46
0
        public void CombineTables()
        {
            //ExStart
            //ExFor:Table
            //ExFor:Cell.CellFormat
            //ExFor:CellFormat.Borders
            //ExFor:Table.Rows
            //ExFor:Table.FirstRow
            //ExFor:CellFormat.ClearFormatting
            //ExId:CombineTables
            //ExSummary:Shows how to combine the rows from two tables into one.
            // Load the document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.Document.doc");

            // Get the first and second table in the document.
            // The rows from the second table will be appended to the end of the first table.
            Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true);
            Table secondTable = (Table)doc.GetChild(NodeType.Table, 1, true);

            // Append all rows from the current table to the next.
            // Due to the design of tables even tables with different cell count and widths can be joined into one table.
            while (secondTable.HasChildNodes)
                firstTable.Rows.Add(secondTable.FirstRow);

            // Remove the empty table container.
            secondTable.Remove();

            doc.Save(ExDir + "Table.CombineTables Out.doc");
            //ExEnd

            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);
            Assert.AreEqual(9, doc.FirstSection.Body.Tables[0].Rows.Count);
            Assert.AreEqual(42, doc.FirstSection.Body.Tables[0].GetChildNodes(NodeType.Cell, true).Count);
        }
        public void InsertTableFromHtml()
        {
            //ExStart
            //ExId:InsertTableFromHtml
            //ExSummary:Shows how to insert a table in a document from a string containing HTML tags.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Insert the table from HTML. Note that AutoFitSettings does not apply to tables
            // inserted from HTML.
            builder.InsertHtml("<table>"                +
                               "<tr>"                   +
                               "<td>Row 1, Cell 1</td>" +
                               "<td>Row 1, Cell 2</td>" +
                               "</tr>"                  +
                               "<tr>"                   +
                               "<td>Row 2, Cell 2</td>" +
                               "<td>Row 2, Cell 2</td>" +
                               "</tr>"                  +
                               "</table>");

            doc.Save(ExDir + "DocumentBuilder.InsertTableFromHtml Out.doc");
            //ExEnd

            // Verify the table was constructed properly.
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Row, true).Count);
            Assert.AreEqual(4, doc.GetChildNodes(NodeType.Cell, true).Count);
        }
Esempio n. 48
0
        public void DisplayContentOfTables()
        {
            //ExStart
            //ExFor:Table
            //ExFor:Row.Cells
            //ExFor:Table.Rows
            //ExFor:Cell
            //ExFor:Row
            //ExFor:RowCollection
            //ExFor:CellCollection
            //ExFor:NodeCollection.IndexOf(Node)
            //ExSummary:Shows how to iterate through all tables in the document and display the content from each cell.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.Document.doc");

            // Here we get all tables from the Document node. You can do this for any other composite node
            // which can contain block level nodes. For example you can retrieve tables from header or from a cell
            // containing another table (nested tables).
            NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

            // Iterate through all tables in the document
            foreach (Table table in tables)
            {
                // Get the index of the table node as contained in the parent node of the table
                int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
                Console.WriteLine("Start of Table {0}", tableIndex);

                // Iterate through all rows in the table
                foreach (Row row in table.Rows)
                {
                    int rowIndex = table.Rows.IndexOf(row);
                    Console.WriteLine("\tStart of Row {0}", rowIndex);

                    // Iterate through all cells in the row
                    foreach (Cell cell in row.Cells)
                    {
                        int cellIndex = row.Cells.IndexOf(cell);
                        // Get the plain text content of this cell.
                        string cellText = cell.ToString(SaveFormat.Text).Trim();
                        // Print the content of the cell.
                        Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
                    }
                    //Console.WriteLine();
                    Console.WriteLine("\tEnd of Row {0}", rowIndex);
                }
                Console.WriteLine("End of Table {0}", tableIndex);
                Console.WriteLine();
            }
            //ExEnd

            Assert.Greater(tables.Count, 0);
        }
Esempio n. 49
0
        public void ExtractImagesToFiles()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Image.SampleImages.doc");

            NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
            int imageIndex = 0;
            foreach (Shape shape in shapes)
            {
                if (shape.HasImage)
                {
                    string imageFileName = string.Format(
                        "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
                    shape.ImageData.Save(ExDir + imageFileName);
                    imageIndex++;
                }
            }
        }
Esempio n. 50
0
        public void DeleteAllImagesPreOrder()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Image.SampleImages.doc");
            Assert.AreEqual(6, doc.GetChildNodes(NodeType.Shape, true).Count);

            //ExStart
            //ExFor:Node.NextPreOrder
            //ExSummary:Shows how to delete all images from a document using pre-order tree traversal.
            Aspose.Words.Node curNode = doc;
            while (curNode != null)
            {
                Aspose.Words.Node nextNode = curNode.NextPreOrder(doc);

                if (curNode.NodeType.Equals(NodeType.Shape))
                {
                    Shape shape = (Shape)curNode;

                    // Several shape types can have an image including image shapes and OLE objects.
                    if (shape.HasImage)
                        shape.Remove();
                }

                curNode = nextNode;
            }
            //ExEnd

            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Shape, true).Count);
            doc.Save(ExDir + "Image.DeleteAllImagesPreOrder Out.doc");
        }
Esempio n. 51
0
        public void DetectBulletedParagraphs()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();

            //ExStart
            //ExFor:Paragraph.ListFormat
            //ExFor:ListFormat.IsListItem
            //ExFor:CompositeNode.GetText
            //ExFor:List.ListId
            //ExSummary:Finds and outputs all paragraphs in a document that are bulleted or numbered.
            NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph, true);
            foreach (Paragraph para in paras)
            {
                if (para.ListFormat.IsListItem)
                {
                    Console.WriteLine(string.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId));
                    Console.WriteLine(para.GetText());
                }
            }
            //ExEnd
        }
Esempio n. 52
0
        public void DeleteAllImages()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Image.SampleImages.doc");
            Assert.AreEqual(6, doc.GetChildNodes(NodeType.Shape, true).Count);

            //ExStart
            //ExFor:Shape.HasImage
            //ExFor:Node.Remove
            //ExSummary:Shows how to delete all images from a document.
            // Here we get all shapes from the document node, but you can do this for any smaller
            // node too, for example delete shapes from a single section or a paragraph.
            NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

            // We cannot delete shape nodes while we enumerate through the collection.
            // One solution is to add nodes that we want to delete to a temporary array and delete afterwards.
            ArrayList shapesToDelete = new ArrayList();
            foreach (Shape shape in shapes)
            {
                // Several shape types can have an image including image shapes and OLE objects.
                if (shape.HasImage)
                    shapesToDelete.Add(shape);
            }

            // Now we can delete shapes.
            foreach (Shape shape in shapesToDelete)
                shape.Remove();
            //ExEnd

            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Shape, true).Count);
            doc.Save(ExDir + "Image.DeleteAllImages Out.doc");
        }
Esempio n. 53
0
        public void InsertTableUsingNodeConstructors()
        {
            //ExStart
            //ExFor:Table
            //ExFor:Row
            //ExFor:Row.RowFormat
            //ExFor:RowFormat
            //ExFor:Cell
            //ExFor:Cell.CellFormat
            //ExFor:CellFormat
            //ExFor:CellFormat.Shading
            //ExFor:Cell.FirstParagraph
            //ExId:InsertTableUsingNodeConstructors
            //ExSummary:Shows how to insert a table using the constructors of nodes.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // We start by creating the table object. Note how we must pass the document object
            // to the constructor of each node. This is because every node we create must belong
            // to some document.
            Table table = new Table(doc);
            // Add the table to the document.
            doc.FirstSection.Body.AppendChild(table);

            // Here we could call EnsureMinimum to create the rows and cells for us. This method is used
            // to ensure that the specified node is valid, in this case a valid table should have at least one
            // row and one cell, therefore this method creates them for us.

            // Instead we will handle creating the row and table ourselves. This would be the best way to do this
            // if we were creating a table inside an algorthim for example.
            Row row = new Row(doc);
            row.RowFormat.AllowBreakAcrossPages = true;
            table.AppendChild(row);

            // We can now apply any auto fit settings.
            table.AutoFit(AutoFitBehavior.FixedColumnWidths);

            // Create a cell and add it to the row
            Cell cell = new Cell(doc);
            cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
            cell.CellFormat.Width = 80;

            // Add a paragraph to the cell as well as a new run with some text.
            cell.AppendChild(new Paragraph(doc));
            cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

            // Add the cell to the row.
            row.AppendChild(cell);

            // We would then repeat the process for the other cells and rows in the table.
            // We can also speed things up by cloning existing cells and rows.
            row.AppendChild(cell.Clone(false));
            row.LastCell.AppendChild(new Paragraph(doc));
            row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

            doc.Save(ExDir + "Table.InsertTableUsingNodes Out.doc");
            //ExEnd

            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Row, true).Count);
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Cell, true).Count);
            Assert.AreEqual("Row 1, Cell 1 Text\r\nRow 1, Cell 2 Text", doc.FirstSection.Body.Tables[0].ToString(SaveFormat.Text).Trim());
        }
Esempio n. 54
0
        public void GetAllFonts()
        {
            //ExStart
            //ExFor:Run
            //ExSummary:Gets all fonts used in a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Names.doc");

            // Select all runs in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Use a hashtable so we will keep only unique font names.
            Hashtable fontNames = new Hashtable();

            foreach (Run run in runs)
            {
                // This adds an entry into the hashtable.
                // The key is the font name. The value is null, we don't need the value.
                fontNames[run.Font.Name] = null;
            }

            // There are two fonts used in this document.
            Console.WriteLine("Font Count: " + fontNames.Count);
            //ExEnd

            // Verify the font count is correct.
            Assert.AreEqual(2, fontNames.Count);
        }
Esempio n. 55
0
        public void ChangeStyleName()
        {
            //ExStart
            //ExFor:Font.StyleName
            //ExSummary:Shows how to use style name to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.StyleName.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that names of built in styles could be different in documents
                // created by Microsoft Word versions for different languages.
                if (run.Font.StyleName.Equals("Emphasis"))
                    run.Font.StyleName = "Strong";
            }

            doc.Save(ExDir + "Font.StyleName Out.doc");
            //ExEnd
        }
Esempio n. 56
0
        public void ReplaceTextboxesWithImages()
        {
            //ExStart
            //ExFor:WrapSide
            //ExFor:ShapeBase.WrapSide
            //ExFor:NodeCollection
            //ExFor:CompositeNode.InsertAfter(Node, Node)
            //ExFor:NodeCollection.ToArray
            //ExSummary:Shows how to replace all textboxes with images.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Shape.ReplaceTextboxesWithImages.doc");

            // This gets a live collection of all shape nodes in the document.
            NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

            // Since we will be adding/removing nodes, it is better to copy all collection
            // into a fixed size array, otherwise iterator will be invalidated.
            Aspose.Words.Node[] shapes = shapeCollection.ToArray();

            foreach (Shape shape in shapes)
            {
                // Filter out all shapes that we don't need.
                if (shape.ShapeType.Equals(ShapeType.TextBox))
                {
                    // Create a new shape that will replace the existing shape.
                    Shape image = new Shape(doc, ShapeType.Image);

                    // Load the image into the new shape.
                    image.ImageData.SetImage(ExDir + "Hammer.wmf");

                    // Make new shape's position to match the old shape.
                    image.Left = shape.Left;
                    image.Top = shape.Top;
                    image.Width = shape.Width;
                    image.Height = shape.Height;
                    image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
                    image.RelativeVerticalPosition = shape.RelativeVerticalPosition;
                    image.HorizontalAlignment = shape.HorizontalAlignment;
                    image.VerticalAlignment = shape.VerticalAlignment;
                    image.WrapType = shape.WrapType;
                    image.WrapSide = shape.WrapSide;

                    // Insert new shape after the old shape and remove the old shape.
                    shape.ParentNode.InsertAfter(image, shape);
                    shape.Remove();
                }
            }

            doc.Save(ExDir + "Shape.ReplaceTextboxesWithImages Out.doc");
            //ExEnd
        }
Esempio n. 57
0
        //ExStart
        //ExFor:Font.Hidden
        //ExFor:Paragraph.Accept
        //ExFor:DocumentVisitor.VisitParagraphStart(Aspose.Words.Paragraph)
        //ExFor:DocumentVisitor.VisitFormField(Aspose.Words.Fields.FormField)
        //ExFor:DocumentVisitor.VisitTableEnd(Aspose.Words.Tables.Table)
        //ExFor:DocumentVisitor.VisitCellEnd(Aspose.Words.Tables.Cell)
        //ExFor:DocumentVisitor.VisitRowEnd(Aspose.Words.Tables.Row)
        //ExFor:DocumentVisitor.VisitSpecialChar(Aspose.Words.SpecialChar)
        //ExFor:DocumentVisitor.VisitGroupShapeStart(Aspose.Words.Drawing.GroupShape)
        //ExFor:DocumentVisitor.VisitShapeStart(Aspose.Words.Drawing.Shape)
        //ExFor:DocumentVisitor.VisitCommentStart(Aspose.Words.Comment)
        //ExFor:DocumentVisitor.VisitFootnoteStart(Aspose.Words.Footnote)
        //ExFor:SpecialChar
        //ExFor:Node.Accept
        //ExFor:Paragraph.ParagraphBreakFont
        //ExFor:Table.Accept
        //ExSummary:Implements the Visitor Pattern to remove all content formatted as hidden from the document.
        public void RemoveHiddenContentFromDocument()
        {
            // Open the document we want to remove hidden content from.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Hidden.doc");

            // Create an object that inherits from the DocumentVisitor class.
            RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

            // This is the well known Visitor pattern. Get the model to accept a visitor.
            // The model will iterate through itself by calling the corresponding methods
            // on the visitor object (this is called visiting).

            // We can run it over the entire the document like so:
            doc.Accept(hiddenContentRemover);

            // Or we can run it on only a specific node.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 4, true);
            para.Accept(hiddenContentRemover);

            // Or over a different type of node like below.
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
            table.Accept(hiddenContentRemover);

            doc.Save(ExDir + "Font.Hidden Out.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count); //ExSkip
        }
        public void InsertFootnote()
        {
            //ExStart
            //ExFor:Footnote
            //ExFor:FootnoteType
            //ExFor:DocumentBuilder.InsertFootnote(FootnoteType,string)
            //ExSummary:Shows how to add a footnote to a paragraph in the document using DocumentBuilder.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.Write("Some text");

            builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
            //ExEnd

            Assert.AreEqual("Footnote text.", doc.GetChildNodes(NodeType.Footnote, true)[0].ToString(SaveFormat.Text).Trim());
        }
Esempio n. 59
0
        public void ChangeStyleIdentifier()
        {
            //ExStart
            //ExFor:Font.StyleIdentifier
            //ExFor:StyleIdentifier
            //ExSummary:Shows how to use style identifier to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.StyleIdentifier.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that using StyleIdentifier we can identify a built-in style regardless
                // of the language of Microsoft Word used to create the document.
                if (run.Font.StyleIdentifier.Equals(StyleIdentifier.Emphasis))
                    run.Font.StyleIdentifier = StyleIdentifier.Strong;
            }

            doc.Save(ExDir + "Font.StyleIdentifier Out.doc");
            //ExEnd
        }
        public void BuildNestedTableUsingDocumentBuilder()
        {
            //ExStart
            //ExFor:Cell.FirstParagraph
            //ExId:BuildNestedTableUsingDocumentBuilder
            //ExSummary:Shows how to insert a nested table using DocumentBuilder.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Build the outer table.
            Cell cell = builder.InsertCell();
            builder.Writeln("Outer Table Cell 1");

            builder.InsertCell();
            builder.Writeln("Outer Table Cell 2");

            // This call is important in order to create a nested table within the first table
            // Without this call the cells inserted below will be appended to the outer table.
            builder.EndTable();

            // Move to the first cell of the outer table.
            builder.MoveTo(cell.FirstParagraph);

            // Build the inner table.
            builder.InsertCell();
            builder.Writeln("Inner Table Cell 1");
            builder.InsertCell();
            builder.Writeln("Inner Table Cell 2");

            builder.EndTable();

            doc.Save(ExDir + "DocumentBuilder.InsertNestedTable Out.doc");
            //ExEnd

            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count);
            Assert.AreEqual(4, doc.GetChildNodes(NodeType.Cell, true).Count);
            Assert.AreEqual(1, cell.Tables[0].Count);
            Assert.AreEqual(2, cell.Tables[0].FirstRow.Cells.Count);
        }