PDF Table plays a significant role of clearly displaying data information in PDF document, which cannot be replaced by words. It provides great convenience for its users. For example, a product list can be more easily recognized and checked than numerous words. Thus, it is very necessary to learn how to generate table in PDF document.

In this article, I will not only introduce users how to generate table in PDF document, but also tell you how to set table style such as font, background color and data size by using Spire.PDF for WPF.

Spire.PDF for WPF enables you to quickly realize the task of drawing a PDF table by the below steps.

Step 1: Create a new project

  • Create a new project in WPF Application
  • Add a button in MainWindow, and set the button Content to be "Run"

Step 2: Add references and namespaces

  • Add System.Drawing and Spire.Pdf.Wpf.dll as references
  • Add below namespaces at the top of the method
[C#]
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Fonts;
using Spire.Pdf.Tables;
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Graphics.Fonts
Imports Spire.Pdf.Tables

Step 3: Draw table in PDF document and set the table style

Create a new PDF document and set its margin

[C#]
             //create a new PDF document
            PdfDocument doc = new PdfDocument();

            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            float y = 20;
[VB.NET]
           'create a new PDF document
	 Dim doc As New PdfDocument()

	 Dim unitCvtr As New PdfUnitConvertor()
	 Dim margin As New PdfMargins()
	  margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	  margin.Bottom = margin.Top
	  margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	  margin.Right = margin.Left

	  Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
	  Dim y As Single = 20

Set table title and then, add data information in PDF document

[C#]
           //add PDF title
            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Verdana", 14f, System.Drawing.FontStyle.Bold));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Part Sales Information", format1).Height;
            y = y + 10;

            //add data information
            String[] data
         = {
        "PartNo;Description;OnHand;OnOrder;Cost;ListPrice",
        "900;Dive kayak;24;16;1356.75;3999.95",
        "912;Underwater Diver Vehicle;5;3;504;1680",
        "1313;Regulator System;165;216;117.5;250",
        "1314;Second Stage Regulator;98;88;124.1;365",
        "1316;Regulator System;75;70;119.35;341",
        "1320;Second Stage Regulator;37;35;73.53;171",
        "1328;Regulator System;166;100;154.8;430",
        "1330;Alternate Inflation Regulator;47;43;85.8;260",
        "1364;Second Stage Regulator;128;135;99.9;270",
        "1390;First Stage Regulator;146;140;64.6;170",
        "1946;Second Stage Regulator;13;10;95.79;309",
        "1986;Depth/Pressure Gauge Console;25;24;73.32;188",
        "2314;Electronic Console;13;12;120.9;390",
        "2341;Depth/Pressure Gauge;226;225;48.3;105",
        "2343;Personal Dive Sonar;46;45;72.85;235",
        "2350;Compass Console Mount;211;300;10.15;29"
            }; 

            String[][] dataSource
                = new String[data.Length][];
            for (int i = 0; i < data.Length; i++)
            {
                dataSource[i] = data[i].Split(';');
            }
[VB.NET]
	'add PDF title
	Dim brush1 As PdfBrush = PdfBrushes.Black
	Dim font1 As New PdfTrueTypeFont(New Font("Verdana", 14F, System.Drawing.FontStyle.Bold))
	Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
	page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1)
	y = y + font1.MeasureString("Part Sales Information", format1).Height
	y = y + 10

	'add data information
	Dim data As [String]() = {"PartNo;Description;OnHand;OnOrder;Cost;ListPrice", 
"900;Dive kayak;24;16;1356.75;3999.95", 
"912;Underwater Diver Vehicle;5;3;504;1680",
       "1313;Regulator System;165;216;117.5;250", 
       "1314;Second Stage Regulator;98;88;124.1;365", 
       "1316;Regulator System;75;70;119.35;341",
       "1320;Second Stage Regulator;37;35;73.53;171",
       "1328;Regulator System;166;100;154.8;430", 
       "1330;Alternate Inflation Regulator;47;43;85.8;260",
       "1364;Second Stage Regulator;128;135;99.9;270",
       "1390;First Stage Regulator;146;140;64.6;170", 
       "1946;Second Stage Regulator;13;10;95.79;309",
       "1986;Depth/Pressure Gauge Console;25;24;73.32;188", 
       "2314;Electronic Console;13;12;120.9;390",
       "2341;Depth/Pressure Gauge;226;225;48.3;105", 
       "2343;Personal Dive Sonar;46;45;72.85;235", 
       "2350;Compass Console Mount;211;300;10.15;29"}

	Dim dataSource As [String]()() = New [String](data.Length - 1)() {}
	For i As Integer = 0 To data.Length - 1
		dataSource(i) = data(i).Split(";"C)
	Next

Set PDF table style and data format

[C#]
            //Set table header
            PdfTable table = new PdfTable();
            table.Style.CellPadding = 3;
            table.Style.HeaderSource = PdfHeaderSource.Rows;
            table.Style.HeaderRowCount = 1;
            table.DataSource = dataSource;
            table.Style.ShowHeader = true;

            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.LightSeaGreen;
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Verdana", 9f, System.Drawing.FontStyle.Bold));
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White;

            //Set table style and data format
            table.Style.BorderPen = new PdfPen(PdfBrushes.LightBlue, 0.5f);
            table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.LightYellow;
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Verdana", 8.5f));
            table.Style.AlternateStyle = new PdfCellStyle();
            table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.AliceBlue;
            table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Verdana", 8.5f));

            float width
                = page.Canvas.ClientSize.Width
                - (table.Columns.Count + 1) * table.Style.BorderPen.Width;
            table.Columns[0].Width = width * 0.1f * width;
            table.Columns[0].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
         
            table.Columns[1].Width = width * 0.28f * width;
            table.Columns[1].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[2].Width = width * 0.1f * width;
            table.Columns[2].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[3].Width = width * 0.1f * width;
            table.Columns[3].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[4].Width = width * 0.12f * width;
            table.Columns[4].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[5].Width = width * 0.12f * width;
            table.Columns[5].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            PdfLayoutResult result = table.Draw(page, new PointF(0, y));
[VB.NET]
	'Set table header
	Dim table As New PdfTable()
	table.Style.CellPadding = 3
	table.Style.HeaderSource = PdfHeaderSource.Rows
	table.Style.HeaderRowCount = 1
	table.DataSource = dataSource
	table.Style.ShowHeader = True

	table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.LightSeaGreen
	table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Verdana", 9F, System.Drawing.FontStyle.Bold))
	table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
	table.Style.HeaderStyle.TextBrush = PdfBrushes.White

	'Set table style and data format
	table.Style.BorderPen = New PdfPen(PdfBrushes.LightBlue, 0.5F)
	table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.LightYellow
	table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Verdana", 8.5F))
	table.Style.AlternateStyle = New PdfCellStyle()
	table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.AliceBlue
	table.Style.AlternateStyle.Font = New PdfTrueTypeFont(New Font("Verdana", 8.5F))

	Dim width As Single = page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width
	table.Columns(0).Width = width * 0.1F * width
	table.Columns(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)

	table.Columns(1).Width = width * 0.28F * width
	table.Columns(1).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(2).Width = width * 0.1F * width
	table.Columns(2).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(3).Width = width * 0.1F * width
	table.Columns(3).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(4).Width = width * 0.12F * width
	table.Columns(4).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(5).Width = width * 0.12F * width
	table.Columns(5).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)

	Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y))

