This C# tutorial shows how to insert text and paragraph to MS Word document.
All the text style (such as text font size, font weight, text color) and paragraph style (such as text alignment, line height, first line indent, borders) can be defined for the whole doucment, or just be customized for the target paragraph.
You can add text to .docx file using TextInline
object, Paragraph
object, and using WordDocumentBuilder
object.
WordDocumentBuilder
is flow content manager, so if there is much more content out of one Word page size, the left content will be added to the second page automatically.
WordDocument document = new WordDocument(); WordDocumentBuilder builder = new WordDocumentBuilder(document); //Set global style for text and paragraph builder.CharacterState.FontFamily = new ThemableFontFamily("Arial"); builder.CharacterState.FontSize = 16; builder.ParagraphState.LineSpacing = 1.2; builder.ParagraphState.FirstLineIndent = 40; //Insert text using builder directly builder.InsertText("Nomal text. "); //Insert one line with text, it will add line break automatically builder.InsertLine("Nomal line with auto line break. "); //So the text below will be added in a second paragraph builder.InsertText("Nomal text. "); //Insert text using TextInline object TextInline textInline = new TextInline(document); textInline.Text = "This text content is using TextInline object. "; textInline.FontSize = 20; builder.InsertInline(textInline); //Insert text with customized style builder.InsertText("Times New Roman, ").FontFamily = new ThemableFontFamily("Times New Roman"); builder.InsertText("bold, ").FontWeight = FontWeights.Bold; builder.InsertText("italic, ").FontStyle = FontStyles.Italic; builder.InsertText("underline, ").Underline.Pattern = UnderlinePattern.Single; builder.InsertText("colors ").ForegroundColor = new ThemableColor(Color.FromRgb(255, 0, 0)); //Add several paragraphs to page for (int i = 0; i < 20; i++) { builder.InsertParagraph(); for (int j = 1; j < 11; j++) { builder.InsertText("This is sentence " + j.ToString() + ". "); } } WordFile wordFile = new WordFile(); using (var stream = File.OpenWrite("AddText.docx")) { wordFile.Export(document, stream); }
We provide powerful & profession document & image controls: Convert the contents of word file to JPEG in c# solution for converting Word document to Tiff with high performance. How to export databse to excel file - C# Tutorial Export data from a DataTable object into an Excel sheet in C# and VB.NET applications. Find and Replace Text in Word with C# search a particular text you like to change and replace it with another value. Digitally sign a PDF form in C# To sign PDF documents, you need a digital certificate. C# PDF Text Search Library find a given string/text in PDF file. C#: insert text to an existing pdf add text and image to exising pdf page. You can download the complete C# code of this tutorial from here.