Paragraph

Paragraph (18)

Tuesday, 10 July 2018 09:32

Remove Paragraphs from Word document in C#

Written by support iceblue

Spire.Doc supports to remove a specific paragraph along with all of the paragraphs from a word document. This article elaborates how we can remove paragraphs from a word document using Spire.Doc and C#.

The example word document we used:

Remove Paragraphs from Word document in C#

Remove a specific paragraph

//Instantiate a Document object 
Document document = new Document();
//Load the Word document
document.LoadFromFile("Input.docx");

//Remove the first paragraph from the first section of the document
document.Sections[0].Paragraphs.RemoveAt(0);

//Save the document
document.SaveToFile("RemoveParagraph.docx", FileFormat.Docx2013);

Output:

Remove Paragraphs from Word document in C#

Remove all of the paragraphs

//Instantiate a Document object
Document document = new Document();
//Load the Word document
document.LoadFromFile("Input.docx");

//Remove paragraphs from every section in the document
foreach(Section section in document.Sections)
{
    section.Paragraphs.Clear();
}

//Save the document
document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);

Output:

Remove Paragraphs from Word document in C#

By using Spire.Doc, you can not only retrieve the style names of all paragraphs in a Word document, but also get the paragraphs with a specific style name. This is useful especially when you need to get the text in Title, Heading 1, Subtitle, etc.

Paragraph Style Names in Word Paragraph Style Names in Spire.Doc
Title Title
Heading 1 Heading1
Heading 2 Heading2
Heading 3 Heading3
Heading 4 Heading3
Subtitle Subtitle

Step 1: Load a sample Word file when initializing the Document object.

Document doc = new Document("sample.docx");

Step 2: Traverse the sections and paragraphs in the document and determine if the paragraph style name is "Heading1", if so, write the paragraph text on screen.

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        if (paragraph.StyleName == "Heading1")
        {
            Console.WriteLine(paragraph.Text);
        }
    }
}

Output:

Get Paragraphs by Style Name in Word in C#, VB.NET

Full Code:

[C#]
Document doc = new Document("sample.docx");
foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        if (paragraph.StyleName == "Heading1")
        {
            Console.WriteLine(paragraph.Text);
        }
    }
}
[VB.NET]
Dim doc As Document = New Document("sample.docx")
For Each section As Section In doc.Sections
    For Each paragraph As Paragraph In section.Paragraphs
        If paragraph.StyleName = "Heading1" Then
            Console.WriteLine(paragraph.Text)
        End If
    Next
Next

With Spire.Doc, we can set the formats for paragraph in C#. This article will focus on demonstrate how to set the spacing before and after the paragraph in C#.

Set the spacing before and after the paragraph for a newly added paragraph added by the method of paragraph.AppendHTML() to a new blank word document.

//create a new word document and add a section and paragraph to it.
Document doc = new Document();
Section sec = doc.AddSection();
Paragraph para = sec.AddParagraph();

