Exemplo n.º 1
0
        static void Main(string[] args)
        {
            var document = new Document();

            document.Add(new Hyperlink()
            {
                Text = "Text", Url = "https://github.com"
            });
            document.Add(new BoldText()
            {
                Text = "Text"
            });
            document.Add(new PlainText()
            {
                Text = "Text"
            });

            var htmlVisitor = new HtmlVisitor();

            document.Accept(htmlVisitor);
            System.Console.WriteLine(htmlVisitor.Result);

            var laTeXVisitor = new LaTeXVisitor();

            document.Accept(laTeXVisitor);
            System.Console.WriteLine(laTeXVisitor.Result);

            var plainTextVisitor = new PlainTextVisitor();

            document.Accept(plainTextVisitor);
            System.Console.WriteLine(plainTextVisitor.Result);

            System.Console.ReadLine();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            #region Employee Management

            // Setup employee collection
            Employees e = new Employees();
            e.Attach(new Clerk());
            e.Attach(new Director());
            e.Attach(new President());

            // Employees are 'visited'
            e.Accept(new IncomeVisitor());
            e.Accept(new VacationVisitor());

            // Wait for user
            Console.ReadKey();

            #endregion

            #region Document Formatting

            // Create a new document.
            var document = new Document();

            // Add some elements to the document.
            document.Elements.Add(new Text("This is plain text."));
            document.Elements.Add(new Hyperlink("Hyperlink to Airbrake.io", "http://airbrake.io"));
            document.Elements.Add(new Paragraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit."));
            document.Elements.Add(new BoldText("Important text to bold!"));

            // Create a few visitors.
            var html     = new HtmlVisitor();
            var markdown = new MarkdownVisitor();
            var bbCode   = new BbVisitor();

            // Force document to accept passed visitors,
            // which will each uniquely alter output.
            document.Accept(html);
            document.Accept(markdown);
            document.Accept(bbCode);

            // Log each visitor's output.
            Console.WriteLine("HTML");
            Console.WriteLine(html.ToString());

            Console.WriteLine("Markdown");
            Console.WriteLine(markdown.ToString());

            Console.WriteLine("BBCode");
            Console.WriteLine(bbCode.ToString());

            #endregion
        }
Exemplo n.º 3
0
        public static void Run()
        {
            var      document    = new Document();
            IVisitor readVisitor = (IVisitor) new ReadVisitor();

            //Here we want to visit all the elements of the doc in a read-only way...
            document.Accept(readVisitor);

            IVisitor writeVisitor = (IVisitor) new WriteVisitor();

            //Here we want to visit all the elements of the doc in a read-write way...
            document.Accept(writeVisitor);
        }
Exemplo n.º 4
0
        public static void Run()
        {
            //ExStart:ExtractContentUsingDocumentVisitor
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithDocument();

            // Open the document we want to convert.
            Document doc = new Document(dataDir + "Visitor.ToText.doc");

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

            // 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).
            //
            // Note that every node in the object model has the Accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor.
            Console.WriteLine(myConverter.GetText());
            //ExEnd:ExtractContentUsingDocumentVisitor
        }
        public static void Run()
        {
            // ExStart:ExtractContentUsingDocumentVisitor
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithDocument();

            // Open the document we want to convert.
            Document doc = new Document(dataDir + "Visitor.ToText.doc");

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

            // 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).
            // 
            // Note that every node in the object model has the Accept method so the visiting
            // Can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // That in this example, has accumulated in the visitor.
            Console.WriteLine(myConverter.GetText());
            // ExEnd:ExtractContentUsingDocumentVisitor
        }
        [Test] //ExSkip
        public void SmartTags()
        {
            Document doc      = new Document();
            SmartTag smartTag = new SmartTag(doc);

            smartTag.Element = "date";

            // Specify a date and set smart tag properties accordingly
            smartTag.AppendChild(new Run(doc, "May 29, 2019"));

            smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
            smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
            smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

            // Set the smart tag's uri to the default
            smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

            doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
            doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

            // Create and add one more smart tag, this time for a financial symbol
            smartTag         = new SmartTag(doc);
            smartTag.Element = "stockticker";
            smartTag.Uri     = "urn:schemas-microsoft-com:office:smarttags";

            smartTag.AppendChild(new Run(doc, "MSFT"));

            doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
            doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

            // Print all the smart tags in our document with a document visitor
            doc.Accept(new SmartTagVisitor());

            doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
        }
Exemplo n.º 7
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.
            Document doc = new 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 + @"\Artifacts\Font.Hidden.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);      //ExSkip
        }
