How to Add Auto Filters in Excel Using C#

Want to make your Excel data easier to explore and analyze? Auto Filters are your go-to tool. With just a few clicks, you can sort, filter and focus on the rows that matter. In this guide, you’ll learn how to add filters in Excel with C# using Spire.XLS for .NET, making it easy to insert Auto Filters into your spreadsheets. As a bonus, we’ll also show you how to remove Auto Filters in Excel when you're done.

Let’s dive in and make your spreadsheets smarter!

What is Spire.XLS and Why Use It

Spire.XLS for .NET is a powerful Excel library that enables you to create, edit, and convert Excel files programmatically — no need for Microsoft Excel to be installed on your machine. It’s ideal for automating Excel tasks in C# and other .NET applications.

To get started, you can install the library via NuGet with the following command:

PM> Install-Package Spire.XLS

For smaller or lightweight Excel projects, the free version is available:

PM> Install-Package FreeSpire.XLS

If you prefer manual setup or need more installation options, you can also download Spire.XLS for .NET or Free Spire.XLS for .NET directly from the official website.

How to Add Auto Filters to a Cell Range in Excel

If you want to quickly filter data in an Excel sheet without writing formulas, Auto Filters will help to instantly display only the needed rows. In this section, you'll learn how to add Auto Filters to a specific cell range in Excel using C#. Whether you're working with a small table or a large dataset, this method helps streamline data analysis with just a few lines of code.

The steps to apply Auto Filters to a cell range with C#:

  • Create a Workbook instance and read an Excel file.
  • Get a certain worksheet.
  • Add an AutoFilter to a specified cell range using Worksheet.AutoFilters.Range property.
  • Save the modified Excel file.

Here’s a code example showing how to add an Auto Filter in the cell range “A1:C1”:

  • C#
using Spire.Xls;

namespace AddAutoFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook instance
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Create an AutoFilter in the sheet and specify the range to be filtered
            sheet.AutoFilters.Range = sheet.Range["A1:C1"];

            // Save the result file
            workbook.SaveToFile("ExcelAutoFilter.xlsx", ExcelVersion.Version2016);
        }
    }
}

Using C# to Add Excel Autofilters

How to Add Built-in Auto Filters in Excel - Date

Excel’s built-in Auto Filters make it easy to filter data by common criteria like dates, numbers, and text. In this part, we’ll show you how to add a date Auto Filter in Excel using C#. The example focuses on applying a filter to a date column so you can quickly display rows based on specific days, months, or years.

  • Create a Workbook instance and load a sample Excel spreadsheet.
  • Get a worksheet and apply filters to a cell range through Worksheet.AutoFilters.Range property.
  • Add a date filter to the cell range with Workbook.AutoFilters.AddDateFilter() method.
  • Apply the date filter using Workbook.AutoFilters.Filter() method.
  • Save the updated Excel file.
  • C#
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.Spreadsheet.AutoFilter;

namespace AddAutoFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook instance
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Create an auto filter in the sheet and specify the range to be filtered
            sheet.AutoFilters.Range = sheet.Range["A1:A12"];

            // Get the column to be filtered
            IAutoFilter filtercolumn = sheet.AutoFilters[0];

            // Add a date filter to filter data related to February 2022
            sheet.AutoFilters.AddDateFilter(filtercolumn, DateTimeGroupingType.Month, 2022, 2, 0, 0, 0, 0);

            // Apply the filter
            sheet.AutoFilters.Filter();

           // Save the result file
            workbook.SaveToFile("DateAutoFilter.xlsx", ExcelVersion.Version2016);
        }
    }
}

Insert a Date Auto Filter to an Excel File Using C#

Quickly Apply Custom AutoFilter in Excel in C#

While built-in filters like date filters offer quick presets, there are times when you need more control over what gets displayed. That’s where custom AutoFilters come in. In this section, we’ll show you how to add a custom AutoFilter in Excel using C#, allowing you to filter by specific values or conditions — such as greater than, contains, or equals — to fit more complex data scenarios.

