### Set Different Page Setup for Document Sections Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Demonstrates how to apply different page setup configurations, such as orientation, to individual document sections. This example changes the orientation of the second section to landscape. ```csharp // Create a new instance of the Document class and load a Word document Document doc = new Document(); // Get the second section of the document Section SectionTwo = doc.Sections[1]; // Set the page orientation of the second section to Landscape SectionTwo.PageSetup.Orientation = PageOrientation.Landscape; // Uncomment the following line to set a custom page size for the second section // SectionTwo.PageSetup.PageSize = new SizeF(800, 800); ``` -------------------------------- ### Example: Applying a Text Watermark Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/images-and-shapes.md A complete example showing how to load a document, apply a text watermark, and save the modified document. ```csharp Document doc = new Document(); doc.LoadFromFile("template.docx"); TextWatermark watermark = new TextWatermark("DRAFT", 1, 120, Color.LightGray, 0.3f); doc.Watermark = watermark; doc.SaveToFile("watermarked.docx", FileFormat.Docx); ``` -------------------------------- ### Install Spire.Doc for .NET via NuGet Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/README.md Install the Spire.Doc for .NET library using the NuGet Package Manager console. ```csharp // Install via NuGet // Install-Package Spire.Doc ``` -------------------------------- ### Clone Section Page Setup Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/section.md Copies the page setup properties (height, width, margins) from an original section to a new section. ```csharp Section originalSection = doc.Sections[0]; Section clonedSection = doc.AddSection(); // Copy page setup clonedSection.PageSetup.PageHeight = originalSection.PageSetup.PageHeight; clonedSection.PageSetup.PageWidth = originalSection.PageSetup.PageWidth; clonedSection.PageSetup.TopMargin = originalSection.PageSetup.TopMargin; ``` -------------------------------- ### Bookmark Example Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/bookmarks-comments.md Demonstrates how to create a bookmark, add text within it, and append subsequent content. Saves the document to a file. ```csharp Document doc = new Document(); Section section = doc.AddSection(); Paragraph para1 = section.AddParagraph(); para1.AppendBookmarkStart("Section1"); para1.AppendText("This is bookmarked content"); para1.AppendBookmarkEnd("Section1"); Paragraph para2 = section.AddParagraph(); para2.AppendText("This is after the bookmark"); // Access bookmark content doc.SaveToFile("bookmarked.docx", FileFormat.Docx); ``` -------------------------------- ### Create New Document Instance Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/document.md Instantiates a new, empty Document object. This is the starting point for creating a document from scratch. ```csharp public Document() ``` -------------------------------- ### C# Example: Inserting and Configuring a DocPicture Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/images-and-shapes.md Demonstrates how to create a DocPicture, load an image, set its dimensions and text wrapping style, and add it to a paragraph. ```csharp Document doc = new Document(); Section section = doc.AddSection(); Paragraph para = section.AddParagraph(); DocPicture picture = new DocPicture(doc); picture.LoadImage("image.png"); picture.Width = 200; picture.Height = 150; picture.TextWrappingStyle = TextWrappingStyle.Through; para.ChildObjects.Add(picture); ``` -------------------------------- ### Comment Example Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/bookmarks-comments.md Demonstrates appending a comment to a paragraph, setting its author, initials, and date, and then saving the document. ```csharp Document doc = new Document(); Section section = doc.AddSection(); Paragraph para = section.AddParagraph(); TextRange textRange = para.AppendText("This text has a comment"); Comment comment = para.AppendComment("Author's note"); comment.Author = "John Smith"; comment.Initial = "JS"; comment.Date = DateTime.Now; doc.SaveToFile("with_comment.docx", FileFormat.Docx); ``` -------------------------------- ### Get Bookmark Content Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/bookmarks-comments.md Illustrates how to load a document and iterate through its sections and child objects to find and process bookmark content marked by PermissionStart. ```csharp Document doc = new Document(); doc.LoadFromFile("document_with_bookmarks.docx"); // Access Bookmarks through document // Bookmarks are accessible via TextBody objects foreach (Section section in doc.Sections) { // Bookmarks can be iterated through child objects foreach (DocumentObject obj in section.Body.ChildObjects) { // Check for PermissionStart (bookmark start marker) if (obj is PermissionStart) { PermissionStart start = obj as PermissionStart; // Process bookmark } } } ``` -------------------------------- ### C# Example: Appending an Image to a Paragraph Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/images-and-shapes.md Shows how to append an image to a paragraph using AppendImage and set its width and height. ```csharp Paragraph para = section.AddParagraph(); DocPicture picture = para.AppendImage("photo.jpg"); picture.Width = 300; picture.Height = 200; ``` -------------------------------- ### Set Transparency for a Textbox Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example demonstrates how to create a Word document, add a textbox, set its fill color, and then adjust its fill transparency. ```csharp //Create a word document Document doc = new Document(); //Create a new section Section section = doc.AddSection(); //Create a new paragraph Paragraph paragraph = section.AddParagraph(); //Append TextBox Spire.Doc.Fields.TextBox textbox1 = paragraph.AppendTextBox(100, 50); //Set fill color textbox1.Format.FillColor = Color.Red; //Set fill transparency textbox1.FillTransparency = 0.45; ``` -------------------------------- ### Mark Bookmark Start Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/bookmarks-comments.md Marks the beginning of a bookmark range within the document. ```csharp public PermissionStart AppendBookmarkStart(string bookmarkName) ``` -------------------------------- ### Convert RTF to PDF Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example demonstrates how to convert an RTF file to a PDF document using Spire.Doc. Ensure the input and output file paths are correctly specified. ```csharp // Create Word document Document document = new Document(); // Load the RTF file from disk document.LoadFromFile(inputFile, FileFormat.Rtf); // Save as PDF document.SaveToFile(outputFile, FileFormat.PDF); // Dispose the document document.Dispose(); ``` -------------------------------- ### Extract Math Equations to MathML Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example demonstrates how to load a Word document, iterate through its sections and paragraphs to find OfficeMath objects, and convert them into MathML code. The extracted MathML is then appended to a StringBuilder. ```csharp Document doc = new Document(); doc.LoadFromFile("input.docx"); List mathEquations = new List(); StringBuilder stringBuilder = new StringBuilder(); foreach (Section section in doc.Sections) { foreach (Paragraph paragraph in section.Paragraphs) { foreach (DocumentObject obj in paragraph.ChildObjects) { if (obj is OfficeMath) { stringBuilder.AppendLine((obj as OfficeMath).ToMathMLCode()); stringBuilder.AppendLine(); mathEquations.Add(obj as OfficeMath); } } } } ``` -------------------------------- ### Clone a Word Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows how to create an exact copy of an existing Word document using the Clone() method in Spire.Doc. The cloned document can then be saved or modified independently. ```csharp // Create a new instance of the Document class. Document document = new Document(); // Load a document from the specified file path. document.LoadFromFile("Template_Docx_1.docx"); // Clone the document and assign it to a new Document object. Document newDoc = document.Clone(); // Save the cloned document to a file with the specified output file name and format. newDoc.SaveToFile("Result-CloneWordDocument.docx", FileFormat.Docx2013); // Clean up resources used by the documents. document.Dispose(); newDoc.Dispose(); ``` -------------------------------- ### Execute Basic Mail Merge Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows the basic execution of a mail merge operation in a Word document. It prepares field names and values and then initiates the merge process. ```csharp Document document = new Document(); string[] fieldNames = new string[] { /* field names */ }; string[] fieldValues = new string[] { /* field values */ }; document.MailMerge.Execute(fieldNames, fieldValues); ``` -------------------------------- ### Create a Simple Hello World Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Demonstrates how to create a new Word document and add a "Hello World!" text to it. ```csharp // Create a new Document object Document document = new Document(); // Add a new Section to the document Section section = document.AddSection(); // Add a new Paragraph to the section Paragraph paragraph = section.AddParagraph(); // Add text content to the paragraph paragraph.AppendText("Hello World!"); ``` -------------------------------- ### Get Form Fields Collection from Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows how to get the collection of all form fields within the first section of a document and retrieve the total count of form fields. ```csharp // Get the first section of the document Section section = document.Sections[0]; // Get the collection of form fields in the section FormFieldCollection formFields = section.Body.FormFields; // Get the count of form fields in the section int fieldCount = formFields.Count; ``` -------------------------------- ### Handle Mail Merge Events for Page Breaks Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows how to subscribe to the MergeField event to add page breaks before specific merge fields, useful for grouping data. The `AddPageBreakForMergeField` helper method traverses previous siblings to find the group start. ```csharp // Subscribe to the MergeField event document.MailMerge.MergeField += new MergeFieldEventHandler(MailMerge_MergeField); // Execute the mail merge using the customerRecords list as the data source document.MailMerge.ExecuteGroup(new MailMergeDataTable("Customer", customerRecords)); void MailMerge_MergeField(object sender, MergeFieldEventArgs args) { // Check if the current row index is greater than the lastIndex if (args.RowIndex > lastIndex) { // Update the lastIndex with the current row index lastIndex = args.RowIndex; // Add a page break before the current merge field AddPageBreakForMergeField(args.CurrentMergeField); } } void AddPageBreakForMergeField(IMergeField mergeField) { // Find position of needing to add page break bool foundGroupStart = false; Paragraph paragraph = mergeField.PreviousSibling.Owner as Paragraph; MergeField previousMergeField = null; // Find the group start merge field by traversing the previous sibling paragraphs while (!foundGroupStart) { paragraph = paragraph.PreviousSibling as Paragraph; for (int i = 0; i < paragraph.Items.Count; i++) { previousMergeField = paragraph.Items[i] as MergeField; if ((previousMergeField != null) && (previousMergeField.Prefix == "GroupStart")) { foundGroupStart = true; break; } } } // Append a page break to the paragraph paragraph.AppendBreak(BreakType.PageBreak); } ``` -------------------------------- ### Extract Document Content Starting from Form Field Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This snippet demonstrates how to extract document content starting from a specific form field. It iterates through form fields to find a text input, identifies its containing paragraph, and copies subsequent child objects to a new document. ```csharp Document sourceDocument = new Document(); Document destinationDoc = new Document(); Section section = destinationDoc.AddSection(); int index = 0; // Iterate through each form field in the body of the source document's first section. foreach (FormField field in sourceDocument.Sections[0].Body.FormFields) { // Check if the form field is of type FieldFormTextInput. if (field.Type == FieldType.FieldFormTextInput) { // Get the paragraph that contains the form field. Paragraph paragraph = field.OwnerParagraph; // Find the index of the paragraph within the child objects of the source document's body. index = sourceDocument.Sections[0].Body.ChildObjects.IndexOf(paragraph); // Exit the loop after finding the first form text input field. break; } } // Copy three consecutive child objects starting from the found index from the source document's body to the destination document's section. for (int i = index; i < index + 3; i++) { // Clone the child object at the current index. DocumentObject doobj = sourceDocument.Sections[0].Body.ChildObjects[i].Clone(); // Add the cloned child object to the body of the destination document's section. section.Body.ChildObjects.Add(doobj); } ``` -------------------------------- ### Create and Customize SmartArt Graphics Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Demonstrates creating various SmartArt types, setting node text and font size, and customizing shape fill color. Requires importing necessary Spire.Doc namespaces. ```csharp public partial class Form1 : Form { private const int SmartArtDefaultWidth = 432; private const int SmartArtDefaultHeight = 252; private const float TitleFontSize = 28f; private const float DefaultNodeFontSize = 15f; private void button1_Click(object sender, EventArgs e) { Document document = new Document(); Section section = document.AddSection(); List smartArtTypes = new List { SmartArtType.VerticalChevronList, SmartArtType.SquareAccentList, SmartArtType.AlternatingHexagons, SmartArtType.HorizontalBulletList, SmartArtType.SegmentedProcess, SmartArtType.VerticalBendingProcess, SmartArtType.StepDownProcess, SmartArtType.CircleAccentTimeLine, SmartArtType.BlockCycle, SmartArtType.SegmentedCycle }; foreach (SmartArtType smartArtType in smartArtTypes) { CreateTitleParagraph(section, smartArtType.ToString()); var paragraph = section.AddParagraph(); var smartArt = CreateSmartArt(paragraph, smartArtType); SmartArtShapeProperties shapeSmartArt = smartArt.Nodes[0].ShapeProperties[0]; shapeSmartArt.Fill.FillType = FillType.Solid; shapeSmartArt.Fill.Color = Color.FromArgb(255, 255, 165, 0); SetSmartArtNodeText(smartArt.Nodes[0], "TextTest_1", 15f); AddSmartArtChildNode(smartArt.Nodes[0], 15f, "ChildNodeTest_1."); SetSmartArtNodeText(smartArt.Nodes[1], "TextTest_2", 25f); AddSmartArtChildNode(smartArt.Nodes[1], 15f, "ChildNodeTest_2."); } } private Paragraph CreateTitleParagraph(Section section, string titleText, float fontSize = TitleFontSize) { var paragraph = section.AddParagraph(); paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center; var textRange = paragraph.AppendText(titleText); textRange.CharacterFormat.FontSize = fontSize; textRange.CharacterFormat.FontName = "Times New Roman"; section.AddParagraph(); section.AddParagraph(); return paragraph; } private SmartArt CreateSmartArt(Paragraph paragraph, SmartArtType smartArtType, int width = SmartArtDefaultWidth, int height = SmartArtDefaultHeight) { paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center; Shape shape = paragraph.AppendSmartArt(smartArtType, width, height); return shape.SmartArt; } private void SetSmartArtNodeText(SmartArtNode node, string text, float fontSize = DefaultNodeFontSize) { if (node == null || string.IsNullOrEmpty(text)) return; node.Text = text; if (node.Paragraphs.Count > 0 && node.Paragraphs[0].ChildObjects.Count > 0) { ((TextRange)node.Paragraphs[0].ChildObjects[0]).CharacterFormat.FontSize = fontSize; } } private void AddSmartArtChildNode(SmartArtNode parentNode, float fontSize, params string[] childTexts) { if (parentNode == null || childTexts == null || childTexts.Length == 0) return; while (parentNode.ChildNodes.Count < childTexts.Length) { parentNode.ChildNodes.Add(); } for (int i = 0; i < childTexts.Length && i < parentNode.ChildNodes.Count; i++) { SetSmartArtNodeText(parentNode.ChildNodes[i], childTexts[i], fontSize); } } } ``` -------------------------------- ### Get the namespace for the Section class Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/section.md The Section class resides within the Spire.Doc.Documents namespace. ```csharp Spire.Doc.Documents ``` -------------------------------- ### Set Table and Cell Borders Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows how to apply different border styles to an entire table and to a specific cell within that table. It includes helper methods for setting table and cell borders. ```csharp // Get the first table in the document's first section Table table = document.Sections[0].Tables[0] as Table; // Set borders for the entire table setTableBorders(table); // Set borders for a specific cell in the table setCellBorders(table.Rows[2].Cells[0]); private void setTableBorders(Table table) { table.Format.Borders.BorderType = Spire.Doc.Documents.BorderStyle.Single; table.Format.Borders.LineWidth = 3.0F; table.Format.Borders.Color = Color.Red; } private void setCellBorders(TableCell tableCell) { tableCell.CellFormat.Borders.BorderType = Spire.Doc.Documents.BorderStyle.DotDash; tableCell.CellFormat.Borders.LineWidth = 1.0F; tableCell.CellFormat.Borders.Color = Color.Green; } ``` -------------------------------- ### Create a Word Document in C# Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/README.md Demonstrates how to create a new Word document, add a section and paragraph, append text, and save the document using Spire.Doc for .NET. ```csharp //Create a Document instance Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph para = section.AddParagraph(); //Append text to the paragraph para.AppendText("Hello World"); //Save the result document doc.SaveToFile(@"C:\Users\Administrator\Desktop\Output.docx", FileFormat.Docx2013); ``` -------------------------------- ### Mark Bookmark End Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/bookmarks-comments.md Marks the end of a bookmark range, requiring a matching name to the start marker. ```csharp public PermissionEnd AppendBookmarkEnd(string bookmarkName) ``` -------------------------------- ### Basic Spire.Doc for .NET Workflow Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/INDEX.md This outlines the fundamental steps for creating, manipulating, and saving documents using Spire.Doc for .NET. It covers document creation, adding sections and content, applying formatting, and saving the document in a specified format. ```csharp 1. Create Document 2. Add Section(s) 3. Add Paragraph(s) / Table(s) 4. Add Content (Text, Images, Fields) 5. Apply Formatting (CharacterFormat, ParagraphFormat) 6. Save to File (FileFormat) ``` -------------------------------- ### Get Paragraph at Index Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/table.md Retrieves a paragraph from a table cell at a specified index. Cells can contain multiple paragraphs. ```csharp public Paragraph Paragraphs[int index] // Get paragraph at index ``` -------------------------------- ### Create and Format a Table Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/table.md Creates a new table with a specified number of rows and columns, formats the header row with a gray background, and adds text to header cells. It then populates the data rows with sample text. ```csharp Document doc = new Document(); Section section = doc.AddSection(); Table table = section.AddTable(true); table.ResetCells(3, 3); // Format header row TableRow headerRow = table.Rows[0]; headerRow.IsHeader = true; for (int i = 0; i < headerRow.Cells.Count; i++) { TableCell cell = headerRow.Cells[i]; cell.CellFormat.Shading.BackgroundPatternColor = Color.Gray; Paragraph para = cell.AddParagraph(); para.AppendText($"Header {i + 1}"); } // Add data rows for (int r = 1; r < table.Rows.Count; r++) { TableRow row = table.Rows[r]; for (int c = 0; c < row.Cells.Count; c++) { TableCell cell = row.Cells[c]; Paragraph para = cell.AddParagraph(); para.AppendText($"Row {r}, Col {c}"); } } doc.SaveToFile("table.docx", FileFormat.Docx); ``` -------------------------------- ### Set Gutter Position in Document Section Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Configures the page setup for a document section to enable and set the width of the gutter. ```csharp // Get the first section of the document. Section section = document.Sections[0]; // Set the top gutter option to true for the section's page setup. section.PageSetup.IsTopGutter = true; // Set the width of the gutter in points (100f). section.PageSetup.Gutter = 100f; ``` -------------------------------- ### Configure Page Settings, Headers, Footers, and Tables Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Configures page setup including size and margins, adds headers and footers with text and page numbering, and inserts a basic table with a header row. This snippet demonstrates comprehensive document customization. ```csharp // Create a new Document object. Document document = new Document(); // Add a new section to the document. Section section = document.AddSection(); // Set the page size of the section to A4. section.PageSetup.PageSize = PageSize.A4; // Set the top margin of the section to 72 points (1 inch). section.PageSetup.Margins.Top = 72f; // Set the bottom margin of the section to 72 points (1 inch). section.PageSetup.Margins.Bottom = 72f; // Set the left margin of the section to 89.85 points (approximately 1.27 cm). section.PageSetup.Margins.Left = 89.85f; // Set the right margin of the section to 89.85 points (approximately 1.27 cm). section.PageSetup.Margins.Right = 89.85f; // Insert headers and footers in the section. HeaderFooter header = section.HeadersFooters.Header; HeaderFooter footer = section.HeadersFooters.Footer; // Add a paragraph to the header and insert text. Paragraph headerParagraph = header.AddParagraph(); TextRange text = headerParagraph.AppendText("Demo of Spire.Doc"); text.CharacterFormat.FontName = "Arial"; text.CharacterFormat.FontSize = 10; text.CharacterFormat.Italic = true; headerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; headerParagraph.Format.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Single; headerParagraph.Format.Borders.Bottom.Space = 0.05F; // Add a paragraph to the footer and insert fields for page numbering. Paragraph footerParagraph = footer.AddParagraph(); footerParagraph.AppendField("page number", FieldType.FieldPage); footerParagraph.AppendText(" of "); footerParagraph.AppendField("number of pages", FieldType.FieldNumPages); footerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; footerParagraph.Format.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Single; footerParagraph.Format.Borders.Top.Space = 0.05F; // Add a table to the section. String[] tableHeader = { "Name", "Capital", "Continent", "Area", "Population" }; Spire.Doc.Table table = section.AddTable(true); // Set the number of rows and columns in the table. table.ResetCells(1, tableHeader.Length); // Only header row // First Row (Table Header) TableRow row = table.Rows[0]; row.IsHeader = true; row.Height = 20; row.HeightType = TableRowHeightType.Exactly; for (int i = 0; i < row.Cells.Count; i++) { row.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Gray; } // Populate the header cells with text and formatting. for (int i = 0; i < tableHeader.Length; i++) { row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p = row.Cells[i].AddParagraph(); p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; TextRange txtRange = p.AppendText(tableHeader[i]); txtRange.CharacterFormat.Bold = true; } ``` -------------------------------- ### Convert Word to PDF, HTML, and XPS in C# Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/README.md Shows how to load an existing Word document and convert it to PDF, HTML, and XPS formats using Spire.Doc for .NET. Ensure the input file exists at the specified path. ```csharp //Create a Document instance Document document = new Document(); //Load a sample document document.LoadFromFile(@"C:\Users\Administrator\Desktop\Template.docx"); //Save to PDF document.SaveToFile("Sample.pdf", FileFormat.PDF); //Save to HTML document.SaveToFile("toHTML.html", FileFormat.Html); //Save to XPS document.SaveToFile("Sample.xps", FileFormat.XPS); ``` -------------------------------- ### Get Table Positioning Information Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Retrieves detailed positioning and spacing information for a table if text wrapping is enabled around it. ```csharp // Get the first section of the document Section section = document.Sections[0]; // Get the first table in the section Table table = section.Tables[0] as Table; // Check if text wrapping is enabled around the table if (table.Format.WrapTextAround) { // Get the positioning information for the table TablePositioning position = table.Format.Positioning; // Horizontal positioning information float horizPosition = position.HorizPosition; HorizontalPositionAbs horizPositionAbs = position.HorizPositionAbs; HorizontalRelation horizRelationTo = position.HorizRelationTo; // Vertical positioning information float vertPosition = position.VertPosition; VerticalPositionAbs vertPositionAbs = position.VertPositionAbs; VerticalRelation vertRelationTo = position.VertRelationTo; // Distance from surrounding text float distanceFromTop = position.DistanceFromTop; float distanceFromLeft = position.DistanceFromLeft; float distanceFromBottom = position.DistanceFromBottom; float distanceFromRight = position.DistanceFromRight; } ``` -------------------------------- ### Create and Save a New Word Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/README.md Demonstrates the basic steps to create a new Word document, add a section and a paragraph with text, and save it to a file. ```csharp using Spire.Doc; using Spire.Doc.Documents; // Create a document Document doc = new Document(); // Add a section Section section = doc.AddSection(); // Add a paragraph Paragraph para = section.AddParagraph(); // Add text para.AppendText("Hello World!"); // Save the document doc.SaveToFile("output.docx", FileFormat.Docx); // Clean up doc.Dispose(); ``` -------------------------------- ### Add Basic Header and Footer Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/headers-footers.md Demonstrates how to add a simple header and footer to a Word document. Ensure the Spire.Doc library is referenced. ```csharp Document doc = new Document(); Section section = doc.AddSection(); // Add main content Paragraph para = section.AddParagraph(); para.AppendText("Document body content"); // Add header HeaderFooter header = section.HeadersFooters.Header; Paragraph headerPara = header.AddParagraph(); headerPara.AppendText("My Document Header"); headerPara.Format.HorizontalAlignment = HorizontalAlignment.Center; // Add footer HeaderFooter footer = section.HeadersFooters.Footer; Paragraph footerPara = footer.AddParagraph(); footerPara.AppendText("Page 1"); footerPara.Format.HorizontalAlignment = HorizontalAlignment.Right; doc.SaveToFile("with_headers_footers.docx", FileFormat.Docx); ``` -------------------------------- ### Get a paragraph by index Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/section.md Access a specific paragraph within the section using its zero-based index via the Paragraphs indexer. ```csharp public Paragraph Paragraphs[int index] ``` -------------------------------- ### Create and Save Word Chart as Template Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Demonstrates how to create a Word document with a column chart and save the chart as a template file (.crtx). Requires Spire.Doc. ```csharp Document doc = new Document(); Section section = doc.AddSection(); Paragraph paragraph = section.AddParagraph(); Chart chart = ((Shape)paragraph.AppendChart(ChartType.Column, 400, 300)).Chart; chart.SaveAsTemplate("SaveChartToTemplate.crtx"); doc.Close(); doc.Dispose(); ``` -------------------------------- ### Embed Non-Installed Fonts in PDF Conversion Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Use PrivateFontPaths in ToPdfParameterList to embed fonts that are not installed on the system when converting Word to PDF. ```csharp // Create a new instance of the Document class. Document document = new Document(); // Load a Word document from the specified file path. document.LoadFromFile("input.docx"); // Create a new instance of the ToPdfParameterList class. ToPdfParameterList parms = new ToPdfParameterList(); // Create a list to hold the paths of private fonts to be embedded. List fonts = new List(); // Add a new PrivateFontPath object to the list, specifying the font name and its file path. fonts.Add(new PrivateFontPath("PT Serif Caption", "PT_Serif-Caption-Web-Regular.ttf")); // Set the PrivateFontPaths property of the parameter list to the created list of fonts. parms.PrivateFontPaths = fonts; // Save the document as a PDF file with the specified parameters. document.SaveToFile("EmbedNoninstalledFonts.pdf", parms); // Dispose of the document to free up resources. document.Dispose(); ``` -------------------------------- ### Load Document from File and Save to Disk in C# Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This snippet demonstrates the basic process of loading a document from a file path and saving it to another location with a specified format. Ensure the `inputPath` and `outputPath` variables are correctly defined. ```csharp // Create a new instance of the Document class Document doc = new Document(); // Load the document from the specified input file doc.LoadFromFile(inputPath); // Save the document to a file with the specified output file name and file format doc.SaveToFile(outputPath, FileFormat.Docx); // Dispose of the document object to free up resources doc.Dispose(); ``` -------------------------------- ### Add Text Watermark to Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/images-and-shapes.md A practical example of adding a 'CONFIDENTIAL' text watermark to a business letter document and saving the result. ```csharp Document doc = new Document(); doc.LoadFromFile("business_letter.docx"); // Add text watermark TextWatermark textWM = new TextWatermark("CONFIDENTIAL", 1, 100, Color.Red, 0.3f); doc.Watermark = textWM; doc.SaveToFile("confidential.docx", FileFormat.Docx); ``` -------------------------------- ### Find Text and Get Page Number Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Locates all occurrences of a specific string within a document and determines the page number for each instance. ```csharp // Create a new Document object Document document = new Document(); // Find all occurrences of the string "Spire" in the document TextSelection[] textSelections = document.FindAllString("Spire", false, false); // Create a FixedLayoutDocument object using the loaded document FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document); // Initialize a counter for matched words int count = 1; // Create a StringBuilder to store the result StringBuilder builder = new StringBuilder(); // Iterate through each TextSelection foreach (TextSelection selection in textSelections) { // Get the layout entities for the current selection foreach (FixedLayoutSpan line in layoutDoc.GetLayoutEntitiesOfNode(selection.GetRanges()[0])) { // Get the page index where the matched word is located int index = line.PageIndex; // Append the result to the StringBuilder builder.AppendLine("The matched word " + count + " is on page:" + index); // Increment the counter count++; } } ``` -------------------------------- ### AppendBookmarkEnd Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/bookmarks-comments.md Marks the end of a bookmark range. The provided bookmark name must match the name used when starting the bookmark range. ```APIDOC ## AppendBookmarkEnd ### Description Marks the end of a bookmark range. ### Method ```csharp public PermissionEnd AppendBookmarkEnd(string bookmarkName) ``` ### Parameters #### Path Parameters - **bookmarkName** (string) - Yes - Bookmark name (must match start) ``` -------------------------------- ### Create Formatted Text with Character Styles Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/paragraph.md Demonstrates how to apply various character formatting, such as bold, italic, color, and font size, to different parts of a paragraph. Ensure a Document and Section are created. ```csharp Document doc = new Document(); Section section = doc.AddSection(); Paragraph para = section.AddParagraph(); para.AppendText("Normal "); TextRange bold = para.AppendText("bold"); bold.CharacterFormat.Bold = true; TextRange italic = para.AppendText(" italic "); italic.CharacterFormat.Italic = true; TextRange colored = para.AppendText("colored"); colored.CharacterFormat.TextColor = Color.Red; colored.CharacterFormat.FontSize = 14; doc.SaveToFile("formatted.docx", FileFormat.Docx); ``` -------------------------------- ### Print Word Document Using XPS Printing Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example demonstrates how to print a Word document by first converting it to XPS format in memory and then sending it to a specified printer. This method is useful for direct printing without user interaction via a dialog. Ensure the Spire.Doc.XpsPrint library is referenced. ```csharp // Create a new MemoryStream for storing the document as XPS using (MemoryStream ms = new MemoryStream()) { // Instantiate a new Document object using (Document document = new Document()) { // Load the Word document document.LoadFromFile("document.docx"); // Save the document to the MemoryStream as XPS format document.SaveToStream(ms, FileFormat.XPS); } // Reset the position of the MemoryStream to the beginning ms.Position = 0; // Specify the printer name to be used for printing String printerName = "Printer Name"; // Print the XPS document using the specified printer and job name XpsPrint.XpsPrintHelper.Print(ms, printerName, "Printing Job", true); } ``` -------------------------------- ### Hide a Row in a Word Table Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Set the 'Hidden' property of a TableRow object to true to hide it. This example targets the first row of a table. ```csharp TableRow row = table.Rows[0]; row.Hidden = true; ``` -------------------------------- ### PDF Conversion with Parameters Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/conversion.md Performs PDF conversion with advanced options. Configure parameters using ToPdfParameterList before saving. ```csharp Document doc = new Document(); doc.LoadFromFile("document.docx"); // Advanced PDF conversion options available through ToPdfParameterList ToPdfParameterList pdfParams = new ToPdfParameterList(); // Configure PDF parameters if needed // pdfParams.CreateOutlines = true; // pdfParams.PreserveMeta = true; doc.SaveToFile("advanced.pdf", FileFormat.PDF); ``` -------------------------------- ### Insert Picture into a Table Cell Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example demonstrates how to insert an image into a specific cell of a Word table and set its dimensions using Spire.Doc. ```csharp //Get the first table from the first section of the document Table table = (Table)doc.Sections[0].Tables[0]; //Add a picture to the specified table cell DocPicture picture = table.Rows[1].Cells[2].Paragraphs[0].AppendPicture(Image.FromFile(imagePath)); //Set picture width picture.Width = 100; //Set picture height picture.Height = 100; ``` -------------------------------- ### Configure PageSetup for Headers/Footers Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/headers-footers.md Adjusts header and footer distances from margins and enables different first page and odd/even page headers/footers. ```csharp Section section = doc.Sections[0]; PageSetup pageSetup = section.PageSetup; // Control spacing from margins to header/footer pageSetup.HeaderDistance = 0.5f; // Distance in inches from top margin pageSetup.FooterDistance = 0.5f; // Distance in inches from bottom margin // Different first page pageSetup.DifferentFirstPageHeaderFooter = true; // Different odd/even pages pageSetup.DifferentOddEvenHeaderFooter = true; // Page margins affect header/footer positioning pageSetup.TopMargin = 1.0f; pageSetup.BottomMargin = 1.0f; ``` -------------------------------- ### Get Bookmarks from Word Document by Index and Name Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This snippet demonstrates how to retrieve Bookmark objects from a Word document using their index and name. ```csharp //Create word document Document document = new Document(); //Get the bookmark by index. Bookmark bookmark1 = document.Bookmarks[0]; //Get the bookmark by name. Bookmark bookmark2 = document.Bookmarks["Test2"]; ``` -------------------------------- ### Convert Document to Byte Array and Back Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Demonstrates converting a Word document to a byte array and then reconstructing a document from that byte array. ```csharp // Create a new instance of the Document class. Document doc = new Document(); // Load the document from the specified input file. doc.LoadFromFile(input); // Create a new MemoryStream to store the document content. MemoryStream outStream = new MemoryStream(); // Save the document to the MemoryStream in Docx format. doc.SaveToStream(outStream, FileFormat.Docx); // Convert the content of the MemoryStream to a byte array. byte[] docBytes = outStream.ToArray(); // The bytes are now ready to be stored/transmitted. // Create a new MemoryStream from the byte array. MemoryStream inStream = new MemoryStream(docBytes); // Create a new Document object by loading from the MemoryStream. Document newDoc = new Document(inStream); // Dispose the existing document object. doc.Dispose(); ``` -------------------------------- ### Create Formatted Table in Word Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This snippet shows how to create a table with headers, sample data, and apply formatting such as background colors and bold text to headers. It also demonstrates alternating row background colors. ```csharp // Create a new document Document document = new Document(); // Add a section to the document Section section = document.AddSection(); // Define the table headers String[] header = { "Name", "Capital", "Continent", "Area", "Population" }; // Sample data for the table String[][] data = { new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"}, new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"}, new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"} }; // Create a new table in the section Spire.Doc.Table table = section.AddTable(true); table.ResetCells(data.Length + 1, header.Length); // Set the properties for the first row (header row) TableRow headerRow = table.Rows[0]; headerRow.IsHeader = true; headerRow.Height = 20; headerRow.HeightType = TableRowHeightType.Exactly; for (int i = 0; i < headerRow.Cells.Count; i++) { headerRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Gray; } // Populate the cells in the header row with the header values for (int i = 0; i < header.Length; i++) { headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p = headerRow.Cells[i].AddParagraph(); p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; TextRange txtRange = p.AppendText(header[i]); txtRange.CharacterFormat.Bold = true; } // Populate the table rows with data for (int r = 0; r < data.Length; r++) { TableRow dataRow = table.Rows[r + 1]; dataRow.Height = 20; dataRow.HeightType = TableRowHeightType.Exactly; for (int i = 0; i < dataRow.Cells.Count; i++) { dataRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Empty; } // Populate the cells in the data rows with the corresponding data values for (int c = 0; c < data[r].Length; c++) { dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle; dataRow.Cells[c].AddParagraph().AppendText(data[r][c]); } } // Apply background color to alternate rows for (int j = 1; j < table.Rows.Count; j++) { if (j % 2 == 0) { TableRow row2 = table.Rows[j]; for (int f = 0; f < row2.Cells.Count; f++) { row2.Cells[f].CellFormat.Shading.BackgroundPatternColor = Color.LightBlue; } } } ``` -------------------------------- ### Create Multi-Section Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/section.md Adds multiple sections to a document, allowing for different page setups like orientation. Save the document to a DOCX file. ```csharp Document doc = new Document(); // First section Section section1 = doc.AddSection(); Paragraph para1 = section1.AddParagraph(); para1.AppendText("Section 1 Content"); // Second section with different page setup Section section2 = doc.AddSection(); section2.PageSetup.Orientation = PageOrientation.Landscape; Paragraph para2 = section2.AddParagraph(); para2.AppendText("Section 2 in Landscape"); doc.SaveToFile("multi_section.docx", FileFormat.Docx); ``` -------------------------------- ### Create Pie Chart in Word Document Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example demonstrates how to create a pie chart in a Word document and add a single series with labels and values. ```csharp // Create a new instance of Document Document document = new Document(); // Add a section to the document Section section = document.AddSection(); // Add a paragraph to the section and append text to it section.AddParagraph().AppendText("Pie chart."); // Add a new paragraph to the section Paragraph newPara = section.AddParagraph(); // Append a pie chart shape to the paragraph with specified width and height ShapeObject shape = newPara.AppendChart(ChartType.Pie, 500, 300); Chart chart = shape.Chart; // Add a series to the chart with categories (labels) and corresponding data values ChartSeries series = chart.Series.Add("Test Series", new[] { "Word", "PDF", "Excel" }, new[] { 2.7, 3.2, 0.8 }); ``` -------------------------------- ### Integrate Font Tables and Clone Sections in C# Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows how to integrate the font table from a source document into a destination document and then clone all sections from the source to the destination. This is useful for merging documents while ensuring consistent font usage. ```csharp // Create document instances Document destDoc = new Document(); Document srcDoc = new Document(); // Integrate the current document font table to the destination document srcDoc.IntegrateFontTableTo(destDoc); // Iterate through each section in the source document. foreach (Section section in srcDoc.Sections) { // Clone each section and add it to the destination document. destDoc.Sections.Add(section.Clone()); } ``` -------------------------------- ### Execute Conditional IF Fields in Mail Merge Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This example shows how to create and execute conditional IF fields within a mail merge operation using Spire.Doc. ```csharp // Create a new Document object Document doc = new Document(); // Add a Section to the document Section section = doc.AddSection(); // Add a Paragraph to the section Paragraph paragraph = section.AddParagraph(); // Create a new IfField object IfField ifField1 = new IfField(doc); // Set the type and code of the IfField ifField1.Type = FieldType.FieldIf; ifField1.Code = "IF "; // Add the IfField to the paragraph paragraph.Items.Add(ifField1); // Append the fields and text to the paragraph paragraph.AppendField("Count", FieldType.FieldMergeField); paragraph.AppendText(" > "); paragraph.AppendText("\"1\" "); paragraph.AppendText("\"Greater than one\" "); paragraph.AppendText("\"Less than one\""); // Create and add the end field mark IParagraphBase end1 = doc.CreateParagraphItem(ParagraphItemType.FieldMark); (end1 as FieldMark).Type = FieldMarkType.FieldEnd; paragraph.Items.Add(end1); // Set the end field mark for the IfField ifField1.End = end1 as FieldMark; // Add another paragraph to the section paragraph = section.AddParagraph(); // Create a new IfField object IfField ifField2 = new IfField(doc); // Set the type and code of the IfField ifField2.Type = FieldType.FieldIf; ifField2.Code = "IF "; // Add the IfField to the paragraph paragraph.Items.Add(ifField2); // Append the fields and text to the paragraph paragraph.AppendField("Age", FieldType.FieldMergeField); paragraph.AppendText(" > "); paragraph.AppendText("\"50\" "); paragraph.AppendText("\"The old man\" "); paragraph.AppendText("\"The young man\""); // Create and add the end field mark IParagraphBase end2 = doc.CreateParagraphItem(ParagraphItemType.FieldMark); (end2 as FieldMark).Type = FieldMarkType.FieldEnd; paragraph.Items.Add(end2); // Set the end field mark for the IfField ifField2.End = end2 as FieldMark; // Set up field names and values for mail merge string[] fieldName = { "Count", "Age" }; string[] fieldValue = { "2", "30" }; // Execute the mail merge doc.MailMerge.Execute(fieldName, fieldValue); // Set IsUpdateFields property to true doc.IsUpdateFields = true; // Dispose the document object doc.Dispose(); ``` -------------------------------- ### Insert and Configure an Image in Word Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md Demonstrates how to load, rotate, and insert an image into a Word document with specified positioning and size. Requires the Spire.Doc library and a valid image file. ```csharp //Create a word document Document doc = new Document(); //Get the first section Section section = doc.Sections[0]; //Add a new section or get the first section Paragraph paragraph = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph(); //Append text paragraph.AppendText("The sample demonstrates how to insert an image into a document."); //Apply style paragraph.ApplyStyle(BuiltinStyle.Heading2); //Add a new paragraph paragraph = section.AddParagraph(); //Append text paragraph.AppendText("The above is a picture."); //Load an image Bitmap p = new Bitmap(Image.FromFile(@"..\..\..\..\..\..\Data\Word.png")); //rotate image and insert image to word document p.RotateFlip(RotateFlipType.Rotate90FlipX); //Create a DocPicture instance DocPicture picture = new DocPicture(doc); //Load the image picture.LoadImage(p); //set image's position picture.HorizontalPosition = 50.0F; picture.VerticalPosition = 60.0F; //set image's size picture.Width = 200; picture.Height = 200; //set textWrappingStyle with image; picture.TextWrappingStyle = TextWrappingStyle.Through; //Insert the picture at the beginning of the second paragraph paragraph.ChildObjects.Insert(0, picture); ``` -------------------------------- ### Create Math Equations from LaTeX and MathML Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/CS-Examples/doc_cs.md This snippet shows how to create OfficeMath objects from LaTeX and MathML code, and how to convert existing OfficeMath objects to MathML code. These are useful for dynamically generating mathematical content. ```csharp // Create an OfficeMath object from LaTeX math code officeMath = new OfficeMath(doc); officeMath.FromLatexMathCode(latexMathCode[i - 1]); paragraph.Items.Add(officeMath); // Convert OfficeMath object to MathML code paragraph.Text = mathEquations[i - 1].ToMathMLCode(); // Create an OfficeMath object from MathML code officeMath = new OfficeMath(doc); officeMath.FromMathMLCode(mathEquations[i - 1].ToMathMLCode()); paragraph.Items.Add(officeMath); ``` -------------------------------- ### Get Merge Field Names Source: https://github.com/eiceblue/spire.doc-for-.net/blob/master/_autodocs/document.md Retrieves an array of all merge field names present in the document. This is useful for preparing data for mail merge operations. ```csharp public string[] GetMergeFieldNames() ```