Exemplo n.º 8
0
        public List <string> GetParaText()
        {
            myVisitor visitor = new myVisitor(_doc);

            _doc.Accept(visitor);

            return(null);
        }
Exemplo n.º 9
0
    static void Main(string[] args)
    {
        var doc = new Document();

        doc.Parts.Add(new BoldText("Überschrift"));
        doc.Parts.Add(new PlainText("Dies ist ein normaler Textabschnitt"));
        doc.Parts.Add(new Hyperlink("Dies ist ein Link", "https://www.hshl.de"));

        var html = new HtmlDocumentConverter();

        doc.Accept(html);
        Console.WriteLine("Als Html:\n" + html.ToString() + "\n");

        var latex = new LatexDocumentConverter();

        doc.Accept(latex);
        Console.WriteLine("Als Latex:\n" + latex.ToString() + "\n");
    }
        public void PrintHorizontalAndVerticalMerged()
        {
            //ExStart:PrintHorizontalAndVerticalMerged
            Document doc = new Document(MyDir + "Table with merged cells.docx");

            SpanVisitor visitor = new SpanVisitor(doc);

            doc.Accept(visitor);
            //ExEnd:PrintHorizontalAndVerticalMerged
        }
Exemplo n.º 11
0
        public static void PrintHorizontalAndVerticalMerged(string dataDir)
        {
            // ExStart:PrintHorizontalAndVerticalMerged
            Document doc = new Document(dataDir + "Table.MergedCells.doc");

            // Create visitor
            SpanVisitor visitor = new SpanVisitor(doc);

            // Accept visitor
            doc.Accept(visitor);
            // ExEnd:PrintHorizontalAndVerticalMerged
            Console.WriteLine("\nHorizontal and vertical merged of a cell prints successfully.");
        }
        public void AddsBodyToSection_WhenStartVisitingFromSection()
        {
            Section section = new Document().FirstSection;
            var sectionProxy = new SectionProxy();
            var bodyProxy = A.Fake<BodyProxy>();

            A.CallTo(() => this.proxyFactory.CreateSection()).Returns(sectionProxy);
            A.CallTo(() => this.proxyFactory.CreateBody()).Returns(bodyProxy);

            section.Accept(this.testee);

            sectionProxy.Body.Should().Be(bodyProxy);
        }
Exemplo n.º 13
0
        [Test] //ExSkip
        public void Create()
        {
            Document doc = new Document();

            // A smart tag appears in a document with Microsoft Word recognizes a part of its text as some form of data,
            // such as a name, date, or address, and converts it to a hyperlink that displays a purple dotted underline.
            SmartTag smartTag = new SmartTag(doc);

            // Smart tags are composite nodes that contain their recognized text in its entirety.
            // Add contents to this smart tag manually.
            smartTag.AppendChild(new Run(doc, "May 29, 2019"));

            // Microsoft Word may recognize the above contents as being a date.
            // Smart tags use the "Element" property to reflect the type of data they contain.
            smartTag.Element = "date";

            // Some smart tag types process their contents further into custom XML properties.
            smartTag.Properties.Add(new CustomXmlProperty("Day", string.Empty, "29"));
            smartTag.Properties.Add(new CustomXmlProperty("Month", string.Empty, "5"));
            smartTag.Properties.Add(new CustomXmlProperty("Year", string.Empty, "2019"));

            // Set the smart tag's URI to the default value.
            smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

            doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
            doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

            // Create another smart tag for a stock ticker.
            smartTag         = new SmartTag(doc);
            smartTag.Element = "stockticker";
            smartTag.Uri     = "urn:schemas-microsoft-com:office:smarttags";

            smartTag.AppendChild(new Run(doc, "MSFT"));

            doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
            doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

            // Print all the smart tags in our document using a document visitor.
            doc.Accept(new SmartTagPrinter());

            // Older versions of Microsoft Word support smart tags.
            doc.Save(ArtifactsDir + "SmartTag.Create.doc");

            // Use the "RemoveSmartTags" method to remove all smart tags from a document.
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.SmartTag, true).Count);

            doc.RemoveSmartTags();

            Assert.AreEqual(0, doc.GetChildNodes(NodeType.SmartTag, true).Count);
            TestCreate(new Document(ArtifactsDir + "SmartTag.Create.doc")); //ExSkip
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            var document = new Document();

            document.Add(new Hyperlink {
                Text = "NET", Url = "1234"
            });
            document.Add(new BoldText {
                Text = "NET"
            });
            document.Add(new PlainText {
                Text = "NET"
            });

            List <string> str = document.Accept(new HtmlVisitor());

            str.AddRange(document.Accept(new LatexVisitor()));
            str.AddRange(document.Accept(new PlainTextVisitor()));

            foreach (var item in str)
            {
                System.Console.WriteLine(item);
            }
        }