Steps to apply custom Auto Filters in Excel:

  • Create a Workbook object and load an Excel file.
  • Retrieve a worksheet.
  • Add an Auto Filter to a cell range.
  • Add a custom filter to the cell range through Workbook.AutoFilters.CustomFilter() method.
  • Apply the filter using Workbook.AutoFilters.Filter() method.
  • Save the resulting file.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.AutoFilter;

namespace AddAutoFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook instance
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Create an auto filter in the sheet and specify the range to be filtered
            sheet.AutoFilters.Range = sheet.Range["G1:G12"];

            // Get the column to be filtered
            FilterColumn filtercolumn = (FilterColumn)sheet.AutoFilters[0];

            // Add a custom filter to filter data containing the string "Grocery"
            string strCrt = "Grocery";
            sheet.AutoFilters.CustomFilter(filtercolumn, FilterOperatorType.Equal, strCrt);

            // Apply the filter
            sheet.AutoFilters.Filter();

           // Save the result file
            workbook.SaveToFile("CustomAutoFilter.xlsx", ExcelVersion.Version2016);
        }
    }
}

How to Add Customized Auto Filters in Excel with C#

Bonus Tip: How to Remove AutoFilters in Excel

Once you're done filtering, removing AutoFilters in Excel is just as easy. You can clear filters from a worksheet using a single line of C# code. This helps reset the view and ensures your data is fully visible again.

Want the exact steps? Check out our full guide on how to remove AutoFilters in Excel, including detailed instructions and code samples.

Wrapping Up

Adding AutoFilters in Excel using C# doesn’t have to be complicated — whether you’re working with a standard cell range, dates, or applying custom filter criteria. With just a few lines of code, you can make your Excel spreadsheets far more interactive and easier to analyze.

FAQ: Excel AutoFilter Questions Answered

Q1: How do I quickly add filters in Excel using C#?

You can quickly add filters to a cell range in Excel by using the Worksheet.AutoFilters.Range property in C#. Just define the target range and apply the filter with a single line of code.

Q2: How do I insert a drop-down filter in Excel?

Excel AutoFilters are essentially drop-down filters. Once you apply an AutoFilter to a column, Excel automatically creates a drop-down menu that lets you sort or filter the data based on values, conditions, or custom criteria.

Q3: How do I add a drop-down slicer in Excel?

Slicers are a visual filtering tool mainly used with PivotTables. While AutoFilters apply to standard worksheets, slicers offer a more user-friendly UI for filtering PivotTable data. If you're working with regular data (not PivotTables), AutoFilters are the better choice.

Q4: Can I remove filters once they’re applied in Excel with C#?

Yes, you can easily remove filters using C#. Just call the Worksheet.AutoFilters.Clear() method to remove all active filters from your worksheet.

The height of headers and footers can be adjusted by using the HeaderDistance and the FooterDistance properties. The detail steps of how to adjust the height of headers and footers in a word document using Spire.Doc are shown below.

Detail steps:

Step 1: Instantiate a Document object and load the word document.

Document doc = new Document();
doc.LoadFromFile("Headers and Footers.docx");

Step 2: Get the first section.

Section section = doc.Sections[0];

Step 3: Adjust the height of headers and footers in the section.

section.PageSetup.HeaderDistance = 100;
section.PageSetup.FooterDistance = 100;

Step 4: Save the file.

doc.SaveToFile("Output.docx", FileFormat.Docx2013);

Screenshot:

Header:

Adjust the Height of Headers and Footers in a Word document in C#

Footer:

Adjust the Height of Headers and Footers in a Word document in C#

Full code:

//Instantiate a Document object
Document doc = new Document();
//Load the word document
doc.LoadFromFile("Headers and Footers.docx");

//Get the first section
Section section = doc.Sections[0];

//Adjust the height of headers in the section
section.PageSetup.HeaderDistance = 100;

//Adjust the height of footers in the section
section.PageSetup.FooterDistance = 100;

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

