Spire.Doc for .NET enables developers to add, modify and remove text and Image header for word documents easily. We have already shown you how to insert header for all the pages and only add header for the first page in word document in C#. This article will focus on demonstrate how to remove the header for all the pages in word document and only remove the header for the first page in C#.

In the example, we will load a word document with headers. And then we will show you how to remove the header only from the first page and all the pages independently.

Check the word document with headers:

How to remove header from the word document in C#

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

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

Step 2: Get the first section of document.

Section section = doc.Sections[0];

Step 3: Remove the header only from the first page of word document.

//This is necessary
section.PageSetup.DifferentFirstPageHeaderFooter = true;
section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();

Step 4: Remove the header for all the pages.

section.HeadersFooters.Header.ChildObjects.Clear();

Step 5: Save the document to file.

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

Effective screenshot of the removal of the header:

How to remove header from the word document in C#

Full codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace RemoveHeader
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Blues.docx");
            Section section = doc.Sections[0];
            //This is necessary
            section.PageSetup.DifferentFirstPageHeaderFooter = true;
            section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();
            //section.HeadersFooters.Header.ChildObjects.Clear();
            doc.SaveToFile("output.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("output.docx");
        }
    }
}

When we print Word and PDF documents which have regular page size, we can clearly know the pagination information for Word and PDF by delimiters. Excel document is different since Excel pagination is based on its content when we print Excel document or convert to Pdf. So get Excel pagination information is important to developer. Below would introduce a solution to get pagination information in Excel document.

The solution call book.GetSplitPageInfo() method to obtain information of excel document and return this information to the List<Dictionary<int, PageColRow>> object via Spire.XLS. By the object we can get this information about: sheet count, page count and the start and end column and row of every page in excel document. Below is effect screenshots:

Get information of pagination in Excel document

The main steps of the solution are:

Step 1: Create and load an excel document.

Workbook book = new Workbook();
book.LoadFromFile(@"test.xlsx");

Step 2: Call GetSplitPageInfo() method to Excel information.

List> pageInfoList = book.GetSplitPageInfo();

Get information of pagination in Excel document

The full code:

[C#]
using System.Collections.Generic;
using Spire.Xls;
using Spire.Xls.Core.Converter.Exporting.EMF;
namespace GetPageInformation
{
    class Program
    {
        static void Main(string[] args)
        {
            // create and load Excel document
Workbook book = new Workbook();
            book.LoadFromFile(@"test.xlsx");
           // get the Excel document information and save in pageInfoList object
            List> pageInfoList = book.GetSplitPageInfo();

            // the sheet count of excel 
            int sheetCount = pageInfoList.Count;

            //The page count of the first sheet
            int pageCount = pageInfoList[0].Count;
            book.SaveToFile("result.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports System.Collections.Generic
Imports Spire.Xls
Imports Spire.Xls.Core.Converter.Exporting.EMF
Module Module1

Sub Main()
'create and load Excel document
        Dim book As New Workbook()
        book.LoadFromFile("test.xlsx")
' get the Excel document information and save in pageInfoList object
        Dim pageInfoList As List(Of Dictionary(Of Integer, PageColRow)) = book.GetSplitPageInfo()

        ' the sheet count of excel 
        Dim sheetCount As Integer = pageInfoList.Count

        'The page count of the first sheet
        Dim pageCount As Integer = pageInfoList(0).Count
        book.SaveToFile("result.pdf", FileFormat.PDF)
    End Sub

End Module

Why we convert PDF to image?

  • PDF requires an external application like Adobe Acrobat Reader while image does not.
  • Browsers have the built-in capability to display images while handling PDF documents requires an external application or plug-in.

So, in some specific cases converting your PDF documents to an image format like PNG or JPEG could be the solution we are looking for.

How to convert PDF to image in WPF?

For developers, we can easily render PDF pages to images with high quality by using Spire.PDF for WPF, which is a professional PDF component providing tons of useful methods to manipulate PDF document in your WPF applications. Now, follow the below steps to achieve this purpose.

Detailed steps:

Step 1: Create a new project by choosing WPF Application in Visual Studio, add a button in MainWindow, double click the button to write code.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
}

Step 2: Create a new instance of Spire.Pdf.Document and load the sample PDF file.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("sample.pdf");

Step 3: To convert PDF to image, we need firstly save PDF pages as BitmapSource by calling the method pdf.SaveAsImage, then convert BitmapSource to Bitmap, then save the Bitmap as image with a specified format using Image.Save().

               BitmapSource source;
            Bitmap bmp;

            for(int i=0;i<pdf.Pages.Count;i++)
            {
                source = pdf.SaveAsImage(i);
                bmp = SourceToBitmap(source);
                bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png);
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {
            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }

Output of the first page:

Convert PDF to Image with High Quality in WPF

Full code:

[C#]
using Spire.Pdf;

namespace ConvertPdfToImage
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("1.pdf");

            BitmapSource source;
            Bitmap bmp;

            for(int i=0;i<pdf.Pages.Count;i++)
            {
                source = pdf.SaveAsImage(i);
                bmp = SourceToBitmap(source);
                bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png);
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {
            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }

    }
}

A table provides a visual grouping of information and gives more convenience for writer to modify and query data in table. In particular when you have a table with colorful cells, your document would be more attractive. With the help of Spire.Presentation, developers can easily add tables and set table styles in PowerPoint document. This tutorial shows you how to fill the table cells with color in C#.

Step 1: Create a presentation document and load the file from disk.

Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.pptx");

Step 2: Fill the table cell with color. You can fill all the cells or only fill one single row of cell in table with color.

foreach (TableRow row in table.TableRows)
  {
     foreach (Cell cell in row)
    {
      cell.FillFormat.FillType = FillFormatType.Solid;
      cell.FillFormat.SolidColor.Color = Color.Green;
     }
  }

Step 3: Save the presentation documents to file.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);

Effective screenshot for fill the color in all the table cells:

How to fill the table cell with color in PowerPoint document in C#

Effective screenshot for fill the color for the first row of table cell:

How to fill the table cell with color in PowerPoint document in C#

Full codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace colorfilltablecell
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("sample.pptx");
            ITable table = null;
            foreach (IShape shape in presentation.Slides[0].Shapes)
            {
                if (shape is ITable)
                {
                    table = (ITable)shape;

                    foreach (TableRow row in table.TableRows)

                    {
                        //TableRow row = table.TableRows[0];
                        foreach (Cell cell in row)
                        {
                            cell.FillFormat.FillType = FillFormatType.Solid;
                            cell.FillFormat.SolidColor.Color = Color.Green;
                        }
                    }
                }
            }
            presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
        }
    }
}