Exemplo n.º 15
0
        public void TestVisitor()
        {
            var document = new Document();

            document.AddPart(new BoldText("This is bold text."));
            document.AddPart(new PlainText("This is plain text."));
            document.AddPart(new Hyperlink("This is hyperlink.", "http://www.example.com"));

            var htmlVisitor = new HtmlVisitor();

            document.Accept(htmlVisitor);

            Assert.That(
                htmlVisitor.Output,
                Is.EqualTo("<b>This is bold text.</b>This is plain text.<a href=\"http://www.example.com\">This is hyperlink.</a>"));

            var latexVisitor = new LatexVisitor();

            document.Accept(latexVisitor);

            Assert.That(
                latexVisitor.Output,
                Is.EqualTo("\\textbf{This is bold text.}This is plain text.\\href{http://www.example.com}{This is hyperlink.}"));
        }
Exemplo n.º 16
0
        public void RemoveHiddenContentFromDocument()
        {
            //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.
            // Open the document we want to remove hidden content from.
            Document doc = new 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 + @"\Artifacts\Font.Hidden.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);      //ExSkip
        }
Exemplo n.º 17
0
        public static void Main()
        {
            Document doc = new Document(
                new List <DocumentPart>()
            {
                new PlainText("Az sym Pesho, kakto se ochakvashe."),
                new BoldText("Pesho."),
                new Hyperlink("Go to Pesho's website.", "http://pesho.com")
            });

            // Could have other formatter in the form of a visitor
            var htmlConverter = new HtmlVisitor();

            doc.Accept(htmlConverter);
            Console.WriteLine("HTML: \n{0}", htmlConverter.Output);
        }
Exemplo n.º 18
0
        [Test] //ExSkip
        public void OfficeMathToText()
        {
            // Open the document that has office math objects we want to print the info of
            Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

            // Create an object that inherits from the DocumentVisitor class
            OfficeMathInfoPrinter visitor = new OfficeMathInfoPrinter();

            // Accepting a visitor lets it start traversing the nodes in the document,
            // starting with the node that accepted it to then recursively visit every child
            doc.Accept(visitor);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor
            Console.WriteLine(visitor.GetText());
        }
Exemplo n.º 19
0
        public static void Equal(string asciidoc, Document document)
        {
            var directoryAttribute = document.Attributes.FirstOrDefault(a => a.Name == "docdir");

            if (directoryAttribute != null)
            {
                document.Attributes.Remove(directoryAttribute);
            }

            var builder = new StringBuilder();

            using (var visitor = new AsciiDocVisitor(new StringWriter(builder)))
            {
                document.Accept(visitor);
            }

            Assert.Equal(asciidoc, builder.ToString().TrimEnd('\r', '\n'));
        }
Exemplo n.º 20
0
        private static string RenderAsciiDoc(Document document)
        {
            var directoryAttributes = document.Attributes.Where(a => a.Name == "docdir").ToList();

            foreach (var directoryAttribute in directoryAttributes)
            {
                document.Attributes.Remove(directoryAttribute);
            }

            var builder = new StringBuilder();

            using (var visitor = new AsciiDocVisitor(new StringWriter(builder)))
            {
                document.Accept(visitor);
            }

            return(builder.ToString().RemoveTrailingNewLine());
        }