//Add the text strings to the paragraph and set the style
para.AppendHTML("

Add a new paragraph to the word and set the spacing

"); para.ApplyStyle(BuiltinStyle.Heading1); //set the spacing before and after para.Format.BeforeAutoSpacing = false; para.Format.BeforeSpacing = 20; para.Format.AfterAutoSpacing = false; para.Format.AfterSpacing = 20; //save the document to file doc.SaveToFile("Result1.docx");

How to set the spacing before and after the paragraph in C#

//create a new word document and load the sample from file
Document document = new Document();
document.LoadFromFile("sample.docx", FileFormat.Docx);

//Add the text strings to the paragraph and set the style
Paragraph para = new Paragraph(document);        
TextRange textRange1 = para.AppendText("This is a inserted paragraph.");
textRange1.CharacterFormat.TextColor = Color.Blue;
textRange1.CharacterFormat.FontSize = 15;

//set the spacing before and after
para.Format.BeforeAutoSpacing = false;
para.Format.BeforeSpacing = 10;
para.Format.AfterAutoSpacing = false;
para.Format.AfterSpacing = 10;

//insert the added paragraph to the word document
document.Sections[0].Paragraphs.Insert(1, para);

//save the document to file
document.SaveToFile("Result2.docx",FileFormat.Docx2010);

How to set the spacing before and after the paragraph in C#

Monday, 18 September 2017 09:28

Add Tab Stops to Word Paragraphs in C#

Written by support iceblue

Tab stops are markers placed on the ruler that define how text or numbers are aligned on a line. To add tab stops to a paragraph in Microsoft Word, we need to open the Tabs dialog box and then set the tab stop position, alignment and leader as shown below.

Add Tab Stops to Word Paragraphs in C#

This article elaborates how to add tab stops to paragraphs in word document programmatically using Spire.Doc.

Detail steps:

Step 1: Instantiate a Document object and add a section to it.

Document document = new Document();
Section section = document.AddSection(); 

Step 2: Add paragraph 1 to the section.

Paragraph paragraph1 = section.AddParagraph();

Step 3: Add tab stops to paragraph 1.

//Add tab and set its position (in points)
Tab tab = paragraph1.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph1.AppendText("\tWashing Machine");

//Add another tab and set its position (in points)
tab = paragraph1.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.Dotted;
//move to next tab and append text
paragraph1.AppendText("\t$650"); 

Step 4: Add paragraph 2 to the section.

Paragraph paragraph2 = section.AddParagraph();

Step 5: Add tab stops to paragraph 2.

//Add tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph2.AppendText("\tRefrigerator");

//Add another tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.NoLeader;
//move to next tab and append text
paragraph2.AppendText("\t$800"); 

Step 6: Save and close the document object.

document.SaveToFile("Tab.docx", FileFormat.Docx2013);
document.Close();

Screenshot:

Add Tab Stops to Word Paragraphs in C#

Full code:

//Instantiate a Document object
Document document = new Document();
//Add a section
Section section = document.AddSection();            

//Add paragraph 1
Paragraph paragraph1 = section.AddParagraph();

//Add tab and set its position (in points)
Tab tab = paragraph1.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph1.AppendText("\tWashing Machine");

//Add another tab and set its position (in points)
tab = paragraph1.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.Dotted;
//move to next tab and append text
paragraph1.AppendText("\t$650"); 

//Add paragraph 2
Paragraph paragraph2 = section.AddParagraph();

//Add tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph2.AppendText("\tRefrigerator"); //move to next tab and append text

//Add another tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.NoLeader;
//move to next tab and append text
paragraph2.AppendText("\t$800"); 

//Save and close the document object            
document.SaveToFile("Tab.docx", FileFormat.Docx2013);
document.Close();

With the help of Spire.Doc, we can easily add new paragraphs to the existing word document. Sometimes, there are many empty lines or blank paragraphs on the wording document when we copy the contents from the internet. We can use Spire.Doc to remove the empty lines at one time easily. This article will show you how to remove the empty lines from the word documents in C#.

Firstly, view the sample document with empty lines:

How to remove empty lines from the word document in C#

Step 1: Create a new word document and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Traverse every section on the word document and remove the null and empty paragraphs.

foreach (Section section in doc.Sections)
{
    for (int i = 0; i < section.Body.ChildObjects.Count; i++)
    {
        if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph)
        {
            if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim()))
            {
                section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);
                i--;
            }
        }

    }
}

Step 3: Save the document to file.

string result = "result.docx";
doc.SaveToFile(result, FileFormat.Docx2013);

Effective screenshot after removing the empty lines from the word document:

How to remove empty lines from the word document in C#

Full codes:

{
    Document doc = new Document();
    doc.LoadFromFile("Sample.docx");
    
    foreach (Section section in doc.Sections)
    {
        for (int i = 0; i < section.Body.ChildObjects.Count; i++)
        {
            if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph)
            {
                if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim()))
                {
                    section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);
                    i--;
                }
            }

        }
    }
    
    string result = "result.docx";
    doc.SaveToFile(result, FileFormat.Docx2013);
  }

RTF is a document language used for encoding formatted text and graphics for easy transfer between applications. This article presents how to insert a piece of RTF encoded string to Word document using Spire.Doc.

Step 1: Initialize an instance of Document class, add a section to it.

Document doc = new Document();
Section section = doc.

Step 2: Add a paragraph to the section.

Paragraph para = section.AddParagraph();

Step 3: Declare a String variable to store the RTF string.

String rtfString = @"{\rtf1\ansi\deff0 {\fonttbl {\f0 hakuyoxingshu7000;}}\f0\fs28 Hello, World}";

Step 4: Append RTF string to paragraph.

para.AppendRTF(rtfString);

Step 5: Save the file.

doc.SaveToFile("Output.docx");

Output:

How to Insert RTF String to Word Documents in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();

String rtfString = @"{\rtf1\ansi\deff0 {\fonttbl {\f0 hakuyoxingshu7000;}}\f0\fs28 Hello, World}";
para.AppendRTF(rtfString);

doc.SaveToFile("Output.docx");
[VB.NET]
Dim doc As New Document()
Dim section As Section = doc.AddSection()
Dim para As Paragraph = section.AddParagraph()