When you type in a document, Word automatically counts the number of pages and words in your document and displays them on the status bar – Word Count, at the bottom of the workspace. But how can we get the number of words, characters in an existing Word document through programming? This article aims to give you a simple solution offered by Spire.Doc.

Test file:

Count the number of words in a document in C#, VB.NET

Detailed Steps for Getting the Number of Words and Characters

Step 1: Create a new instance of Spire.Doc.Document class and load the test file.

Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx2010);

Step 2: Display the number of words, characters including or excluding spaces on console.

Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);

Output:

Count the number of words in a document in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using System;
namespace CountNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("test.docx", FileFormat.Docx2010);
            Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
            Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
            Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);
            Console.ReadKey();
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace CountNumber
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("test.docx", FileFormat.Docx2010)
			Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount)
			Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace)
			Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount)
			Console.ReadKey()
		End Sub
	End Class
End Namespace

Content controls provide a way for you to design documents. When you add a content control to a document, the control is identified by a border, a title, and temporary text that can provide instructions to the user. According to Microsoft, content controls mainly benefit from two features:

  • Prevent users from editing or deleting protected sections of a document.
  • Bind parts of a document or template to data. You can bind content controls to database fields, managed objects in the .NET Framework, XML elements that are stored in the document, and other data sources.

Therefore, it is necessary for developers to get the properties of content controls when dealing content controls at run time. This article illustrates how to get all controls and their properties including alias, id and tag via Spire.Doc.

Firstly, check the test file that contains six content controls distributed in lines and a table. By default, the border and the title of the control do not appear if we don't click the protected section.

Test File:

Get alias, tag and id of content controls in a Word document in C#

Main Steps:

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

Step 2: Create two lists to store tags which are distributed in lines and a table separately. Here, each content control will be identified by tag.

Step 3: Use foreach sentence to get all tags in the Word document.