Exemplo n.º 21
0
        [Test] //ExSkip
        public void Create()
        {
            Document doc      = new Document();
            SmartTag smartTag = new SmartTag(doc);

            smartTag.Element = "date";

            // Specify a date and set smart tag properties accordingly
            smartTag.AppendChild(new Run(doc, "May 29, 2019"));

            smartTag.Properties.Add(new CustomXmlProperty("Day", string.Empty, "29"));
            smartTag.Properties.Add(new CustomXmlProperty("Month", string.Empty, "5"));
            smartTag.Properties.Add(new CustomXmlProperty("Year", string.Empty, "2019"));

            // Set the smart tag's uri to the default
            smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

            doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
            doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

            // Create and add one more smart tag, this time for a financial symbol
            smartTag         = new SmartTag(doc);
            smartTag.Element = "stockticker";
            smartTag.Uri     = "urn:schemas-microsoft-com:office:smarttags";

            smartTag.AppendChild(new Run(doc, "MSFT"));

            doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
            doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

            // Print all the smart tags in our document with a document visitor
            doc.Accept(new SmartTagVisitor());

            // SmartTags are supported by older versions of microsoft Word
            doc.Save(ArtifactsDir + "SmartTag.Create.doc");

            // We can strip a document of all its smart tags with RemoveSmartTags()
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.SmartTag, true).Count);
            doc.RemoveSmartTags();
            Assert.AreEqual(0, doc.GetChildNodes(NodeType.SmartTag, true).Count);

            TestCreate(new Document(ArtifactsDir + "SmartTag.Create.doc")); //ExSkip
        }
Exemplo n.º 22
0
        public void ExtractContentUsingDocumentVisitor()
        {
            //ExStart:ExtractContentUsingDocumentVisitor
            Document doc = new Document(MyDir + "Absolute position tab.docx");

            MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

            // 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).
            // Note that every node in the object model has the accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // That in this example, has accumulated in the visitor.
            Console.WriteLine(myConverter.GetText());
            //ExEnd:ExtractContentUsingDocumentVisitor
        }
Exemplo n.º 23
0
        //ExStart
        //ExFor:Document.Accept
        //ExFor:Body.Accept
        //ExFor:DocumentVisitor
        //ExFor:DocumentVisitor.VisitAbsolutePositionTab
        //ExFor:DocumentVisitor.VisitBookmarkStart 
        //ExFor:DocumentVisitor.VisitBookmarkEnd
        //ExFor:DocumentVisitor.VisitRun
        //ExFor:DocumentVisitor.VisitFieldStart
        //ExFor:DocumentVisitor.VisitFieldEnd
        //ExFor:DocumentVisitor.VisitFieldSeparator
        //ExFor:DocumentVisitor.VisitBodyStart
        //ExFor:DocumentVisitor.VisitBodyEnd
        //ExFor:DocumentVisitor.VisitParagraphEnd
        //ExFor:DocumentVisitor.VisitHeaderFooterStart
        //ExFor:VisitorAction
        //ExId:ExtractContentDocToTxtConverter
        //ExSummary:Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
        public void ToText()
        {
            // Open the document we want to convert.
            Document doc = new Document(MyDir + "Visitor.ToText.doc");

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

            // 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).
            // 
            // Note that every node in the object model has the Accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor.
            Console.WriteLine(myConverter.GetText());
        }