Step 4: Save and Launch

[C#]
            // save and launch the file
            doc.SaveToFile("SimpleTable.pdf");
            doc.Close();
            System.Diagnostics.Process.Start("SimpleTable.pdf");
[VB.NET]
	' save and launch the file
	doc.SaveToFile("SimpleTable.pdf")
	doc.Close()
	System.Diagnostics.Process.Start("SimpleTable.pdf")

Effective Screeshot:

Generate PDF Table

Footnotes and endnotes are short notes that can be used to provide explanations, comments or references to certain words or sentences in a document. Footnotes usually appear at the bottom of the page containing their reference numbers, while endnotes appear at the end of the document or section. If you are writing an academic paper in Word, inserting footnotes or endnotes may be essential. This article will demonstrate how to insert footnotes and endnotes in Word documents in C# and VB.NET 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 DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Insert a Footnote in Word in C# and VB.NET

A footnote consists of two parts - a footnote reference mark and the corresponding footnote text. To insert a footnote for a specific text, you need to search for the text and get the paragraph where the text is located, after that add a footnote to the paragraph, then insert the footnote reference mark after the found text and set the footnote text. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Search for a specific text in the document using Document.FindString() method and get the found text as a single text range using TextSelection.GetAsOneRange() method.
  • Access the owner paragraph of the text range through TextRange.OwnerParagraph property and get the index of the text range in the paragraph using Paragraph.ChildObjects.IndexOf() method.
  • Add a footnote to the paragraph using Paragraph.AppendFootnote(FootnoteType.Footnote) method.
  • Insert the footnote reference mark after the text range using Paragraph.ChildObjects.Insert() method.
  • Set the footnote text using Footnote.TextBody.AddParagraph().AppendText() method.
  • Set formatting such as font name, font size and text color for the footnote text and reference mark.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace InsertFootnote
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile(@"Sample.docx");

            //Find a specific text in the document
            TextSelection selection = document.FindString("Spire.Doc for .NET", false, true);
            //Get the found text as a single text range
            TextRange textRange = selection.GetAsOneRange();
            //Get the owner paragraph of the text range
            Paragraph paragraph = textRange.OwnerParagraph;
            //Get the index of the text range in the paragraph
            int index = paragraph.ChildObjects.IndexOf(textRange);

            //Add a footnote to the paragraph
            Footnote footnote = paragraph.AppendFootnote(FootnoteType.Footnote);
            //Insert the footnote reference mark after the text range
            paragraph.ChildObjects.Insert(index + 1, footnote);
            //Set the footnote text
            textRange = footnote.TextBody.AddParagraph().AppendText("Developed by E-iceblue Co., LTD.");

            //Set format for the footnote text
            textRange.CharacterFormat.FontName = "Arial Black";
            textRange.CharacterFormat.FontSize = 12;
            textRange.CharacterFormat.TextColor = Color.DarkGray;

            //Set format for the footnote reference mark
            footnote.MarkerCharacterFormat.FontName = "Calibri";
            footnote.MarkerCharacterFormat.FontSize = 12;
            footnote.MarkerCharacterFormat.Bold = true;
            footnote.MarkerCharacterFormat.TextColor = Color.DarkGreen;

            //Save the result document
            document.SaveToFile("InsertFootnote.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

C#/VB.NET: Insert Footnotes and Endnotes in Word Documents

Insert an Endnote in Word in C# and VB.NET

An endnote also consists of two parts - an endnote reference mark and the corresponding endnote text. The steps to insert an endnote for a specific text are very similar to that of the above example:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Search for a specific text in the document using Document.FindString() method and get the found text as a single text range using TextSelection.GetAsOneRange() method.
  • Access the owner paragraph of the text range through TextRange.OwnerParagraph property and get the index of the text range in the paragraph using Paragraph.ChildObjects.IndexOf() method.
  • Add an endnote to the paragraph using Paragraph.AppendFootnote(FootnoteType.Endnote) method.
  • Insert the endnote reference mark after the text range using Paragraph.ChildObjects.Insert() method.
  • Set the endnote text using Footnote.TextBody.AddParagraph().AppendText() method.
  • Set formatting such as font name, font size and text color for the endnote text and reference mark.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace InsertEndnote
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile(@"Sample.docx");

            //Find a specific text in the document
            TextSelection selection = document.FindString("Microsoft Office", false, true);
            //Get the found text as a single text range
            TextRange textRange = selection.GetAsOneRange();
            //Get the owner paragraph of the text range
            Paragraph paragraph = textRange.OwnerParagraph;
            //Get the index of the text range in the paragraph
            int index = paragraph.ChildObjects.IndexOf(textRange);

            //Add an endnote to the paragraph
            Footnote endnote = paragraph.AppendFootnote(FootnoteType.Endnote);
            //Insert the endnote reference mark after the text range
            paragraph.ChildObjects.Insert(index + 1, endnote);
            //Set the endnote text
            textRange = endnote.TextBody.AddParagraph().AppendText("Developed by Microsoft.");

            //Set format for the endnote text
            textRange.CharacterFormat.FontName = "Arial Black";
            textRange.CharacterFormat.FontSize = 12;
            textRange.CharacterFormat.TextColor = Color.DarkGray;

            //Set format for the endnote reference mark
            endnote.MarkerCharacterFormat.FontName = "Calibri";
            endnote.MarkerCharacterFormat.FontSize = 12;
            endnote.MarkerCharacterFormat.Bold = true;
            endnote.MarkerCharacterFormat.TextColor = Color.DarkGreen;

            //Save the result document
            document.SaveToFile("InsertEndnote.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

C#/VB.NET: Insert Footnotes and Endnotes in Word Documents

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.

This section will introduce a solution to export data from database to Excel for WPF. The whole solution is easily performed by this WPF Excel component Spire.XLS for WPF.

database to excel

In the task of database to Excel, first we need to connect with database by this class provided by Microsoft: System.Data.Oledb.OledbConnection. Here we use an MS access database. Then, OleDbCommand can help us specify a datatable from database in order to save the data in Dataset later. Finally fill the data into dataset table. After all the connection, we can see the key source code provided by Spire.XLS to export data columns from datatable to Excel: Spire.Xls.Worksheet.InsertDataTable(System.Data.DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn).

There are four parameters passed.

  • dataTable: The first parameter is to export the data column;
  • columnHeaders: the second is to indicate whether to import field names;
  • firstRow, firstColumn: the third and fourth parameters are index of first row and first column.

Here we can download Spire.XLS for WPF. After installing it on system, and start our database to excel task as below code:

[C#]
//export datatable to excel
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
sheet.InsertDataTable(t, true, 1, 1);
book.SaveToFile("insertTableToExcel.xls");
System.Diagnostics.Process.Start("insertTableToExcel.xls");
[VB.NET]
//export datatable to excel
Dim book As New Workbook()
Dim sheet As Worksheet = book.Worksheets(0)
sheet.InsertDataTable(t, True, 1, 1)
book.SaveToFile("insertTableToExcel.xls")
System.Diagnostics.Process.Start("insertTableToExcel.xls")
End Sub
End Class
End Namespace

In people's daily life, we can open a PDF document by right clicking the open option as well as using C#, VB.NET or other programming languages. Both methods are available as long as you have a PDF Document, but for PDF itself, it has no viewing function, thus, we need to use PDF Viewer to help us view it. This article is designed to open a PDF Document with C#, VB.NET via PDF Viewer by two methods.

Spire. PDFViewer is designed for viewing PDF files from .NET application. It does NOT require Adobe Read or any other 3rd party software/library installed on system. By using Spire.PDFViewer, we can do this job easily. Please just follow the below procedure.

Step 1: Create a new project

  • Freely Download Spire.PDFViewer
  • Create a new project in Visual Studio and add a toolScript in Form1
  • Set its target Framework to be .NET Framework 4
  • Add Spire.PdfViewer. Forms as reference in Project. And add using at the top of the method. Please see below:
[C#]
using System.IO; 
using Spire.PdfViewer.Forms;
[VB.NET]
Imports Sytem. IO
Imports Spire.PdfViewer.Forms

Step 2: Open a PDF Document with C#, VB.NET via Spire.PDFViewer

Method one: This method is to directly load a PDF file from system, then open it.

[C#]
        public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
         
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            string pdfDoc = @"D:\michelle\e-iceblue\Spire.Office.pdf";
            if (File.Exists(pdfDoc))
            {
                this.pdfDocumentViewer1.LoadFromFile(pdfDoc);
            }

        }
    }
 }
[VB.NET]
Public Partial Class Form1
		Inherits Form

		Public Sub New()

			InitializeComponent()
		End Sub

		Private Sub Form1_Load(sender As Object, e As EventArgs)

		End Sub

		Private Sub toolStripButton1_Click(sender As Object, e As EventArgs)
			Dim pdfDoc As String = "D:\michelle\e-iceblue\Spire.Office.pdf"
			If File.Exists(pdfDoc) Then
				Me.pdfDocumentViewer1.LoadFromFile(pdfDoc)
			End If

		End Sub
	End Class
End Namespace

Method Two: This method allows you to choose the PDF file you want to open in a dialog box from your computer.

[C#]
public partial class Form1 : Form
 {
       
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
         
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PDF document (*.pdf)|*.pdf";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    string pdfFile = dialog.FileName;
                    this.pdfDocumentViewer1.LoadFromFile(pdfFile);
                }
                catch (Exception exe)
                {
                    MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

        }
   }
[VB.NET]
Public Partial Class Form1
	Inherits Form

	Public Sub New()

		InitializeComponent()
	End Sub

	Private Sub Form1_Load(sender As Object, e As EventArgs)

	End Sub

	Private Sub toolStripButton1_Click(sender As Object, e As EventArgs)
		Dim dialog As New OpenFileDialog()
		dialog.Filter = "PDF document (*.pdf)|*.pdf"
		Dim result As DialogResult = dialog.ShowDialog()
		If result = DialogResult.OK Then
			Try
				Dim pdfFile As String = dialog.FileName
				Me.pdfDocumentViewer1.LoadFromFile(pdfFile)
			Catch exe As Exception
				MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.[Error])

			End Try
		End If

	End Sub
End Class

Step 3: Launch the file

Press F5, you can see Form1 display itself as picture below:

Then click "open" in the Form. When you use method one, you can see the PDF document content shows in the Form1. Also you can set the size of the form according to your own preference. When you use method two, you can choose the PDF Document by yourself in a dialog box. And then preview it in Form1.

Note: I set the default name of toolScript to be "open".

Effective Screenshot:

C#/VB.NET: Add Worksheets to Excel

2022-04-15 08:25:00 Written by Koohji

When working with an existing Excel file or creating an Excel file from scratch, we may need to add one or more worksheets to record data. In this article, we will demonstrate how to add worksheets to Excel in C# and VB.NET using Spire.XLS for .NET library.

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 DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Add a Worksheet to an Existing Excel file in C# and VB.NET

The following are the steps to add a worksheet to an existing Excel file:

  • C#
  • VB.NET
using Spire.Xls;

namespace AddWorksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Add a worksheet 
            Worksheet sheet = workbook.Worksheets.Add("New_Sheet");

            //Add data to cell (1, 1)
            sheet.Range[1, 1].Value = "New Sheet";

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

C#/VB.NET: Add Worksheets to Excel

Add a Worksheet to a New Excel File in C# and VB.NET

The following steps show how to create a new Excel file and add a worksheet to it:

  • C#
  • VB.NET
using Spire.Xls;

namespace AddWorksheetToNewExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Clear the default worksheets
            workbook.Worksheets.Clear();
            
            //Add a worksheet with name
            Worksheet sheet = workbook.Worksheets.Add("Sheet1");

            //Add data to cell (1, 1)
            sheet.Range[1, 1].Value = "Sheet 1";

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

C#/VB.NET: Add Worksheets to Excel

Add Multiple Worksheets to a New Excel File in C# and VB.NET

The following steps show how to create a new Excel file and add 3 worksheets to it:

  • C#
  • VB.NET
using Spire.Xls;

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

            //Add 3 worksheets 
            workbook.CreateEmptySheets(3);

            //Loop through the worksheets
            for (int i = 0; i < workbook.Worksheets.Count; i++)
            {
                Worksheet sheet = workbook.Worksheets[i];
                //Add data to cell (1, 1) in each worksheet
                sheet.Range[1, 1].Value = "Sheet " + (i + 1);
            }

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

C#/VB.NET: Add Worksheets to 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.

Finding specific text or phrases in a long Word document can be a bit of a hassle. Fortunately, MS Word provides the "Find" function to locate specific content in a document quickly. You can also highlight the found content with a background color to ensure that they won't be overlooked by the readers. This article will demonstrate how to programmatically find and highlight text 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 DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Find and Highlight Text in a Word Document

The detailed steps are as follows.

  • Create a Document instance
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find all matching text in the document using Document.FindAllString(string matchString, bool caseSensitive, bool wholeWord) method.
  • Loop through all matching text in the document.
  • Get the text range of a specific matching text using TextSelection.GetAsOneRange() method, and then set its highlight color using TextRange.CharacterFormat.HighlightColor property.
  • Save the result file using Document.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace FindHighlight
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

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

            //Find all matching text in the document
            TextSelection[] text = document.FindAllString("transcendentalism", false, true);

            //Loop through all matching text and set highlight color for them
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            //Save the result file
            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Find and Highlight Text in Word

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.

Word Heading can be taken as title of each part in Word document. This guide demonstrates solution to manage these Word headings and form them as a catalogue in C# and VB.NET.

In Word document, users can set some contents, for example, phrases of summary of the following paragraphs, as headings. These Word headings can be displayed in the first page of whole document and form as catalogue after arrangement so that readers can get outline of whole document. Solution in this guide presents how to manage Word headings with numbered style in a new created document in C# and VB.NET via Spire.Doc for .NET and screenshot below shows results of managing Word headings.

Word Paragraph Headings

Heading is one of kind of styles for paragraphs and Spire.Doc for .NET provides several BuiltinStyle types for paragraphs. In this example, three BuiltinStyle types will be applied: Heading1, Heading2 and Heading3. Following, details will be presented step by step.

Firstly, initialize a Document instance and add section, paragraph for this instance. Secondly, invoke AppendText method with parameter string text and ApplyStyle(BuiltinStyle.Heading1) method of Paragraph class to add text and set heading style for new added paragraph. Then, invoke ListFromat.ApplyNumberedStyle() method of Paragraph class to set number list for it. Thirdly, add new paragraph and set Heading2 style for it as the previous step. Initialize a ListStyle instance for document with Numbered ListType. Then, initialize a ListLevel instance from ListStyle and set UsePrevLevelPattern and NumberPrefix properties for this instance. After that, invoke ListStyleCollection.Add(ListStyle) method of Document class and ListFormat.ApplyStyle method of Paragraph class with parameter string styleName to add ListStyle for Heading2. Fourthly, add a new paragraph and set BuiltinStyle as Heading3 and apply ListStyle for this paragraph as the previous step. Finally, invoke SaveToFile method of Document class with parameter string fileName and FileFormat to save this document. Refer the code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordHeading
{
    class Heading
    {
        static void Main(string[] args)
        {
             //Create Document
             Document document = new Document();
             Section section = document.AddSection();
             Paragraph paragraph = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();

             //Add Heading 1
             paragraph = section.AddParagraph();
             paragraph.AppendText(BuiltinStyle.Heading1.ToString());
             paragraph.ApplyStyle(BuiltinStyle.Heading1);
             paragraph.ListFormat.ApplyNumberedStyle();

             //Add Heading 2
             paragraph = section.AddParagraph();
             paragraph.AppendText(BuiltinStyle.Heading2.ToString());
             paragraph.ApplyStyle(BuiltinStyle.Heading2);

             //List Style for Headings 2
             ListStyle listSty2 = document.Styles.Add(ListType.Numbered, "MyStyle2");

             foreach (ListLevel listLev in listSty2.ListRef.Levels)
             {
                 listLev.UsePrevLevelPattern = true;
                 listLev.NumberPrefix = "1.";
             }

             paragraph.ListFormat.ApplyStyle(listSty2.Name);

             //Add List Style 3
             ListStyle listSty3 = document.Styles.Add(ListType.Numbered, "MyStyle3");
             foreach (ListLevel listLev in listSty3.ListRef.Levels)
             {
                 listLev.UsePrevLevelPattern = true;
                 listLev.NumberPrefix = "1.1.";
             }

             //Add Heading 3
             for (int i = 0; i < 4; i++)
             {
                 paragraph = section.AddParagraph();

                 //Append Text
                 paragraph.AppendText(BuiltinStyle.Heading3.ToString());

                 //Apply List Style 3 for Heading 3
                 paragraph.ApplyStyle(BuiltinStyle.Heading3);
                 paragraph.ListFormat.ApplyStyle(listSty3.Name);
             }

             //Save and Launch
             document.SaveToFile("Word Headings.docx", FileFormat.Docx);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordHeading
    Friend Class Heading
        Shared Sub Main(ByVal args() As String)
         'Create Document
         Dim document As New Document()
         Dim section As Section = document.AddSection()
         Dim paragraph As Paragraph = If(section.Paragraphs.Count > 0, section.Paragraphs(0), section.AddParagraph())

         'Add Heading 1
         paragraph = section.AddParagraph()
         paragraph.AppendText(BuiltinStyle.Heading1.ToString())
         paragraph.ApplyStyle(BuiltinStyle.Heading1)
         paragraph.ListFormat.ApplyNumberedStyle()

         'Add Heading 2
         paragraph = section.AddParagraph()
         paragraph.AppendText(BuiltinStyle.Heading2.ToString())
         paragraph.ApplyStyle(BuiltinStyle.Heading2)

         ' List Style for Headings 2
         Dim listSty2 As ListStyle = document.Styles.Add(ListType.Numbered, "MyStyle2")

         For Each listLev As ListLevel In listSty2.ListRef.Levels
             listLev.UsePrevLevelPattern = True
             listLev.NumberPrefix = "1."
         Next

         paragraph.ListFormat.ApplyStyle(listSty2.Name)

         ' Add List Style 3
         Dim listSty3 As ListStyle = document.Styles.Add(ListType.Numbered, "MyStyle3")

         For Each listLev As ListLevel In listSty3.ListRef.Levels
             listLev.UsePrevLevelPattern = True
             listLev.NumberPrefix = "1.1."
         Next

         'Add Heading 3
         For i As Integer = 0 To 3
             paragraph = section.AddParagraph()

             'Append Text
             paragraph.AppendText(BuiltinStyle.Heading3.ToString())

             'Apply List Style 3 for Heading 3
             paragraph.ApplyStyle(BuiltinStyle.Heading3)
             paragraph.ListFormat.ApplyStyle(listSty3.Name)
         Next i

         'Save and Launch
         document.SaveToFile("Word Headings.docx", FileFormat.Docx)
        End Sub
    End Class
End Namespace

Spire.Doc, as professional Word component, is very powerful on fast generating, loading, writing, modifying and saving Word documents in .NET, WPF, Silverlight without Word automation and any third party tools.

C#/VB.NET: Set or Get PDF Properties

2023-06-30 06:13:00 Written by Koohji

PDF properties are metadata that provide additional information about a PDF file. Typically, these properties include, but are not limited to, the title of the document, the author, keywords, subject and the application that created the document. When there are a large number of PDF files, adding properties is essential as it can make the files easily retrievable. In this article, you will learn how to programmatically set or get PDF properties using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF 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.PDF

Set the Properties of a PDF File in C# and VB.NET

Basic PDF document properties such as title, author, subject and keywords make it easier for users to search or retrieve specific documents later on. The following are the detailed steps on how to set these properties using Spire.PDF for .NET.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get PDF properties using PdfDocument.DocumentInformation property, and then set values for specific document properties such as title, subject and author through Title, Subject and Author properties of PdfDocumentInformation class.
  • Save the result PDF file using PdfDocument.SaveToFile () method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace PDFProperties
{
    class Properties
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document
            pdf.LoadFromFile("input.pdf");

            //Set the title
            pdf.DocumentInformation.Title = "PDF (Portable Document Format)";

            //Set the author
            pdf.DocumentInformation.Author = "E-iceblue";

            //Set the subject
            pdf.DocumentInformation.Subject = "Set PDF Properties";

            //Set the keywords
            pdf.DocumentInformation.Keywords = "NET PDF, Properties, Document";

            //Set the producer name
            pdf.DocumentInformation.Producer = "Spire.PDF";

            //Save the result document
            pdf.SaveToFile("PdfProperties.pdf");
        }
    }
}

C#/VB.NET: Set or Get PDF Properties

Get the Properties of a PDF File in C# and VB.NET

To get specific PDF properties, you can use the corresponding properties under the PdfDocumentInformation class. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get PDF properties using PdfDocument.DocumentInformation property, and then get specific document properties such as title, author, keyword using properties under PdfDocumentInformation class.
  • Append the extracted properties to the StringBuilder instance using StringBuilder.Append() method.
  • Write the StringBuilder to a TXT file using File.WriteAllText() method.
  • C#
  • VB.NET
using Spire.Pdf;
using System.IO;
using System.Text;

namespace GetPdfProperties

{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document 
            pdf.LoadFromFile("PdfProperties.pdf");

            //Create a StringBuilder instance
            StringBuilder content = new StringBuilder();

            //Get the PDF document properties and append them in the StringBuilder
            content.Append("Title: " + pdf.DocumentInformation.Title + "\r\n");
            content.Append("Author: " + pdf.DocumentInformation.Author + "\r\n");
            content.Append("Subject: " + pdf.DocumentInformation.Subject + "\r\n");
            content.Append("Keywords: " + pdf.DocumentInformation.Keywords + "\r\n");
            content.Append("PDF Producer: " + pdf.DocumentInformation.Producer + "\r\n");

            //Write the StringBuilder to a TXT file
            File.WriteAllText("GetPDFProperties.txt", content.ToString());
        }
    }
} 

C#/VB.NET: Set or Get PDF Properties

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.

Draw PDF Table in C#/VB.NET

2012-06-12 05:59:58 Written by Koohji

PDF table is one of the best ways to display data information. Using it, all the data can be quickly and clearly read. This section will introduce a solution to draw PDF table via a .NET PDF component in C#, VB.NET.

Using Spire.PDF for .NET (a .NET PDF library for manipulating PDF files), you can draw PDF table through two simple steps. One is to draw all the data by a string array. Another step is to split these string array by string[] Split(params char[] separator); Thus, a PDF table has been drawn. From below picture, you can see the effect of the task:

Here, you can download Spire.PDF for .NET and install it on your system. After adding the Spire.Pdf dll from your Bin folder, you can follow below key code to draw your PDF table in C#, VB.NET.

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


namespace DrawPDFTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            PdfSection sec = doc.Sections.Add();
            sec.PageSettings.Width = PdfPageSize.A4.Width;
            PdfPageBase page = sec.Pages.Add();
            float y = 10;
            //title
            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Country List", format1).Height;
            y = y + 5;

            String[] data
         = {
   "PartNo;Description;OnHand;OnOrder;Cost;ListPrice",
   "900;Dive kayak;24;16;1356.75;3999.95",
   "912;Underwater Diver Vehicle;5;3;504;1680",
   "1313;Regulator System;165;216;117.5;250",
   "1314;Second Stage Regulator;98;88;124.1;365",
   "1316;Regulator System;75;70;119.35;341",
   "1320;Second Stage Regulator;37;35;73.53;171",
   "1328;Regulator System;166;100;154.8;430",
   "1330;Alternate Inflation Regulator;47;43;85.8;260",
   "1364;Second Stage Regulator;128;135;99.9;270",
   "1390;First Stage Regulator;146;140;64.6;170",
   "1946;Second Stage Regulator;13;10;95.79;309",
   "1986;Depth/Pressure Gauge Console;25;24;73.32;188",
   "2314;Electronic Console;13;12;120.9;390",
   "2341;Depth/Pressure Gauge;226;225;48.3;105",
   "2343;Personal Dive Sonar;46;45;72.85;235",
   "2350;Compass Console Mount;211;300;10.15;29"
       };
            String[][] dataSource
                = new String[data.Length][];
            for (int i = 0; i < data.Length; i++)
            {
                dataSource[i] = data[i].Split(';');
            }

            PdfTable table = new PdfTable();
            table.Style.CellPadding = 2;
            table.Style.BorderPen = new PdfPen(brush1, 0.75f);
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            table.Style.HeaderSource = PdfHeaderSource.Rows;
            table.Style.HeaderRowCount = 1;
            table.Style.ShowHeader = true;
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
            table.DataSource = dataSource;
            foreach (PdfColumn column in table.Columns)
            {
                column.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            }
            table.Draw(page, new PointF(0, y));

            doc.SaveToFile("SimpleTable.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Imports System.Drawing


Namespace DrawPDFTable
	Class Program
		Private Shared Sub Main(args As String())
			'Create a pdf document.
			Dim doc As New PdfDocument()
			Dim sec As PdfSection = doc.Sections.Add()
			sec.PageSettings.Width = PdfPageSize.A4.Width
			Dim page As PdfPageBase = sec.Pages.Add()
			Dim y As Single = 10
			'title
			Dim brush1 As PdfBrush = PdfBrushes.Black
			Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16F, FontStyle.Bold))
			Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
			page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1)
			y = y + font1.MeasureString("Country List", format1).Height
			y = y + 5

			Dim data As [String]() = {"PartNo;Description;OnHand;OnOrder;Cost;ListPrice", "900;Dive kayak;24;16;1356.75;3999.95", "912;Underwater Diver Vehicle;5;3;504;1680", "1313;Regulator System;165;216;117.5;250", "1314;Second Stage Regulator;98;88;124.1;365", "1316;Regulator System;75;70;119.35;341", _
				"1320;Second Stage Regulator;37;35;73.53;171", "1328;Regulator System;166;100;154.8;430", "1330;Alternate Inflation Regulator;47;43;85.8;260", "1364;Second Stage Regulator;128;135;99.9;270", "1390;First Stage Regulator;146;140;64.6;170", "1946;Second Stage Regulator;13;10;95.79;309", _
				"1986;Depth/Pressure Gauge Console;25;24;73.32;188", "2314;Electronic Console;13;12;120.9;390", "2341;Depth/Pressure Gauge;226;225;48.3;105", "2343;Personal Dive Sonar;46;45;72.85;235", "2350;Compass Console Mount;211;300;10.15;29"}
			Dim dataSource As [String]()() = New [String](data.Length - 1)() {}
			For i As Integer = 0 To data.Length - 1
				dataSource(i) = data(i).Split(";"C)
			Next

			Dim table As New PdfTable()
			table.Style.CellPadding = 2
			table.Style.BorderPen = New PdfPen(brush1, 0.75F)
			table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
			table.Style.HeaderSource = PdfHeaderSource.Rows
			table.Style.HeaderRowCount = 1
			table.Style.ShowHeader = True
			table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue
			table.DataSource = dataSource
			For Each column As PdfColumn In table.Columns
				column.StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
			Next
			table.Draw(page, New PointF(0, y))

			doc.SaveToFile("SimpleTable.pdf")
		End Sub
	End Class