A table in Excel is a structured range of data that includes headers for each column. When you convert a range of cells into a table, Excel automatically applies formatting, adds filter arrows to each header cell, and provides enhanced features for manipulating and analyzing the data. In this article, we will explain how to create, resize, and remove tables in Excel in C# using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Create a Table in Excel in C#

Spire.XLS for .NET allows you to convert a specific range of data in an Excel worksheet to a table using the Worksheet.ListObjects.Create(tableName, cellRange) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[index] property.
  • Get the cell range you want to convert to a table using Worksheet.Range[] property.
  • Convert the cell range to a table using Worksheet.ListObjects.Create(tableName, cellRange) method.
  • Save the resulting workbook to a file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace CreateTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the cell range you want to convert to a table
            CellRange range = sheet.Range[1, 1, sheet.LastRow, sheet.LastColumn];

            //Convert the cell range to a table
            IListObject table = sheet.ListObjects.Create("SalesTransactions", range);

            //Format the table with a built-in table style
            table.BuiltInTableStyle = TableBuiltInStyles.TableStyleLight2;

            //Save the resulting workbook to a file
            workbook.SaveToFile("CreateTable.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Create, Resize or Remove Tables in Excel

Add a Total Row to a Table in Excel in C#

You can add a total row after the end of a table to display summary calculations, such as sums, averages, or other aggregations of the data in the table. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[index] property.
  • Get a specific table in the worksheet using Worksheet.ListObjects[index] property.
  • Display a total row at the end of the table by setting Table.DisplayTotalRow property to true.
  • Set total row label in a specific table column using IListObject.Columns[index].TotalsRowLabel property.
  • Set the calculation functions for specific table columns using IListObject.Columns[index].TotalsCalculation property.
  • Save the resulting workbook to a file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace AddTotalRowToTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("CreateTable.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the first table in the worksheet
            IListObject table = sheet.ListObjects[0];

            //Show total row
            table.DisplayTotalRow = true;
            // Set total row label
            table.Columns[0].TotalsRowLabel = "Total";
            //Set the function used for the total calculation
            table.Columns[3].TotalsCalculation = ExcelTotalsCalculation.Sum;
            table.Columns[4].TotalsCalculation = ExcelTotalsCalculation.Sum;

            //Save the resulting workbook to a file
            workbook.SaveToFile("AddTotalRow.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();            
        }
    }
}

C#: Create, Resize or Remove Tables in Excel

Resize a Table in Excel in C#