Exemplo n.º 24
0
        [Test] //ExSkip
        public void EditableRangeToText()
        {
            // Open the document that has editable ranges we want to print the info of
            Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

            // Create an object that inherits from the DocumentVisitor class
            EditableRangeInfoPrinter visitor = new EditableRangeInfoPrinter();

            // Accepting a visitor lets it start traversing the nodes in the document,
            // starting with the node that accepted it to then recursively visit every child
            doc.Accept(visitor);

            Paragraph p = new Paragraph(doc);

            p.AppendChild(new Run(doc, "Paragraph with editable range text."));

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor
            Console.WriteLine(visitor.GetText());
        }
        [Test] //ExSkip
        public void HeaderFooterToText()
        {
            // Open the document that has headers and/or footers we want to print the info of
            Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

            // Create an object that inherits from the DocumentVisitor class
            HeaderFooterInfoPrinter visitor = new HeaderFooterInfoPrinter();

            // Accepring a visitor lets it start traversing the nodes in the document,
            // starting with the node that accepted it to then recursively visit every child
            doc.Accept(visitor);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor
            Console.WriteLine(visitor.GetText());

            // An alternative way of visiting a document's header/footers section-by-section is by accessing the collection
            // We can also turn it into an array
            HeaderFooter[] headerFooters = doc.FirstSection.HeadersFooters.ToArray();
            Assert.AreEqual(6, headerFooters.Length);
        }
        [Test] //ExSkip
        public void Visitor()
        {
            Document doc = new Document();

            doc.Protect(ProtectionType.ReadOnly, "MyPassword");

            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.Writeln("Hello world! Since we have set the document's protection level to read-only," +
                            " we cannot edit this paragraph without the password.");

            // When we write-protect documents, editable ranges allow us to pick specific areas that users may edit.
            // There are two mutually exclusive ways to narrow down the list of allowed editors.
            // 1 -  Specify a user:
            EditableRange editableRange = builder.StartEditableRange().EditableRange;

            editableRange.SingleUser = "******";
            builder.Writeln($"This paragraph is inside the first editable range, can only be edited by {editableRange.SingleUser}.");
            builder.EndEditableRange();

            Assert.AreEqual(EditorType.Unspecified, editableRange.EditorGroup);

            // 2 -  Specify a group that allowed users are associated with:
            editableRange             = builder.StartEditableRange().EditableRange;
            editableRange.EditorGroup = EditorType.Administrators;
            builder.Writeln($"This paragraph is inside the first editable range, can only be edited by {editableRange.EditorGroup}.");
            builder.EndEditableRange();

            Assert.AreEqual(string.Empty, editableRange.SingleUser);

            builder.Writeln("This paragraph is outside the editable range, and cannot be edited by anybody.");

            // Print details and contents of every editable range in the document.
            EditableRangePrinter editableRangePrinter = new EditableRangePrinter();

            doc.Accept(editableRangePrinter);

            Console.WriteLine(editableRangePrinter.ToText());
        }
Exemplo n.º 27
0
        public void ToText()
        {
            //ExStart
            //ExFor:Document.Accept
            //ExFor:Body.Accept
            //ExFor:DocumentVisitor
            //ExFor:DocumentVisitor.VisitAbsolutePositionTab
            //ExFor:DocumentVisitor.VisitBookmarkStart
            //ExFor:DocumentVisitor.VisitBookmarkEnd
            //ExFor:DocumentVisitor.VisitRun
            //ExFor:DocumentVisitor.VisitFieldStart
            //ExFor:DocumentVisitor.VisitFieldEnd
            //ExFor:DocumentVisitor.VisitFieldSeparator
            //ExFor:DocumentVisitor.VisitBodyStart
            //ExFor:DocumentVisitor.VisitBodyEnd
            //ExFor:DocumentVisitor.VisitParagraphEnd
            //ExFor:DocumentVisitor.VisitHeaderFooterStart
            //ExFor:VisitorAction
            //ExId:ExtractContentDocToTxtConverter
            //ExSummary:Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
            // Open the document we want to convert.
            Document doc = new Document(MyDir + "Visitor.ToText.doc");

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

            // 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).
            //
            // Note that every node in the object model has the Accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor.
            Console.WriteLine(myConverter.GetText());
        }
        [Test] //ExSkip
        public void CreateEditableRanges()
        {
            Document doc = new Document(MyDir + "Document.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Start an editable range
            EditableRangeStart edRange1Start = builder.StartEditableRange();

            // An EditableRange object is created for the EditableRangeStart that we just made
            EditableRange editableRange1 = edRange1Start.EditableRange;

            // Put something inside the editable range
            builder.Writeln("Paragraph inside first editable range");

            // An editable range is well-formed if it has a start and an end
            // Multiple editable ranges can be nested and overlapping 
            EditableRangeEnd edRange1End = builder.EndEditableRange();

            // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
            EditableRangeStart edRange2Start = builder.StartEditableRange();
            builder.Writeln("Paragraph inside second editable range");
            EditableRange editableRange2 = edRange2Start.EditableRange;
            EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

            // Editable range starts and ends have their own respective node types
            Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
            Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

            // Editable range IDs are unique and set automatically
            Assert.AreEqual(0, editableRange1.Id);
            Assert.AreEqual(1, editableRange2.Id);

            // Editable range starts and ends always belong to a range
            Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
            Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

            // They also inherit the ID of the entire editable range that they belong to
            Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
            Assert.AreEqual(editableRange1.Id, edRange1End.Id);
            Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
            Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

            // If the editable range was found in a document, it will probably have something in the single user property
            // But if we make one programmatically, the property is null by default
            Assert.AreEqual(null, editableRange1.SingleUser);

            // We have to set it ourselves if we want the ranges to belong to somebody
            editableRange1.SingleUser = "******";
            editableRange2.SingleUser = "******";

            // Initialize a custom visitor for editable ranges that will print their contents 
            EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

            // Both the start and end of an editable range can accept visitors, but not the editable range itself
            edRange1Start.Accept(editableRangeReader);
            edRange2End.Accept(editableRangeReader);
            
            // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
            editableRangeReader.Reset();
            doc.Accept(editableRangeReader);

            Console.WriteLine(editableRangeReader.ToText());
        }
        public void SetsBodyAsRoot_WhenStartVisitingFromBody()
        {
            Body body = new Document().FirstSection.Body;
            var bodyProxy = A.Fake<BodyProxy>();

            A.CallTo(() => this.proxyFactory.CreateBody()).Returns(bodyProxy);

            body.Accept(this.testee);

            this.testee.Root.Should().Be(bodyProxy);
        }
        public void SetsDocumentAsRoot_WhenStartVisitingFromDocument()
        {
            var document = new Document();
            var documentProxy = new DocumentProxy();

            A.CallTo(() => this.proxyFactory.CreateDocument()).Returns(documentProxy);

            document.Accept(this.testee);

            this.testee.Root.Should().Be(documentProxy);
        }
Exemplo n.º 31
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.
            Document doc = new 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 + @"\Artifacts\Font.Hidden.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count); //ExSkip
        }