End Namespace

Spire.PDF for .NET is a professional .NET PDF component which enables you to create, edit and handle PDF files in C#, VB.NET.

PDF format, beyond all doubt, provides great convenience for people in daily work. But sometimes, the character of requiring an external application like Acrobat Reader makes things more complex. For example, images can be easily and quickly presented on browsers as long as you have image addresses or load them from your system. While for PDF document, it has to be presented by an external application. Besides, loading images can save much time compared with loading a PDF file since images can be loaded one by one, while PDF file is only available after the complete PDF document is downloaded. Furthermore, images are more likely to handle by Office applications. That is why people need to export PDF document pages to images.

When it comes to the conversion or transformation from this document format to another, people subconsciously think about conversion software. But for Spire.PDF Viewer, you do not need any PDF converter and can realize the PDF to image task in two ways. Moreover, you can export the PDF pages to any image format such as png, jpg, bmp and so on. Finally, except exporting PDF pages to images, Spire.PDFViewer is a totally independent .NET library and has other functions such as open and read encrypted PDF files, view embedded PDF file with hyperlinks and so on.

Two solutions will be displayed to finish this task. The first solution is more complicated than the second one but it has more functions. So both methods have their own advantages. You can choose any one according to your own need.

Export PDF to Images Solution 1

This method requires two forms. One is to load PDF document and the other is to display images which are exported from PDF file. You can export any page or pages to save as images. Details can be shown in the below procedure.

