Aspose.Words for .NET Code Example

using Aspose.Words;
using Aspose.Words.Saving;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document(@"C:\Temp\input.rtf");

            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg);
            options.PageCount = 1;
            int pageCountDoc = doc.PageCount;
            for (int pageCount = 0; pageCount < pageCountDoc; pageCount++)
            {
                options.PageIndex = pageCount;
                doc.Save(@"C:\Temp\out_" + pageCount + ".jpg", options);
            }
        }
    }
}
using Aspose.Words;
using Aspose.Words.Drawing;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document(@"C:\Temp\input.docx");

            // Always set name of 'watermark' to be able to remove it afterwards
            //watermark.Name("WaterMark");
            foreach (HeaderFooter hf in doc.GetChildNodes(NodeType.HeaderFooter, true))
            {
                foreach (Shape shape in hf.GetChildNodes(NodeType.Shape, true))
                {
                    if (shape.Name.Contains("WaterMark"))
                    {
                        shape.Remove();
                    }
                }
            }

            doc.Save(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Replacing;
using System.Collections;
using System.Drawing;
using System.Text.RegularExpressions;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document(@"C:\Temp\input.docx");

            FindReplaceOptions options = new FindReplaceOptions();
            options.ReplacingCallback = new ReplaceEvaluatorFindAndHighlight();
            options.Direction = FindReplaceDirection.Backward;
            // We want the "your document" phrase to be highlighted.
            Regex regex = new Regex("your document", RegexOptions.IgnoreCase);
            doc.Range.Replace(regex, "", options);

            doc.Save(@"C:\Temp\output.docx");
        }

        private class ReplaceEvaluatorFindAndHighlight : IReplacingCallback
        {
            /// <summary>
            /// This method is called by the Aspose.Words find and replace engine for each match.
            /// This method highlights the match string, even if it spans multiple runs.
            /// </summary>
            ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
            {
                // This is a Run node that contains either the beginning or the complete match.
                Node currentNode = e.MatchNode;

                // The first (and may be the only) run can contain text before the match, 
                // In this case it is necessary to split the run.
                if (e.MatchOffset > 0)
                    currentNode = SplitRun((Run)currentNode, e.MatchOffset);

                // This array is used to store all nodes of the match for further highlighting.
                ArrayList runs = new ArrayList();

                // Find all runs that contain parts of the match string.
                int remainingLength = e.Match.Value.Length;

                while (
                    (remainingLength > 0) &&
                    (currentNode != null) &&
                    (currentNode.GetText().Length <= remainingLength))
                {
                    runs.Add(currentNode);
                    remainingLength = remainingLength - currentNode.GetText().Length;

                    // Select the next Run node. 
                    // Have to loop because there could be other nodes such as BookmarkStart etc.
                    do
                    {
                        currentNode = currentNode.NextSibling;
                    }
                    while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
                }

                // Split the last run that contains the match if there is any text left.
                if ((currentNode != null) && (remainingLength > 0))
                {
                    SplitRun((Run)currentNode, remainingLength);
                    runs.Add(currentNode);
                }

                // Now highlight all runs in the sequence.
                foreach (Run run in runs)
                    run.Font.HighlightColor = Color.Yellow;

                // Signal to the replace engine to do nothing because we have already done all what we wanted.
                return ReplaceAction.Skip;
            }
        }

        private static Run SplitRun(Run run, int position)
        {
            Run afterRun = (Run)run.Clone(true);
            afterRun.Text = run.Text.Substring(position);
            run.Text = run.Text.Substring(0, position);
            run.ParentNode.InsertAfter(afterRun, run);
            return afterRun;
        }
    }
}
using Aspose.Words;
using Aspose.Words.Tables;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            Table table = builder.StartTable();
            // Insert a cell
            builder.InsertCell();
            // Use fixed column widths.
            table.AutoFit(AutoFitBehavior.FixedColumnWidths);
            builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            builder.Write("This is row 1 cell 1");

            // Insert a cell
            builder.InsertCell();
            builder.Write("This is row 1 cell 2");
            builder.EndRow();

            // Insert a cell
            builder.InsertCell();
            // Apply new row formatting
            builder.RowFormat.Height = 100;
            builder.RowFormat.HeightRule = HeightRule.Exactly;
            builder.CellFormat.Orientation = TextOrientation.Upward;
            builder.Writeln("This is row 2 cell 1");

            // Insert a cell
            builder.InsertCell();
            builder.CellFormat.Orientation = TextOrientation.Downward;
            builder.Writeln("This is row 2 cell 2");
            builder.EndRow();

            builder.EndTable();

            doc.Save(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            // We call this method to start building the table.
            builder.StartTable();
            builder.InsertCell();
            builder.Write("Row 1, Cell 1 Content.");
            // Build the second cell
            builder.InsertCell();
            builder.Write("Row 1, Cell 2 Content.");
            // Call the following method to end the row and start a new row.
            builder.EndRow();

            // Build the first cell of the second row.
            builder.InsertCell();
            builder.Write("Row 2, Cell 1 Content");

            // Build the second cell.
            builder.InsertCell();
            builder.Write("Row 2, Cell 2 Content.");
            builder.EndRow();

            // Signal that we have finished building the table.
            builder.EndTable();

            doc.Save(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Tables;
using System.Drawing;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            Table table = builder.StartTable();
            // Make the header row.
            builder.InsertCell();

            // Set the left indent for the table. Table wide formatting must be applied after 
            // At least one row is present in the table.
            table.LeftIndent = 20.0;

            // Set height and define the height rule for the header row.
            builder.RowFormat.Height = 40.0;
            builder.RowFormat.HeightRule = HeightRule.AtLeast;

            // Some special features for the header row.
            builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.Font.Size = 16;
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;

            builder.CellFormat.Width = 100.0;
            builder.Write("Header Row,\n Cell 1");

            // We don't need to specify the width of this cell because it's inherited from the previous cell.
            builder.InsertCell();
            builder.Write("Header Row,\n Cell 2");

            builder.InsertCell();
            builder.CellFormat.Width = 200.0;
            builder.Write("Header Row,\n Cell 3");
            builder.EndRow();

            // Set features for the other rows and cells.
            builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
            builder.CellFormat.Width = 100.0;
            builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

            // Reset height and define a different height rule for table body
            builder.RowFormat.Height = 30.0;
            builder.RowFormat.HeightRule = HeightRule.Auto;
            builder.InsertCell();
            // Reset font formatting.
            builder.Font.Size = 12;
            builder.Font.Bold = false;

            // Build the other cells.
            builder.Write("Row 1, Cell 1 Content");
            builder.InsertCell();
            builder.Write("Row 1, Cell 2 Content");

            builder.InsertCell();
            builder.CellFormat.Width = 200.0;
            builder.Write("Row 1, Cell 3 Content");
            builder.EndRow();

            builder.InsertCell();
            builder.CellFormat.Width = 100.0;
            builder.Write("Row 2, Cell 1 Content");

            builder.InsertCell();
            builder.Write("Row 2, Cell 2 Content");

            builder.InsertCell();
            builder.CellFormat.Width = 200.0;
            builder.Write("Row 2, Cell 3 Content.");
            builder.EndRow();
            builder.EndTable();

            doc.Save(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Tables;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new 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(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Tables;
using System.Drawing;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new 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(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Tables;
namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();
            Document doc = new Document(@"C:\Temp\Table.SimpleTable.doc");
            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(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Tables;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();
            Document doc = new Document(@"C:\Temp\Table.SimpleTable.doc");
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
            // Clone the last row in the table.
            Row clonedRow = (Row)table.LastRow.Clone(true);
            // Remove all content from the cloned row's cells. This makes the row ready for
            // New content to be inserted into.
            foreach (Cell cell in clonedRow.Cells)
                cell.RemoveAllChildren();
            // Add the row to the end of the table.
            table.AppendChild(clonedRow);
            doc.Save(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            // Insert the table from HTML. Note that AutoFitSettings does not apply to tables
            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(@"C:\Temp\output.docx");
        }
    }
}
using Aspose.Words;
using Aspose.Words.Replacing;
using Aspose.Words.Tables;
using System;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document(@"C:\Temp\Table.SimpleTable.doc");

            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

            // The range text will include control characters such as "\a" for a cell.
            // You can call ToString and pass SaveFormat.Text on the desired node to find the plain text content.

            // Print the plain text range of the table to the screen.
            Console.WriteLine("Contents of the table: ");
            Console.WriteLine(table.Range.Text);


            // Print the contents of the second row to the screen.
            Console.WriteLine("\nContents of the row: ");
            Console.WriteLine(table.Rows[1].Range.Text);

            // Print the contents of the last cell in the table to the screen.
            Console.WriteLine("\nContents of the cell: ");
            Console.WriteLine(table.LastRow.LastCell.Range.Text);

            // Replace any instances of our string in the entire table.
            table.Range.Replace("Carrots", "Eggs", new FindReplaceOptions(FindReplaceDirection.Forward));
            // Replace any instances of our string in the last cell of the table only.
            table.LastRow.LastCell.Range.Replace("50", "20",
                        new FindReplaceOptions(FindReplaceDirection.Forward));

            doc.Save(@"C:\Temp\output.docx");
            Console.Read();
        }
    }
}
using Aspose.Words;
using Aspose.Words.Markup;
using NUnit.Framework;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Get specific style from the document to apply it to an SDT
            Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
            StructuredDocumentTag sdtPlainText =
                        new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
            sdtPlainText.Style = quoteStyle;

            StructuredDocumentTag sdtRichText =
                        new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
            // Second method to apply specific style to an SDT control
            sdtRichText.StyleName = "Quote";

            // Insert content controls into the document
            builder.InsertNode(sdtPlainText);
            builder.InsertNode(sdtRichText);

            // We can get a collection of StructuredDocumentTags by looking for
            // the document's child nodes of this NodeType
            Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

            NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

            foreach (Node node in tags)
            {
                StructuredDocumentTag sdt = (StructuredDocumentTag)node;
                // If style was not defined before, style should be "Default Paragraph Font"
                Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
                Assert.AreEqual("Quote", sdt.StyleName);
            }
        }
    }
}
using Aspose.Words;
using Aspose.Words.Drawing;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            string MyDir = "C:\\images\\";
            string imageFileName = MyDir + "birds.jpg";

            DocumentBuilder builder = new DocumentBuilder();
            builder.Write("Image linked, not stored in the document: ");

            Shape linkedOnly = builder.InsertImage(imageFileName);
            linkedOnly.WrapType = WrapType.Inline;
            linkedOnly.ImageData.SourceFullName = imageFileName;

            builder.Writeln();
            builder.Write("Image linked and stored in the document: ");

            Shape linkedAndStored = builder.InsertImage(imageFileName);
            linkedAndStored.WrapType = WrapType.Inline;
            linkedAndStored.ImageData.SourceFullName = imageFileName;
            linkedAndStored.ImageData.SetImage(imageFileName);

            builder.Writeln();
            builder.Write("Image stored in the document, but not linked: ");

            Shape stored = builder.InsertImage(imageFileName);
            stored.WrapType = WrapType.Inline;
            stored.ImageData.SetImage(imageFileName);

            builder.Writeln();
            builder.Document.Save(MyDir + "out.docx");
        }
    }
}
using Aspose.Words;

namespace Unit_Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            License.Apply();

            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.InsertOnlineVideo("https://youtu.be/7QvogMTZIIY", 360, 270);

            // We can watch the video from Microsoft Word by clicking on the shape.
            doc.Save("C:\\Temp\\InsertVideoWithUrl.docx");
        }
    }
}