Spire.Doc
Wednesday, 24 September 2014 06:15

Replace Images in Word with Texts in C#

Written by support iceblue

This topic is from Stackoverflow (original post), let us see how Spire.Doc can help developers to resolve their problems related to programming with Office technology. According to the description, the poster wants to replace each image in the Word file with “Here was image {image index}” correspondingly. However, we would like to provide a solution with below sample code.

Test File:

Replace Images in Word with Texts in C#

Code Snippet for Replace Images with Texts

Step 1: Create a new Word document and load the test file.

Document document = new Document(@"..\..\test.docx");

Step 2: Get all pictures in the Word document and replace them with the text "Here was image {image index}".

int j = 1;
foreach (Section sec in document.Sections)
{
    foreach (Paragraph para in sec.Paragraphs)
    {
        List pictures = new List(); 
        foreach (DocumentObject docObj in para.ChildObjects)
        {
            if (docObj.DocumentObjectType == DocumentObjectType.Picture)
            {
                pictures.Add(docObj);
            }
        }
        foreach (DocumentObject pic in pictures)
        {
            int index = para.ChildObjects.IndexOf(pic);
            TextRange range = new TextRange(document);
            range.Text = string.Format("Here was image {0}", j);
            para.ChildObjects.Insert(index, range);
            para.ChildObjects.Remove(pic);
            j++;
        }
    }
}

Step 3: Save and launch the file.

          document.SaveToFile(@"..\..\result.docx", FileFormat.Docx);
          System.Diagnostics.Process.Start(@"..\..\result.docx");

Result:

Replace Images in Word with Texts in C#

Full C# Code:

[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;
using System.Drawing;

namespace ReplaceImageWithText
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document(@"..\..\test.docx");
            int j = 1;
            foreach (Section sec in document.Sections)
            {
                foreach (Paragraph para in sec.Paragraphs)
                {
                    List pictures = new List(); 
                    foreach (DocumentObject docObj in para.ChildObjects)
                    {
                        if (docObj.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            pictures.Add(docObj);
                        }
                    }
                    foreach (DocumentObject pic in pictures)
                    {
                        int index = para.ChildObjects.IndexOf(pic);
                        TextRange range = new TextRange(document);
                        range.Text = string.Format("Here was image {0}", j);
                        para.ChildObjects.Insert(index, range);
                        para.ChildObjects.Remove(pic);
                        j++;
                    }
                }
            }
            document.SaveToFile(@"..\..\result.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start(@"..\..\result.docx");
        }
    }
}
Tuesday, 02 September 2014 09:06

Insert page break at a specified location

Written by support iceblue

Spire.Doc supports to insert page breaks in C# and VB.NET. We have already had a tutorial article of how to insert a page break after a paragraph. This article we will demonstrate how to add a page break at a specified location by searching a single word.

First, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer. Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Here comes to the steps of how to insert a page break at a specified location.

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

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

Step 2: Find the specified word "experience" where we want to insert the page break.

TextSelection[] selections = doc.FindAllString("experience", true, true);

Step 3: Traverse each word "experience".

foreach (TextSelection ts in selections)
   {
     TextRange range = ts.GetAsOneRange();
     Paragraph paragraph = range.OwnerParagraph;
     int index = paragraph.ChildObjects.IndexOf(range);
     Break pageBreak = new Break(doc, BreakType.PageBreak);
   }

Step 4: Create a new instance of page break and insert a page break after the word "experience".

Break pageBreak = new Break(doc, BreakType.PageBreak);
paragraph.ChildObjects.Insert(index + 1, pageBreak);

Step 5: Save the word document to file and process it.

doc.SaveToFile("Break.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Break.docx");

Effective screenshot of the inserted page break after the word "experience":

Insert page break at a specified location

Full codes:

{
class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Test.docx");
            TextSelection[] selections = doc.FindAllString("experience", true, true);
            foreach (TextSelection ts in selections)
            {
                TextRange range = ts.GetAsOneRange();
                Paragraph paragraph = range.OwnerParagraph;
                int index = paragraph.ChildObjects.IndexOf(range);
                Break pageBreak = new Break(doc, BreakType.PageBreak);
                paragraph.ChildObjects.Insert(index + 1, pageBreak);
            }
            doc.SaveToFile("Break.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Break.docx");

        }
    }
}
Thursday, 28 August 2014 06:12

Prevent Page Breaks in Word Tables in C#

Written by support iceblue

All too often, we start a table near the bottom of a page. Microsoft Word automatically places a page break in a table if a single row or several rows are too long to fit between the top and bottom margins of the page. So we'd rather the same row can be placed on one page or have the entire table on the next page instead of being broken over two pages. In this article, I'll introduce you two ways to avoid page breaks in Word tables via Spire.Doc.

Assume that we have a Word table like this (Row 2 splits to different pages), we may want to optimize the layout by the following two methods.

Prevent Page Breaks in Word Tables

Method 1: Keep the entire table on the same page.

Step 1: Create a new Word document and load the test file.

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

Step 2: Get the table from Word document.

Table table = doc.Sections[0].Tables[0] as Table;

Step 3: Change the paragraph setting to keep them together.

           foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                  foreach (Paragraph p in cell.Paragraphs)
                   {
                       p.Format.KeepFollow = true;
                   }
                }
           }

Step 4: Save and launch the file.

      doc.SaveToFile("Result.docx", FileFormat.Docx2010);
      System.Diagnostics.Process.Start("Result.docx");

Output:

Prevent Page Breaks in Word Tables

Method 2: Prevent Word from breaking a table row across two pages.

There still exists a situation that the table is not small enough to fit on one page, you can prevent Word from breaking a table row that contains multiple paragraphs across two pages. In this example, the second row has been splitted in different pages, we can set property of TableFormat with following sentence to avoid this problem.

table.TableFormat.IsBreakAcrossPages = false;

Use this sentence to replace Step 3, you'll get the layout as below:

Prevent Page Breaks in Word Tables

Full C# Code:

Method 1

            Document doc = new Document("Test.docx");
            Table table = doc.Sections[0].Tables[0] as Table;
            foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                  foreach (Paragraph p in cell.Paragraphs)
                   {
                       p.Format.KeepFollow = true;
                   }
                }
            }  
            doc.SaveToFile("Result.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("Result.docx");

Method 2

             Document doc = new Document("Test.docx");
             Table table = doc.Sections[0].Tables[0] as Table;
             table.TableFormat.IsBreakAcrossPages = false;
             doc.SaveToFile("Result.docx", FileFormat.Docx2010);
             System.Diagnostics.Process.Start("Result.docx");
Page 1 of 25