Step 1: Create a new project

  • Create a new project in Windows Forms Application.
  • Set the Target Framework to be .NET Framework 2 or above in Properties.
  • Set the target Framework in this project Properties to be .NET Framework 2.0 or above.

Step 2: Design two Forms

  • Add a toolScript and PdfDocumentViewer in Form1.
  • Add three Buttons, two Labels and two ComboBoxes in Form1 from the toolScript dropdown list.
  • Set the Properties of the Buttons, Labels, ComboBoxes and PdfDocumentViewer as below table.
  • Add another Form in Windows Form from Add item by right clicking the project. I name this Form to be FormImages.
  • In FormImages, I add a FlowLayoutPanel to it and set its Name to be panelImages1, the Dock property to be Fill.

Step 3: Export PDF file pages to images

Click Form1, add Spire.PDFViewer Forms dll as reference from your downloaded Spire.PDFViewer. Then, add namespaces to the top of the method.

[C#]
using System.IO;
using Spire.PdfViewer.Forms;
[VB.NET]
Imports System.IO
Imports Spire.PdfViewer.Forms

Load a PDF file from system and open it. This step also enables you to open another PDF from your system by clicking the "Open" button in Form1.

[C#]
private void Form1_Load(object sender, EventArgs e)
        {
            string pdfDoc = @"D:\michelle\e-iceblue\Spire.PDFViewer\Demos\Data\PDFViewer.pdf";
            if (File.Exists(pdfDoc))
            {
                this.pdfDocumentViewer1.LoadFromFile(pdfDoc);
            }
        }
private void btnOpen_Click(object sender, EventArgs e)
       {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PDF document (*.pdf)|*.pdf";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    string pdfFile = dialog.FileName;
                    this.pdfDocumentViewer1.LoadFromFile(pdfFile);
                }
                catch (Exception exe)
                {
                    MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }
[VB.NET]
Private Sub Form1_Load(sender As Object, e As EventArgs)
		Dim pdfDoc As String = "D:\michelle\e-iceblue\Spire.PDFViewer\Demos\Data\PDFViewer.pdf"
		If File.Exists(pdfDoc) Then
			Me.pdfDocumentViewer1.LoadFromFile(pdfDoc)
		End If
End Sub

Private Sub btnOpen_Click(sender As Object, e As EventArgs)
	Dim dialog As New OpenFileDialog()
	dialog.Filter = "PDF document (*.pdf)|*.pdf"
	Dim result As DialogResult = dialog.ShowDialog()
	If result = DialogResult.OK Then
		Try
			Dim pdfFile As String = dialog.FileName
		Me.pdfDocumentViewer1.LoadFromFile(pdfFile)
		Catch exe As Exception
			MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.[Error])

		End Try
	End If
End Sub

Load the PDF document and use the "this.pdfDocumentViewer1.SaveAsImage(currentPage - 1)" to save the current PDF page as image.

[C#]
private void pdfDocumentViewer1_PdfLoaded(object sender, EventArgs args)
{
            this.comBoxFrom.Items.Clear();
            this.comboxTo.Items.Clear();

            int totalPage = this.pdfDocumentViewer1.PageCount;
            for (int i = 1; i <= totalPage; i++)
            {
                this.comBoxFrom.Items.Add(i.ToString());
                this.comboxTo.Items.Add(i.ToString());


            }
            this.comBoxFrom.SelectedIndex = 0;
            this.comboxTo.SelectedIndex = 0;

 }
private void btnExport_Click(object sender, EventArgs e)
 {
            if (this.pdfDocumentViewer1.PageCount > 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "JPG Format(*.jpg)|*.jpg|BMP Format(*.bmp)|*.bmp|PNG Format(*.png)|*.png|GIF Format(*.gif)|*.gif";
                DialogResult result = dialog.ShowDialog();
                string fileName = dialog.FileName;
                if (result == DialogResult.OK)
                {

                    int currentPage = this.pdfDocumentViewer1.CurrentPageNumber;
                    Bitmap image = this.pdfDocumentViewer1.SaveAsImage(currentPage - 1);
                    image.Save(fileName);
                    MessageBox.Show("You have exported current page to an image:\n" + fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);


                    Dictionary dictionaryImages = new Dictionary();
                    dictionaryImages.Add(fileName, image);

                    this._formImages = new FormImages();
                    this._formImages.DictionaryImages = dictionaryImages;
                    this._formImages.Show();

                  }
              }
  }
[VB.NET]
Private Sub pdfDocumentViewer1_PdfLoaded(sender As Object, args As EventArgs)
	Me.comBoxFrom.Items.Clear()
	Me.comboxTo.Items.Clear()
	Dim totalPage As Integer = Me.pdfDocumentViewer1.PageCount
	For i As Integer = 1 To totalPage
		Me.comBoxFrom.Items.Add(i.ToString())
		Me.comboxTo.Items.Add(i.ToString())
	Next
	Me.comBoxFrom.SelectedIndex = 0
	Me.comboxTo.SelectedIndex = 0
End Sub
Private Sub btnExport_Click(sender As Object, e As EventArgs)
	If Me.pdfDocumentViewer1.PageCount > 0 Then
		Dim dialog As New SaveFileDialog()
		dialog.Filter = "JPG Format(*.jpg)|*.jpg|BMP Format(*.bmp)|*.bmp|PNG Format(*.png)|*.png|GIF Format(*.gif)|*.gif"
		Dim result As DialogResult = dialog.ShowDialog()
		Dim fileName As String = dialog.FileName
		If result = DialogResult.OK Then
			Dim currentPage As Integer = Me.pdfDocumentViewer1.CurrentPageNumber
			Dim image As Bitmap = Me.pdfDocumentViewer1.SaveAsImage(currentPage - 1)
			image.Save(fileName)
			MessageBox.Show("You have exported current page to an image:" & vbLf & fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information)
			Dim dictionaryImages As New Dictionary(Of String, Image)()
			dictionaryImages.Add(fileName, image)
			Me._formImages = New FormImages()
			Me._formImages.DictionaryImages = dictionaryImages
			Me._formImages.Show()
		End If
	End If
End Sub

Save multiple pages as images by selecting the PDF export range from the start page to the end page. And use the "this.pdfDocumentViewer1.SaveAsImage(fromPage, toPage)" method to save the images.

[C#]
private void btnMultiExport_Click(object sender, EventArgs e)
{
            if (this.pdfDocumentViewer1.PageCount <= 0)
            {
                return;
            }

            int fromPage = this.comBoxFrom.SelectedIndex;
            int toPage = this.comboxTo.SelectedIndex;
            if (fromPage > toPage)
            {
                MessageBox.Show("End page number must be not less than started page number!", "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();


                DialogResult result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                {

                    string path = dialog.SelectedPath;
                    Bitmap[] images = this.pdfDocumentViewer1.SaveAsImage(fromPage, toPage);
                    Dictionary dictionaryImages = new Dictionary();
                    for (int i = 0; i < images.Length; i++)
                    {
                        string name = "image" + (i + 1 + fromPage).ToString() + ".bmp";
                        string fileName = path + "\\" + name;
                        images[i].Save(fileName);
                        dictionaryImages.Add(fileName, images[i]);

                    }
                    string message = "You have exported " + (fromPage + 1).ToString() + "-" + (toPage + 1).ToString() + " pages as images to:\n"
                       + path;
                    MessageBox.Show(message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this._formImages = new FormImages();
                    this._formImages.DictionaryImages = dictionaryImages;
                    this._formImages.Show();

                }
            }
   }
[VB.net]
Private Sub btnMultiExport_Click(sender As Object, e As EventArgs)
		If Me.pdfDocumentViewer1.PageCount <= 0 Then
			Return
		End If

		Dim fromPage As Integer = Me.comBoxFrom.SelectedIndex
		Dim toPage As Integer = Me.comboxTo.SelectedIndex
		If fromPage > toPage Then
			MessageBox.Show("End page number must be not less than started page number!", "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Warning)
			Return
		Else
			Dim dialog As New FolderBrowserDialog()
			Dim result As DialogResult = dialog.ShowDialog()
			If result = DialogResult.OK Then
				Dim path As String = dialog.SelectedPath
				Dim images As Bitmap() = Me.pdfDocumentViewer1.SaveAsImage(fromPage, toPage)
				Dim dictionaryImages As Dictionary(Of [String], Image) = New Dictionary(Of String, Image)()
				For i As Integer = 0 To images.Length - 1
					Dim name As String = "image" & (i + 1 + fromPage).ToString() & ".bmp"
					Dim fileName As String = path & "\" & name
					images(i).Save(fileName)
					dictionaryImages.Add(fileName, images(i))
				Next
				Dim message As String = "You have exported " & (fromPage + 1).ToString() & "-" & (toPage + 1).ToString() & " pages as images to:" & vbLf & path
				MessageBox.Show(message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information)
				Me._formImages = New FormImages()
				Me._formImages.DictionaryImages = dictionaryImages
				Me._formImages.Show()
			End If
		End If
	End Sub

Display the images in the second Form: FormImages.

[C#]
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Spire.PdfViewer.Forms;

namespace  pdf2images1
{
    public partial class FormImages : Form
    {

        private Dictionary _dictionaryImags;

        public Dictionary DictionaryImages
        {
            get { return this._dictionaryImags; }
            set
            {
                this._dictionaryImags = value;
                this.ViewImages();
            }
        }
        public FormImages()
        {
            InitializeComponent();
        }

        public void ViewImages()
        {
            if (this.DictionaryImages != null && this.DictionaryImages.Count > 0)
            {
                this.panelImages1.Controls.Clear();
                String image_name = "";
                int panelHeight = 0;
                int panelWidth = 0;

                foreach (KeyValuePair pair in this.DictionaryImages)
                {
                    image_name = pair.Key;

                    Panel panelImage = new Panel();
                    panelImage.AutoSize = true;


                    PictureBox ptrBox = new PictureBox();
                    ptrBox.Height = 150;
                    ptrBox.Width = 200;

                    ptrBox.SizeMode = PictureBoxSizeMode.Zoom;

                    ptrBox.Image = pair.Value;
                    ptrBox.Cursor = Cursors.Hand;

                    panelImage.Controls.Add(ptrBox);

                    LinkLabel lbl = new LinkLabel();
                    String imageName = Path.GetFileName(pair.Key);
                    lbl.Text = imageName;
                    int x = (Int32)(ptrBox.Width / 2 - lbl.Width / 2);
                    int y = ptrBox.Height;
                    lbl.Left = x;
                    lbl.Top = y;
                    panelImage.Controls.Add(lbl);

                    this.panelImages1.Controls.Add(panelImage);

                    this.SetClickEventHandler(ptrBox, lbl, image_name);
                    panelHeight = panelImage.Height;
                    panelWidth = panelImage.Width;

                }
                int nimages = this._dictionaryImags.Count;
                if (nimages >= 4)
                {

                    int n = (Int32)Math.Ceiling(Math.Sqrt(nimages));

                    this.Width = panelWidth * n + 20 * (n - 1) + 40;
                    this.Height = panelHeight * n + 20 * (n - 1) + 40;
                }
            }
        }
        private void SetClickEventHandler(PictureBox ptrBox, LinkLabel lbl, string imageName)
        {
            ptrBox.Click += new EventHandler(delegate(Object sender, EventArgs args)
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(imageName);
                process.StartInfo = info;
                process.Start();
            });

            lbl.Click += new EventHandler(delegate(Object sender, EventArgs args)
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(imageName);
                process.StartInfo = info;
                process.Start();
            });

        }
    }
}
[VB.NET]
Imports System.Collections.Generic
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms

Namespace pdf2images1
	Public Partial Class FormImages
		Inherits Form
		Private _dictionaryImags As Dictionary(Of [String], Image)
		Public Property DictionaryImages() As Dictionary(Of [String], Image)
			Get
				Return Me._dictionaryImags
			End Get
			Set
				Me._dictionaryImags = value
				Me.ViewImages()
			End Set
		End Property
		Public Sub New()
			InitializeComponent()
		End Sub

		Public Sub ViewImages()
			If Me.DictionaryImages IsNot Nothing AndAlso Me.DictionaryImages.Count > 0 Then
				Me.panelImages1.Controls.Clear()
				Dim image_name As [String] = ""
				Dim panelHeight As Integer = 0
				Dim panelWidth As Integer = 0

				For Each pair As KeyValuePair(Of [String], Image) In Me.DictionaryImages
					image_name = pair.Key

					Dim panelImage As New Panel()
					panelImage.AutoSize = True


					Dim ptrBox As New PictureBox()
					ptrBox.Height = 150
					ptrBox.Width = 200

					ptrBox.SizeMode = PictureBoxSizeMode.Zoom

					ptrBox.Image = pair.Value
					ptrBox.Cursor = Cursors.Hand

					panelImage.Controls.Add(ptrBox)

					Dim lbl As New LinkLabel()
					Dim imageName As [String] = Path.GetFileName(pair.Key)
					lbl.Text = imageName
					Dim x As Integer = CType(ptrBox.Width \ 2 - lbl.Width \ 2, Int32)
					Dim y As Integer = ptrBox.Height
					lbl.Left = x
					lbl.Top = y
					panelImage.Controls.Add(lbl)

					Me.panelImages1.Controls.Add(panelImage)

					Me.SetClickEventHandler(ptrBox, lbl, image_name)
					panelHeight = panelImage.Height

					panelWidth = panelImage.Width
				Next
				Dim nimages As Integer = Me._dictionaryImags.Count
				If nimages >= 4 Then

					Dim n As Integer = CType(Math.Truncate(Math.Ceiling(Math.Sqrt(nimages))), Int32)

					Me.Width = panelWidth * n + 20 * (n - 1) + 40
					Me.Height = panelHeight * n + 20 * (n - 1) + 40
				End If
			End If
		End Sub
		Private Sub SetClickEventHandler(ptrBox As PictureBox, lbl As LinkLabel, imageName As String)
			AddHandler ptrBox.Click, New EventHandler(Function(sender As [Object], args As EventArgs) Do
				Dim process As New System.Diagnostics.Process()
				Dim info As New System.Diagnostics.ProcessStartInfo(imageName)
				process.StartInfo = info
				process.Start()
			End Function)

			AddHandler lbl.Click, New EventHandler(Function(sender As [Object], args As EventArgs) Do
				Dim process As New System.Diagnostics.Process()
				Dim info As New System.Diagnostics.ProcessStartInfo(imageName)
				process.StartInfo = info
				process.Start()
			End Function)
		End Sub
	End Class
End Namespace

Step 4: Debug the project

Click the Debug or Press F5 to launch the project. You can preview as below.

Export Page 4-7

Display Image 4-7

Export PDF to Image Solution 2

This method is much simple and it needs a Form generated dynamically. Two buttons are provided. One is for exporting the current PDF page, the other is for exporting multiple pages. The difference between the first method and the second lies in you can choose any export range in the first method. For example, you can choose page 4-7 to save as images, but when you use method two, you have to save all the pages from 1-7 since it only support to save page from 1 to current page as images. Please look at the procedure.

Step 1: Create a new project

  • Create a new project in Console Application.
  • Set the target Framework to be .NET Framework 2 or above.
  • Add System. Drawing and Spire.PdfViewer.Forms. dll as references and add the below namespaces at the top of the method.
[C#]
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Spire.PdfViewer.Forms;
[VB.NET]
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Imports Spire.PdfViewer.Forms

Step 2: Export PDF file pages to images

Load a PDF file from system

[C#]
viewer = new PdfDocumentViewer();
viewer.LoadFromFile(@"D:\michelle\e-iceblue\Spire.PDFViewer\Demos\Data\PDFViewer.pdf");
[VB.NET]
viewer = New PdfDocumentViewer()
viewer.LoadFromFile("D:\michelle\e-iceblue\Spire.PDFViewer\Demos\Data\PDFViewer.pdf")

Create a new Form and design it. Except setting the properties of this Form, two buttons are added also. One is for exporting one page, and the other multiple pages.

[C#]
            //form and child components
            Form mainForm = new Form();
            mainForm.Text = "Spire.PdfView Demo - Export";
            mainForm.Size = new System.Drawing.Size(800, 600);
            mainForm.StartPosition = FormStartPosition.CenterScreen;

            TableLayoutPanel table = new TableLayoutPanel();
            table.ColumnCount = 3;
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 20));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
            table.RowCount = 2;
            table.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
            table.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));

            table.Controls.Add(viewer, 0, 0);
            table.SetColumnSpan(viewer, 3);
            viewer.Dock = DockStyle.Fill;

            //Export current page to one image
            Button button = new Button();
            button.Text = "Export to one image";
            button.Size = new Size(180, 24);
            button.TextAlign = ContentAlignment.MiddleCenter;
            table.Controls.Add(button, 0, 1);
            button.Dock = DockStyle.Right;
            button.Click += ExportToOneImage;

            //Export current pdf document to multiple images
            button = new Button();
            button.Text = "Export to multiple images";
            button.Size = new Size(180, 24);
            button.TextAlign = ContentAlignment.MiddleCenter;
            table.Controls.Add(button, 2, 1);
            button.Dock = DockStyle.Left;
            button.Click += ExportToMultipleImages;

            mainForm.Controls.Add(table);
            table.Dock = DockStyle.Fill;

            Application.Run(mainForm);
[VB.NET]
	'form and child components
	Dim mainForm As New Form()
	mainForm.Text = "Spire.PdfView Demo - Export"
	mainForm.Size = New System.Drawing.Size(800, 600)
	mainForm.StartPosition = FormStartPosition.CenterScreen

	Dim table As New TableLayoutPanel()
	table.ColumnCount = 3
	table.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 50))
	table.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 20))
	table.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 50))
	table.RowCount = 2
	table.RowStyles.Add(New RowStyle(SizeType.Percent, 100))
	table.RowStyles.Add(New RowStyle(SizeType.Absolute, 30))

	table.Controls.Add(viewer, 0, 0)
	table.SetColumnSpan(viewer, 3)
	viewer.Dock = DockStyle.Fill

	'Export current page to one image
	Dim button As New Button()
	button.Text = "Export to one image"
	button.Size = New Size(180, 24)
	button.TextAlign = ContentAlignment.MiddleCenter
	table.Controls.Add(button, 0, 1)
	button.Dock = DockStyle.Right
	AddHandler button.Click, AddressOf ExportToOneImage

	'Export current pdf document to multiple images
	button = New Button()
	button.Text = "Export to multiple images"
	button.Size = New Size(180, 24)
	button.TextAlign = ContentAlignment.MiddleCenter
	table.Controls.Add(button, 2, 1)
	button.Dock = DockStyle.Left
	AddHandler button.Click, AddressOf ExportToMultipleImages

	mainForm.Controls.Add(table)
	table.Dock = DockStyle.Fill

	Application.Run(mainForm)