Dim rtfString As[String] = "{\rtf1\ansi\deff0 {\fonttbl {\f0 hakuyoxingshu7000;}}\f0\fs28 Hello, World}"
para.AppendRTF(rtfString)

doc.SaveToFile("Output.docx")

When we want to manage the pagination for the paragraphs, we can insert a page break directly. But later we may find that it is hard to add or remove text above the page break and then we have to remove the whole page break. With Microsoft word, we can also use the Paragraph dialog to manage the pagination flexible for the word paragraph as below:

How to manage pagination on word document in C#

We have already shown you how to insert page break to the word document, this article we will show you how to manage the pagination by using the Paragraph.Format offered by Spire.Doc. Here comes to the steps of how to manage the pagination for the word document paragraph in C#:

Step 1: Create a new word document and load the document from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first section and the paragraph we want to manage the pagination

Section sec = doc.Sections[0];
Paragraph para = sec.Paragraphs[4];

Step 3: Set the pagination format as Format.PageBreakBefore for the checked paragraph.

para.Format.PageBreakBefore = true; 

Step 4: Save the document to file.

doc.SaveToFile("result.docx",FileFormat.Docx2010);

Effective screenshot after managing the pagination for the word document:

How to manage pagination on word document in C#

Full codes:

static void Main(string[] args)
 {
     Document doc = new Document();
     doc.LoadFromFile("sample.docx");

     Section sec = doc.Sections[0];
     Paragraph para = sec.Paragraphs[4];
     para.Format.PageBreakBefore = true;           
      
     doc.SaveToFile("result.docx",FileFormat.Docx2010);

 }
Wednesday, 08 June 2016 05:46

How to hide word paragraph in C#

Written by support iceblue

When we operate the word document, we can hide some texts or the whole paragraph on the Microsoft Word after click the font box to hide the selected texts. Please check the screenshot of how Microsoft hide the text as below:

How to hide word paragraph in C#

Spire.Doc offers a CharacterFormat.Hidden property to enable developers to hide the specified text or the whole paragraph. This article will demonstrate how to hide the whole paragraph on the word document in C#.

Here comes to the code snippets:

Step 1: Create a new word document and load from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first section and the first paragraph from the word document.

Section sec = doc.Sections[0];
Paragraph para = sec.Paragraphs[0];

Step 3: Get the first TextRange and set CharacterFormat.Hidden property as true to hide the texts.

(para.ChildObjects[0] as TextRange).CharacterFormat.Hidden = true;

Step 4: Save the document to file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Effective screenshot after the paragraph is hidden:

How to hide word paragraph in C#

After we set the options to display the hidden text, the hidden text will show like this:

How to hide word paragraph in C#

Full codes:

static void Main(string[] args)
 {
     Document doc = new Document();
     doc.LoadFromFile("sample.docx");
     Section sec = doc.Sections[0];
     Paragraph para = sec.Paragraphs[0];
       
      (para.ChildObjects[0] as TextRange).CharacterFormat.Hidden = true;
                  
     doc.SaveToFile("result.docx", FileFormat.Docx);

 }

With the help of Spire.Doc, developers can easily merge multiple word documents into one word documents. After merged the documents, you may need to insert a note or new paragraph to add some description on it. This article explains and describes how to insert a new paragraph to the existing word document in C# by using Spire.Doc.

The following example shows how to insert a paragraph into the document.

Step 1: Create a new document and load from file.

Document document = new Document();
document.LoadFromFile("sample.docx", FileFormat.Docx);

Step 2: Append the text and set the formatting for the font.

Paragraph paraInserted = new Paragraph(document);
TextRange textRange1 = paraInserted.AppendText("This is a inserted paragraph, I want to insert this paragraph in the start of document.");
textRange1.CharacterFormat.TextColor = Color.Blue;
textRange1.CharacterFormat.FontSize = 15;
textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;

Step 3: Insert the new paragraph.

document.Sections[0].Paragraphs.Insert(0, paraInserted);

Step 4: Save the document to file.

document.SaveToFile("result.docx", FileFormat.Docx);

Effective screenshot:

How to insert a new paragraph to word document in C#

Full codes:

static void Main(string[] args)
{
    Document document = new Document();
    document.LoadFromFile("sample.docx", FileFormat.Docx);

    Paragraph paraInserted = document.Sections[0].AddParagraph();
    TextRange textRange1 = paraInserted.AppendText("This is a inserted paragraph, I want to insert this paragraph in the start of document.");
    textRange1.CharacterFormat.TextColor = Color.Blue;
    textRange1.CharacterFormat.FontSize = 15;
    textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;
  
    document.Sections[0].Paragraphs.Insert(0, document.Sections[0].Paragraphs[document.Sections[0].Paragraphs.Count - 1]);

    document.SaveToFile("result.docx", FileFormat.Docx);
}