You can resize a table by updating the data range of it using IListObject.Location property. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[index] property.
  • Get a specific table in the worksheet using Worksheet.ListObjects[index] property.
  • Resize the table by updating the data range of it using IListObject.Location property.
  • Save the resulting workbook to a file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace ResizeTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("CreateTable.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the first table in the worksheet
            IListObject table = sheet.ListObjects[0];

            table.Location = sheet.Range["C1:E8"];

            //Save the resulting workbook to a file
            workbook.SaveToFile("ResizeTable.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Create, Resize or Remove Tables in Excel

Remove a Table from Excel in C#

If you no longer need a table, you can convert it back to a normal range of cells by using the IListObjects.RemoveAt(tableIndex) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[index] property.
  • Get the table collection of the worksheet using Worksheet.ListObjects property.
  • Remove a specific table from the table collection using IListObjects.RemoveAt(tableIndex) property.
  • Save the resulting workbook to a file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace RemoveTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("CreateTable.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the table collection of the worksheet
            IListObjects tables = sheet.ListObjects;
            //Remove a specific table by its index
            tables.RemoveAt(0);

            ////Or remove a specific table by its name
            //for (int i = tables.Count - 1; i >= 0; i--)
            //{
            //    // Check if the table name matches the specific value
            //    if (tables[i].Name == "SalesTransactions")
            //    {
            //        // Remove the table
            //        tables.RemoveAt(i);
            //    }
            //}

            //Save the resulting workbook to a file
            workbook.SaveToFile("RemoveTable.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
            System.Diagnostics.Process.Start("RemoveTable.xlsx");
        }
    }
}

C#: Create, Resize or Remove Tables in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

In Spire.Presentation, when we add a common animation effect that belongs to both entrance and exit types, it’s applied as entrance effect by default. This article is going to show you how to add exit animation effect to a shape in PowerPoint using Spire.Presentation.

Detail steps:

Step 1: Create a Presentation instance and get the first slide.

Presentation ppt = new Presentation();
ISlide slide = ppt.Slides[0];

Step 2: Add a shape to the slide.

IShape starShape = slide.Shapes.AppendShape(ShapeType.FivePointedStar, new RectangleF(100, 100, 200, 200));

Step 3: Add random bars effect to the shape.

AnimationEffect effect = slide.Timeline.MainSequence.AddEffect(starShape, AnimationEffectType.RandomBars);

Step 4: Change the type of the effect from entrance to exit.

effect.PresetClassType = TimeNodePresetClassType.Exit;

Step 5: Save the file.

ppt.SaveToFile("ExitAnimationEffect.pptx", FileFormat.Pptx2013);

Screenshot:

Add Exit Animation Effect to a Shape in PowerPoint in C#

Full code:

using Spire.Presentation;
using Spire.Presentation.Drawing.Animation;
using System.Drawing;

namespace AddExitAnimationEffect
{

    class Program
    {

        static void Main(string[] args)
        {
            {
                //Create a Presentation instance
                Presentation ppt = new Presentation();

                //Get the first slide
                ISlide slide = ppt.Slides[0];

                //Add a shape to the slide
                IShape starShape = slide.Shapes.AppendShape(ShapeType.FivePointedStar, new RectangleF(100, 100, 200, 200));

                //Add random bars effect to the shape
                AnimationEffect effect = slide.Timeline.MainSequence.AddEffect(starShape, AnimationEffectType.RandomBars);

                //Change effect type from entrance to exit
                effect.PresetClassType = TimeNodePresetClassType.Exit;

                //Save the file
                ppt.SaveToFile("ExitAnimationEffect.pptx", FileFormat.Pptx2013);



            }
        }

    }
}

How to use Spire.Doc on .NET Core

2018-07-27 10:13:16 Written by Koohji

This program guide focus on helping you how to make Spire.Doc workable on Windows and Linux.

Starts from V 6.7.4, Spire.Doc supports .NET Core 2.0. Spire.Doc uses System.Drawing.Common, which depends on Libgdiplus library. So when you use Spire.Doc on .NET core, you need to install Libgdiplus library.

On Windows, we recommend you to get Spire.Doc package via Nuget. The Libgdiplus library will be installed automatically.

How to use Spire.Doc on .NET Core

On Linux, you need to install Libgdiplus library independently. Please follow the below three steps to install it successfully.

Step1: Open xxxx.csproj file and write the code snippet into it.

<ItemGroup>
<PackageReference Include=”Spire.Doc” Version=”6.7.13”/>
</ItemGroup>

How to use Spire.Doc on .NET Core

Step 2. Execute "dotnet build" command on terminal window of Visual Studio Code. It will install Spire.Doc package.

How to use Spire.Doc on .NET Core

Step 3. Open terminal window on Linux and execute Libgdiplus library installation command, for example, the command on Linux Ubuntu is "sudo apt-get install libgdiplus".

How to use Spire.Doc on .NET Core

Then you can use Spire.Doc on .NET core.

If you have any question, please feel free to contact us.

Replace Text with a Word document in C#

2018-07-24 07:10:57 Written by Koohji

Spire.Doc provides several overloaded Replace methods to replace text in different scenarios. This article is going to show you how to replace a specified text in a template document with another document using Spire.Doc.

The template document:

Replace Text with a Word document in C#

The document to replace text:

Replace Text with a Word document in C#

Detail steps:

Step 1: Load a template document.

Document document = new Document("Template.docx");

Step 2: Load another document to replace text.

IDocument replaceDocument = new Document("Document1.docx");

Step 3: Replace specified text with the other document.

document.Replace("Document 1", replaceDocument, false, true);  

Step 4: Save the file.

document.SaveToFile("Output.docx", FileFormat.Docx2013);

Output:

Replace Text with a Word document in C#

Full code:

using Spire.Doc;
using Spire.Doc.Interface;

namespace Replace_Text_With_Document
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a template document 
            Document document = new Document("Template.docx");

            //Load another document to replace text
            IDocument replaceDocument = new Document("Document1.docx");

            //Replace specified text with the other document
            document.Replace("Document 1", replaceDocument, false, true);

            //Save the file
            document.SaveToFile("Output.docx", FileFormat.Docx2013);
        }
    }
}