Save the current PDF page as one image.

[C#]
private static void ExportToOneImage(object sender, EventArgs e)
      {
         if (viewer.PageCount > 0)
          {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "PNG Format(*.png)|*.png";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    int currentPage = viewer.CurrentPageNumber;
                    Bitmap image = viewer.SaveAsImage(currentPage - 1);
                    image.Save(dialog.FileName);
                    MessageBox.Show("You have exported current page to an image:\n" + dialog.FileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
[VB.NET]
Private Shared Sub ExportToOneImage(sender As Object, e As EventArgs)
	If viewer.PageCount > 0 Then
		Dim dialog As New SaveFileDialog()
		dialog.Filter = "PNG Format(*.png)|*.png"
		If dialog.ShowDialog() = DialogResult.OK Then
			Dim currentPage As Integer = viewer.CurrentPageNumber
			Dim image As Bitmap = viewer.SaveAsImage(currentPage - 1)
			image.Save(dialog.FileName)
			MessageBox.Show("You have exported current page to an image:" & vbLf & dialog.FileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information)
		End If
	End If
End Sub

Save multiple PDF pages to images.

[C#]
private static void ExportToMultipleImages(object sender, EventArgs e)
        {
            if (viewer.PageCount > 0)
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    int currentPage = viewer.CurrentPageNumber;
                    Bitmap[] images = viewer.SaveAsImage(0, currentPage - 1);
                    for (int i = 0; i < images.Length; i++)
                    {
                        String fileName = Path.Combine(dialog.SelectedPath, String.Format("PDFViewer-{0}.png", i));
                        images[i].Save(fileName);
                    }
                    string message = "You have exported 1" + "-" + currentPage.ToString() + " pages as images to:\n" + dialog.SelectedPath;
                    MessageBox.Show(message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
[VB.NET]
Private Shared Sub ExportToMultipleImages(sender As Object, e As EventArgs)
	If viewer.PageCount > 0 Then
		Dim dialog As New FolderBrowserDialog()
		If dialog.ShowDialog() = DialogResult.OK Then
			Dim currentPage As Integer = viewer.CurrentPageNumber
			Dim images As Bitmap() = viewer.SaveAsImage(0, currentPage - 1)
			For i As Integer = 0 To images.Length - 1
				Dim fileName As [String] = Path.Combine(dialog.SelectedPath, [String].Format("PDFViewer-{0}.png", i))
				images(i).Save(fileName)
			Next
			Dim message As String = "You have exported 1" & "-" & currentPage.ToString() & " pages as images to:" & vbLf & dialog.SelectedPath
			MessageBox.Show(message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information)
		End If
	End If
End Sub

Step 3: Debug the project

Press F5 or click Debug to launch the project. Then, preview the effect.

Form

Export Multiple PDF Pages

Obviously, the second method is easier than the first one. But if you have a PDF document with hundreds of pages, solution 1 can exporting the specified pages in a fast speed and, to a large extent, it escapes the trouble of saving numerous PDF pages as images. While, for some PDF file with a few pages, solution 2 is more convenient.

Spire.PDFViewer is a powerful PDF Viewer component performed on .NET and WPF. It enables developers to load PDF document from stream, file and byte array. Also it is available on viewing PDF/A-1B, PDF/X1A and enables to open and read encrypted PDF files Click to know more

page 73