We can set Asian typography for paragraph for .doc files, there are four text alignments: Top, Center, Baseline, Bottom and Auto. In this article let's see how to set alignment when append HTML string code to .doc in C#.

Download Spire.Doc 5.3.83 or upper version, then add reference to your project.

Here are the steps:

Step 1: Create a HTML file contain the following code.

<html>
<body>
<i>f</i>(<i>x</i>)=<img align="middle" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACcAAAAlCAYAAADBa/A+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADvSURBVFhH7ZNbCsUwCES7/03nIkSwRh1rL00+PCCJVaeTPq5xMG2uSpuLuC7fwlZzZOxYc0TZnDwZ76WYzjVRjQnn57oQmdC5x9ses6IHUO7xd3NW8xNzVPPCwrtOLBXdbAlHgpJMX9SzVGQz7fUw55Eo87ZnqVAzh8x5z8jrHpl6pBNPb6bNVWlzVW7m5N+zKyT9Wqu0OYn3fVl8am754IHBz5+cpGxOP3qda9CNLNAMVESmmG3mMjw1lzrwXF0iEap5gUj1zNUlI0Jk+4i05lxNWCR1ysIh0Ixb1SJQCNQJ1pERgRU30uaqHGxujB+eJddCfZBWMwAAAABJRU5ErkJggg==" />

Step 2: Create a new document and add new section.

Document doc2 = new Document();
doc2.AddSection();

Step 3: Create new paragraph p and set its property of TextAlignment as "Center".

p.AppendText("Alignment:Center      ");
p.AppendHTML(File.ReadAllText(@"test.html"));
p.Format.TextAlignment = TextAlignment.Center; 

Step 4: Set other options to make a contrast, Auto is Baseline by default.

Paragraph p1 = doc2.Sections[0].AddParagraph();
p1.AppendText("Alignment:Baseline   ");
p1.AppendHTML(File.ReadAllText(@"test.html"));
p1.Format.TextAlignment = TextAlignment.Baseline;

Paragraph p2 = doc2.Sections[0].AddParagraph();
p2.AppendText("Alignment:Bottom    ");
p2.AppendHTML(File.ReadAllText(@"test.html"));
p2.Format.TextAlignment = TextAlignment.Bottom;

Paragraph p3 = doc2.Sections[0].AddParagraph();
p3.AppendText("Alignment:Top          ");
p3.AppendHTML(File.ReadAllText(@"test.html"));
p3.Format.TextAlignment = TextAlignment.Top;

Paragraph p4 = doc2.Sections[0].AddParagraph();
p4.AppendText("Alignment:Auto        ");
p4.AppendHTML(File.ReadAllText(@"test.html"));
p4.Format.TextAlignment = TextAlignment.Auto;

Step 5: Save and review.

doc2.SaveToFile(@"test.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("test.doc");

The screen shot:

Set text alignment when append HTML string code to .doc in C#

Full Code Here:

Document doc2 = new Document();
doc2.AddSection();
Paragraph p = doc2.Sections[0].AddParagraph();
p.AppendText("Alignment:Center      ");
p.AppendHTML(File.ReadAllText(@"test.html"));
p.Format.TextAlignment = TextAlignment.Center;

Paragraph p1 = doc2.Sections[0].AddParagraph();
p1.AppendText("Alignment:Baseline   ");
p1.AppendHTML(File.ReadAllText(@"test.html"));
p1.Format.TextAlignment = TextAlignment.Baseline;

Paragraph p2 = doc2.Sections[0].AddParagraph();
p2.AppendText("Alignment:Bottom    ");
p2.AppendHTML(File.ReadAllText(@"test.html"));
p2.Format.TextAlignment = TextAlignment.Bottom;

Paragraph p3 = doc2.Sections[0].AddParagraph();
p3.AppendText("Alignment:Top          ");
p3.AppendHTML(File.ReadAllText(@"test.html"));
p3.Format.TextAlignment = TextAlignment.Top;

Paragraph p4 = doc2.Sections[0].AddParagraph();
p4.AppendText("Alignment:Auto        ");
p4.AppendHTML(File.ReadAllText(@"test.html"));
p4.Format.TextAlignment = TextAlignment.Auto;

doc2.SaveToFile(@"test.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("test.doc");
Page 1 of 2