This article elaborates the steps to apply soft edges effect to an excel chart using Spire.XLS.

The example Excel file we used for demonstration:

Apply Soft Edges effect to Excel Chart in C#

Detail steps:

Step 1: Instantiate a Workbook object and load the excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Get the chart.

IChart chart = sheet.Charts[0];

Step 4: Specify the size of the soft edge. Value can be set from 0 to 100.

chart.ChartArea.Shadow.SoftEdge = 10;

Step 5: Save the file.

workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);

Output:

Apply Soft Edges effect to Excel Chart in C#

Full code:

using Spire.Xls;
using Spire.Xls.Core;

namespace Soft_Edges_in_Excel_Chart
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate a Workbook object
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("Input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the chart
            IChart chart = sheet.Charts[0];

            //Specify the size of the soft edge. Value can be set from 0 to 100
            chart.ChartArea.Shadow.SoftEdge = 10;

            //Save the file
            workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);
        }
    }
}

Hyperlinks in a PowerPoint file not only can be linked to external URLs, but also to the specific slide within the document. This article will show you how to create a hyperlink that links to a specified slide using Spire.Presentation.

Step 1: Create a PowerPoint file and append a slide to it.

Presentation presentation = new Presentation();
presentation.Slides.Append();

Step 2: Add a shape to the second slide.

IAutoShape shape = presentation.Slides[1].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(10, 50, 200, 50));
shape.TextFrame.Text = "Jump to the first slide"; 

Step 3: Create a hyperlink based on the shape and the text on it, linking to the first slide .

ClickHyperlink hyperlink = new ClickHyperlink(presentation.Slides[0]);
shape.Click = hyperlink;
shape.TextFrame.TextRange.ClickAction = hyperlink;

Step 4: Save the file.

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

Output:

How to Link to a Specific Slide in PowerPoint in C#, VB.NET

Full Code:

[C#]
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
namespace Link_to_a_Specific_Slide
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            presentation.Slides.Append();
            IAutoShape shape = presentation.Slides[1].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(10, 50, 200, 50));
            shape.Fill.FillType = FillFormatType.None;
            shape.Line.FillType = FillFormatType.None;
            shape.TextFrame.Text = "Jump to the first slide";
            ClickHyperlink hyperlink = new ClickHyperlink(presentation.Slides[0]);
            shape.Click = hyperlink;
            shape.TextFrame.TextRange.ClickAction = hyperlink;
            presentation.SaveToFile("output.pptx", FileFormat.Pptx2010);


        }
    }
}
[VB.NET]
Imports Spire.Presentation
Imports Spire.Presentation.Drawing
Imports System.Drawing
Namespace Link_to_a_Specific_Slide

	Class Program

		Private Shared Sub Main(args As String())
			Dim presentation As New Presentation()
			presentation.Slides.Append()
			Dim shape As IAutoShape = presentation.Slides(1).Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(10, 50, 200, 50))
			shape.Fill.FillType = FillFormatType.None
			shape.Line.FillType = FillFormatType.None
			shape.TextFrame.Text = "Jump to the first slide"
			Dim hyperlink As New ClickHyperlink(presentation.Slides(0))
			shape.Click = hyperlink
			shape.TextFrame.TextRange.ClickAction = hyperlink
			presentation.SaveToFile("output.pptx", FileFormat.Pptx2010)


		End Sub
	End Class
End Namespace