Full Code:

       static void Main(string[] args)
        {
            using (Document document = new Document(@"..\..\TestData\test.docx"))
            {
                StructureTags structureTags = GetAllTags(document);
                List<StructureDocumentTagInline> tagInlines = structureTags.tagInlines;

                string alias = tagInlines[0].SDTProperties.Alias;
                decimal id = tagInlines[0].SDTProperties.Id;
                string tag = tagInlines[0].SDTProperties.Tag;

                List<StructureDocumentTag> tags = structureTags.tags;
                alias = tags[0].SDTProperties.Alias;
                id = tags[0].SDTProperties.Id;
                tag = tags[0].SDTProperties.Tag;

            }
        }
       static StructureTags GetAllTags(Document document)
        {
            StructureTags structureTags = new StructureTags();
            foreach (Section section in document.Sections)
            {
                foreach (DocumentObject obj in section.Body.ChildObjects)
                {
                    if (obj.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject pobj in (obj as Paragraph).ChildObjects)
                        {
                            if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                            {
                                structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
                            }
                        }
                    }
                    else if (obj.DocumentObjectType == DocumentObjectType.Table)
                    {
                        foreach (TableRow row in (obj as Table).Rows)
                        {
                            foreach (TableCell cell in row.Cells)
                            {
                                foreach (DocumentObject cellChild in cell.ChildObjects)
                                {
                                    if (cellChild.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
                                    {
                                        structureTags.tags.Add(cellChild as StructureDocumentTag);
                                    }
                                    else if (cellChild.DocumentObjectType == DocumentObjectType.Paragraph)
                                    {
                                        foreach (DocumentObject pobj in (cellChild as Paragraph).ChildObjects)
                                        {
                                            if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                                            {
                                                structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return structureTags;
        }
        public class StructureTags
        {
            List<StructureDocumentTagInline> m_tagInlines;
            public List tagInlines
            {
                get
                {
                    if (m_tagInlines == null)
                        m_tagInlines = new List();
                    return m_tagInlines;
                }
                set
                {
                    m_tagInlines = value;
                }
            }
            List<StructureDocumentTag> m_tags;
            public List tags
            {
                get
                {
                    if (m_tags == null)
                        m_tags = new List();
                    return m_tags;
                }
                set
                {
                    m_tags = value;
                }
            }
        }

Effect Screenshot:

Content controls in lines

Get alias, tag and id of content controls in a Word document in C#

Content controls in table

Get alias, tag and id of content controls in a Word document in C#

As a powerful PDF component, Spire.PDF supports to work with page setting for PDF well, such as set PDF properties, view preference, and set background color etc. This article will focus on show you how to add image as page background to an existing PDF file in C#.

Make sure Spire.PDF for .NET has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll".

Firstly, check the original PDF file without background image.

Add image as page background in PDF file

The following code snippet shows you how to add image as background for PDF in C#.

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

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("sample.pdf");

Step 2: Get the first page in PDF file

PdfPageBase page = doc.Pages[0];

Step 3: Load the image from file and set it as background image.

Image backgroundImage = Image.FromFile("background.png");
page.BackgroundImage = backgroundImage;

Step 4: Save the document to file and launch it.

doc.SaveToFile("result.pdf");
System.Diagnostics.Process.Start("result.pdf");

Effective Screenshot:

Add image as page background in PDF file

Full Codes:

using Spire.Pdf;
using System.Drawing;

namespace Addimagebackground
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("sample.pdf");
            PdfPageBase page = doc.Pages[0];
            Image backgroundImage = Image.FromFile("background.png");
            page.BackgroundImage = backgroundImage;
            doc.SaveToFile("result.pdf");
            System.Diagnostics.Process.Start("result.pdf");
        }
    }
}

Text annotation is frequently used in PDF for creating a comment or explaining more about an item. Using Spire.PDF you can create a text mark-up annotation, edit an existing annotation and delete specified or all annotations. This article is aimed to demonstrate how to modify and format an existing text annotation in a PDF document.

Test File:

Modify and Format Annotation in PDF in C#, VB.NET

Changes we want to make:

  • Modify the annotation text.
  • Change the color of the annotation icon.
  • Fix the annotation flag including its position, color, and type.

Code Snippet

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

PdfDocument pdf = new PdfDocument("test.pdf");

Step 2: Get the annotation from the document.

PdfAnnotation annotation = pdf.Pages[0].Annotations[0];

Step 3: Set the text, border, color of the annotation and lock the annotation flag.

annotation.Text = "Revised annotation";
annotation.Border = new PdfAnnotationBorder(0.75f);
annotation.Color = new PdfRGBColor(Color.White);
annotation.Flags = PdfAnnotationFlags.Locked;

Step 4: Save and launch the file.

pdf.SaveToFile("result.pdf");
Process.Start("result.pdf");

Target Effect:

Modify and Format Annotation in PDF in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Diagnostics;
using System.Drawing;

namespace ModifyAndFormatAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument("test.pdf");
            PdfAnnotation annotation = pdf.Pages[0].Annotations[0];

            annotation.Text = "Revised annotation";
            annotation.Border = new PdfAnnotationBorder(0.75f);
            annotation.Color = new PdfRGBColor(Color.White);
            annotation.Flags = PdfAnnotationFlags.Locked;

            pdf.SaveToFile("result.pdf");
            Process.Start("result.pdf");
        }

    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Annotations
Imports Spire.Pdf.Graphics
Imports System.Diagnostics
Imports System.Drawing

Namespace ModifyAndFormatAnnotation
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument("test.pdf")
			Dim annotation As PdfAnnotation = pdf.Pages(0).Annotations(0)

			annotation.Text = "Revised annotation"
			annotation.Border = New PdfAnnotationBorder(0.75F)
			annotation.Color = New PdfRGBColor(Color.White)
			annotation.Flags = PdfAnnotationFlags.Locked

			pdf.SaveToFile("result.pdf")
			Process.Start("result.pdf")
		End Sub

	End Class
End Namespace

When you need to print many PDF documents, surely you don't want to see the print dialog every time. This article will show you clearly how to print PDF documents in WPF without invoking Print Dialog by using Spire.PDFViewer for WPF.

Here comes to the steps of how to print PDF files in WPF.

Step 1: First you need to create a new project by choosing "WPF Application".

Step 2: Set the Target Framework to be .NET Framework 4 in Properties.

Step 3: Right-click on the blank part of the Toolbox → "Add Tab" → "Choose Items" → "WPF Components" → "Browse" to the "Bin" folder → find the file "Spire.PdfViewer.Wpf.dll" → "OK".

Step4: Spire.PDFViewer offers PdfViewer and PdfDocumentViewer to print the PDF files in C#. Please check the code snippet as below:

Print via PdfViewer without invoking PrintDialog with the following method.

PrintDialog dialog = new PrintDialog();
this.pdfViewer1.PrintDialog = dialog;
dialog.PrintDocument(pdfViewer1.PrintDocument.DocumentPaginator, "Print Document");

Print via PdfDocumentViewer without invoking PrintDialog with the following method.

PrintDialog dialog = new PrintDialog();
this.pdfDocumentViewer1.PrintDialog = dialog;
dialog.PrintDocument(pdfDocumentViewer1.PrintDocument.DocumentPaginator, "Print Document");

Then your PDF document will be printed directly without showing the print dialog.

Full codes of how to print PDF file in WPF.

namespace PrintPDFinWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.pdfViewer1.LoadFromFile("sample.pdf");
            ////Print the PDF file directly with PrintDialog
            //this.pdfViewer1.Print();

            //Print without Print Dialog
            PrintDialog dialog = new PrintDialog();
            this.pdfViewer1.PrintDialog = dialog;
            dialog.PrintDocument(pdfViewer1.PrintDocument.DocumentPaginator, "Print Document");
        }
    }
}

A file with the XLSM extension is an Excel Macro-Enabled Workbook file. For security reasons, XLS file or XLSX file does not enable macros by default. Thus, if you want to execute macros in Excel file, you need to convert XLS or XLSX to XLSM at the first place. In this article, I’ll introduce you how to convert XLS to XLSM with the macro maintained using Spire.XLS.

Here is the method:

Step 1: Create a new instance of Spire.Xls.Workbook class.

Workbook workbook = new Workbook();

Step 2: Load the test file and imports its data to workbook.

workbook.LoadFromFile("test.xls", ExcelVersion.Version97to2003);

Step 3: Save the workbook as a new XLSM file.

workbook.SaveToFile("result.xlsm", FileFormat.Version2007);

Full Code:

[C#]
using Spire.Xls;
namespace Convert
{
    class Program
    {
          static void Main(string[] args)
{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("test.xls", ExcelVersion.Version97to2003);
    workbook.SaveToFile("result.xlsm", FileFormat.Version2007);
}

        }
    }
[VB.NET]
Imports Spire.Xls
Namespace Convert
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("test.xls", ExcelVersion.Version97to2003)
			workbook.SaveToFile("result.xlsm", FileFormat.Version2007)
		End Sub

	End Class
End Namespace

Test File:

As is shown in the picture, Excel automatically disables macro in XLS file.

Convert XLS to XLSM and Maintain Macro in C#, VB.NET

Result:

No security warning in the converted XLSM file.

Convert XLS to XLSM and Maintain Macro in C#, VB.NET

page 53