Exemplo n.º 32
0
 /// <summary>
 /// Visits the specified document.
 /// </summary>
 /// <param name="document">The document.</param>
 public void VisitDocument(Document document)
 {
     document.Accept(this);
 }
Exemplo n.º 33
0
 public Document Convert(Document document)
 {
     document.Accept(this);
     return(_newDocument);
 }
        public static void PrintHorizontalAndVerticalMerged(string dataDir)
        {
            // ExStart:PrintHorizontalAndVerticalMerged
            Document doc = new Document(dataDir + "Table.MergedCells.doc");

            // Create visitor
            SpanVisitor visitor = new SpanVisitor(doc);

            // Accept visitor
            doc.Accept(visitor);
            // ExEnd:PrintHorizontalAndVerticalMerged
            Console.WriteLine("\nHorizontal and vertical merged of a cell prints successfully.");
           
        }
Exemplo n.º 35
0
		public Document Convert(Document document)
		{
			document.Accept(this);
			return _newDocument;
		}
Exemplo n.º 36
0
 public void Render(Document document, TextWriter writer)
 {
     _writer = writer;
     document.Accept(this);
 }
        public void SetsParagraphAsRoot_WhenStartVisitingFromParagraph()
        {
            Paragraph paragraph = new Document().FirstSection.Body.FirstParagraph;

            var paragraphProxy = A.Fake<ParagraphProxy>();

            A.CallTo(() => this.proxyFactory.CreateParagraph()).Returns(paragraphProxy);

            paragraph.Accept(this.testee);

            this.testee.Root.Should().Be(paragraphProxy);
        }
Exemplo n.º 38
0
 /// <summary>
 /// Splits nodes which appear× over two or more pages into separate nodes so that they still appear in the same way
 /// but no longer appear across a page.
 /// </summary>
 public void SplitNodesAcrossPages()
 {
     // Visit any composites which are possibly split across pages and split them into separate nodes.
     Document.Accept(new SectionSplitter(this));
 }