A tiled background usually refers to the background that is filled with one or more repetitions of a small image. In this article, you will learn how to tile an image in PDF and make a tile background for your PDFs in C# and VB.NET.

Step 1: Create a PdfDocument object and load a sample PDF document.

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

Step 2: Load an image file to PdfImage object.

PdfImage image = PdfImage.FromFile("logo.png");

Step 3: Create a PdfTilingBrush object specifying its size, set the transparency of the brush, and draw an image at the specified position of the brush.

PdfTilingBrush brush = new PdfTilingBrush(new SizeF(pdf.Pages[1].Canvas.Size.Width / 3, pdf.Pages[1].Canvas.Size.Height / 5));
brush.Graphics.SetTransparency(0.2f);
brush.Graphics.DrawImage(image,new PointF((brush.Size.Width-image.Width)/2,(brush.Size.Height-image.Height)/2));

Step 4: Draw rectangles on the PDF page using the brush.

pdf.Pages[1].Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.Size));

Step 5: Save the file.

pdf.SaveToFile("output.pdf");

Output:

How to Add a Tiled Background Image to PDF in C#, VB.NET

Full Code:

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


namespace Image
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("sample.pdf");

            PdfImage image = PdfImage.FromFile("logo.png");
            foreach (PdfPageBase page in pdf.Pages)
            {
                PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.Size.Width / 3, page.Canvas.Size.Height / 5));
                brush.Graphics.SetTransparency(0.2f);
                brush.Graphics.DrawImage(image, new PointF((brush.Size.Width - image.Width) / 2, (brush.Size.Height - image.Height) / 2));
                page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.Size));
            }
            pdf.SaveToFile("output.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing


Namespace Image
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument()
			pdf.LoadFromFile("sample.pdf")

			Dim image As PdfImage = PdfImage.FromFile("logo.png")
			For Each page As PdfPageBase In pdf.Pages
				Dim brush As New PdfTilingBrush(New SizeF(page.Canvas.Size.Width / 3, page.Canvas.Size.Height / 5))
				brush.Graphics.SetTransparency(0.2F)
				brush.Graphics.DrawImage(image, New PointF((brush.Size.Width - image.Width) / 2, (brush.Size.Height - image.Height) / 2))
				page.Canvas.DrawRectangle(brush, New RectangleF(New PointF(0, 0), page.Canvas.Size))
			Next
			pdf.SaveToFile("output.pdf")
		End Sub
	End Class
End Namespace

When processing a Word document, you may need to remove some paragraphs. For example, after you copied contents from the Internet with a lot of redundant paragraphs to your document, you need to delete the extra paragraphs and keep only those that are useful. The deletion can be easily achieved by Spire.Doc for .NET by programming with no need for other software. This article will show you the detailed steps of removing paragraphs in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Delete a Specific Paragraph in a Word Document

Spire.Doc for .NET provides a method RemoveAt() under ParagraphCollection to remove paragraphs.

The detailed steps of removing a specific paragraph are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section using Document.Section[] property.
  • Remove the 4th paragraph using Section.Paragraphs.RemoveAt() method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Doc;

namespace RemoveParagraphs
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of Document class
            Document document = new Document();

            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Get the first section
            Section section = document.Sections[0];

            //Remove the first paragraph in the section
            section.Paragraphs.RemoveAt(3);
            
            //Save the document
            document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Remove Paragraphs in a Word Document

Delete All Paragraphs in a Word Document

To remove all paragraphs, you can use the method Clear() under ParagraphCollection provided by Spire.Doc for .NET.

The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word Document using Document.LoadFromFile() method.
  • Loop through all sections, and remove all paragraphs in each section using Section.Paragraphs.Clear() method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Doc;

namespace RemoveAllParagraphs
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of Document class
            Document document = new Document();

            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Loop through all sections
            foreach (Section section in document.Sections)
            {
                //Remove all paragraphs in the section
                section.Paragraphs.Clear();
            }

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

C#/VB.NET: Remove Paragraphs in a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 15