Exemplo n.º 39
0
        public List <PageInfo> Convert(String inputFile, ImageConversionOptions options)
        {
            var ext        = (options.ProcessAs ?? Path.GetExtension(inputFile).Trim('.', ' ')).ToUpper();
            var isTextFile = (ext == "TXT");

            // Open the document
            Document doc = OpenDocument(inputFile, ext);

            // Specific processing for MHT, HTM and HTML
            if (ext == "MHT" || ext == "HTM" || ext == "HTML" || isTextFile)
            {
                // Adjust Margins, Paper Size and Orientation
                foreach (Section section in doc.Sections)
                {
                    section.PageSetup.PaperSize   = PaperSize.A4;
                    section.PageSetup.Orientation = isTextFile ? Orientation.Landscape : Orientation.Portrait;

                    section.PageSetup.LeftMargin   = (section.PageSetup.LeftMargin / 2.54) / 2;
                    section.PageSetup.RightMargin  = (section.PageSetup.RightMargin / 2.54) / 2;
                    section.PageSetup.TopMargin    = (section.PageSetup.TopMargin / 2.54) / 2;
                    section.PageSetup.BottomMargin = (section.PageSetup.BottomMargin / 2.54) / 2;

                    if (isTextFile)
                    {
                        FontChanger changer = new FontChanger("Courier New");
                        doc.Accept(changer);
                    }
                    else
                    {
                        // Get the portrait and landscape widths
                        var portraitWidth  = section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin;
                        var landscapeWidth = section.PageSetup.PageHeight - section.PageSetup.TopMargin - section.PageSetup.BottomMargin;

                        // Adjust table fit
                        foreach (Table table in section.Body.Tables)
                        {
                            var width = GetTableWidth(table);

                            if (width > portraitWidth)
                            {
                                if (section.PageSetup.Orientation != Orientation.Landscape)
                                {
                                    section.PageSetup.Orientation = Orientation.Landscape;
                                }

                                if (width > landscapeWidth)
                                {
                                    table.AutoFit(AutoFitBehavior.AutoFitToWindow);
                                }
                            }
                        }

                        // Get the usable width/height
                        var usableWidth  = section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin;
                        var usableHeight = section.PageSetup.PageHeight - section.PageSetup.TopMargin - section.PageSetup.BottomMargin;

                        // Adjust image size
                        foreach (Shape shape in section.GetChildNodes(NodeType.Shape, true))
                        {
                            if (shape.HasImage && (shape.Width > usableWidth || shape.Height > usableHeight))
                            {
                                // Adjust shape size
                                var scale = Math.Min((usableWidth / shape.Width), (usableHeight / shape.Height));

                                shape.Width  = shape.Width * scale;
                                shape.Height = shape.Height * scale;
                            }
                        }
                    }
                }

                if (!isTextFile)
                {
                    // Update table layout following adjustments
                    doc.UpdateTableLayout();
                }
            }

            if (options.BinarisationAlgorithm == BinarisationAlgorithm.Default)
            {
                options.BinarisationAlgorithm = BinarisationAlgorithm.OtsuThreshold;
            }

            var pages = new List <PageInfo>();

            var saveOptions = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Png);

            saveOptions.Resolution = options.Resolution;
            saveOptions.PageCount  = 1;

            for (int i = 0; i < doc.PageCount; i++)
            {
                saveOptions.PageIndex = i;

                using (MemoryStream ms = new MemoryStream())
                {
                    // Save the page to the memory stream
                    doc.Save(ms, saveOptions);

                    // Set the position back to the start of the stream
                    ms.Seek(0, SeekOrigin.Begin);

                    try
                    {
                        // Convert the page and add it to the list
                        pages.AddRange(ImageProcessingEngine.Instance.Convert(ms, options));
                    }
                    catch (Exception e)
                    {
                        if (e.Message == "Decode: Unknown or wrong format [Stream][CiImage::Open]")
                        {
                            // This is a known error, there is an occasional issue with  the ClearImage Open method
                            // Loading the stream into a Bitmap object works around the issue for now...
                            using (var stream = new MemoryStream(ms.ToArray()))
                                using (var bitmap = (Bitmap)Bitmap.FromStream(stream, true, false))
                                {
                                    pages.AddRange(ImageProcessingEngine.Instance.Convert(bitmap, options));
                                }
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            return(pages);
        }
        public void SetsSectionAsRoot_WhenStartVisitingFromSection()
        {
            Section section = new Document().FirstSection;
            var sectionProxy = A.Fake<SectionProxy>();

            A.CallTo(() => this.proxyFactory.CreateSection()).Returns(sectionProxy);

            section.Accept(this.testee);

            this.testee.Root.Should().Be(sectionProxy);
        }