How to Set TopText of Barcode in WinForm

2014-11-05 05:58:46 Written by Koohji

A barcode is a small image of lines and spaces that is often used in a store to reflect the description and price of a product, moreover, barcodes can be used in many other aspects in our daily life, such as tickets, medicine prescriptions, library books. In this article, I'll introduce you a way to add extra information in TopText of a barcode using Spire.Barcode in WinForm.

By default, 'E-iceblue' will be shown as TopText in a barcode if you don't request a key to remove it. Click here to see how to remove 'E-iceblue' logo in barcode. In this sample, more than one line of text will be added in TopText to replace 'E-iceblue'. Let's see detailed steps.

Step 1: Add Spire.Barcode controls to Visual Studio Toolbox.

Step 2: Create a Windows Forms project. Drag 'BarCodeControl' to your Form1. Here I changed the barcode type as EAN13.

How to Set TopText of Barcode in WinForm

Step 3: Double click 'button1' to write code. Customized TopText can be saved in BarCodeControl.TopText string.

string title = "Title: xxx" + Environment.NewLine;
string subject = "Subject: Information Technology" + Environment.NewLine;
string date = "Date: " + DateTime.Now.ToString() + Environment.NewLine;
string isbn = "ISBN: 1234567890005";
this.barCodeControl1.TopText = title + date + subject + isbn;

Step 4: Run the sample code and click 'button1' to get the new barcode. In addition, you can call BarCodeControl.SaveToFile() method to save the barcode as an image.

How to Set TopText of Barcode in WinForm

Full Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace SetTopText
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string title = "Title: xxx" + Environment.NewLine;
            string date = "Date: " + DateTime.Now.ToString() + Environment.NewLine;
            string subject = "Subject: Information Technology" + Environment.NewLine;
            string isbn = "ISBN: 1234567890005";
            this.barCodeControl1.TopText = title + date + subject + isbn;

        }
    }
}

In some case, we need make some modifications in an existing table but don't want destroy the original data, so we would like to copy the existing table then make some changes in the new table. How could we get the copied table? The easiest method is clone. There would introduce a solution to copy table and modify some data then insert the new table after original table via Spire.Doc.

Spire.Doc for .NET, a stand-alone .NET Word component, provides a method, Table.clone() to allow users to copy an existing table.

The main steps of the solution:

Firstly: load the word document with a table.

Document doc = new Document();
doc.LoadFromFile(@"CopyTable.doc");

The original document effect screenshot:

Insert an existing Table by cloning

Secondly: extract the existing table and call the table.clone () method to copy it.

Section se = doc.Sections[0];
Table original_Table =(Table) se.Tables[0];
Table copied_Table = original_Table.Clone();

Thirdly: extract the last row then traversal its cells to modify data.

string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
//get the last row of copied table
TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
//change lastRow data.
lastRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Gray;
for (int i = 0; i < lastRow.Cells.Count; i++)
    {
    lastRow.Cells[i].Paragraphs[0].Text = st[i];       
     }

Finally: call Section. tables.add() method to add the copied table in section and save this document.

se.Tables.Add(copied_Table);
doc.SaveToFile("result.doc", FileFormat.Doc);
The result document effect screenshot:

Insert an existing Table by cloning

Full code:

using Spire.Doc;
using System.Drawing;

namespace InsertingaAnExistingTable
{
    class Program
    {
        static void Main(string[] args)
        { 
//load a word document
            Document doc = new Document();
            doc.LoadFromFile(@"CopyTable.doc");

// extract the existing table
            Section se = doc.Sections[0];
            Table original_Table =(Table) se.Tables[0];

// copy the existing table to copied_Table via Table.clone()
            Table copied_Table = original_Table.Clone();
string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
            //get the last row of table
            TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
            //change last row data.
            lastRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Gray;
            for (int i = 0; i < lastRow.Cells.Count; i++)
            {
                lastRow.Cells[i].Paragraphs[0].Text = st[i];
            }
// add copied_Table in section
            se.Tables.Add(copied_Table);
            doc.SaveToFile("result.doc", FileFormat.Doc);     
        }
    }
}

Convert Word to Image in WPF

2014-10-31 06:13:46 Written by Koohji

In some circumstances, we may need to convert or save Word documents as pictures. For one reason, a picture is difficult to edit; for another, compared with Word, pictures are much easier to be published for browsing. This article is aimed to explore how we can convert .doc/.docx to popular image formats such as Jpg, Png, Gif and Bmp in WPF using Spire.Doc.

Spire.Doc for WPF, as a professional Word component, provides a plenty of useful methods to manipulate Word documents in your WPF applications. Using Spire.Doc, developers are able to export Word documents as images with high quality. Here comes the method:

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

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
        }

Step 2: Initialize a new instance of Spire.Doc.Document class and load the sample Word file.

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

Step 3: To convert Word to image in WPF, we need firstly save Word as BitmapSource by calling the method Document.SaveAsImage(ImageType type), then convert BitmapSource to Bitmap, then save the Bitmap as image with a specified format using Image.Save(). Here, I saved Bitmap as .Png.

       BitmapSource[] bss = doc.SaveToImages(ImageType.Bitmap);
            for (int i = 0; i < bss.Length; i++)
            {
                SourceToBitmap(bss[i]).Save(string.Format("img-{0}.png", i));
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {        

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

Output of the first page:

Convert Word to Image in WPF

Entire Code:

using Spire.Doc;
using Spire.Doc.Documents;

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document doc = new Document("sample.docx", FileFormat.Docx2010);
            BitmapSource[] bss = doc.SaveToImages(ImageType.Bitmap);
            for (int i = 0; i < bss.Length; i++)
            {
                SourceToBitmap(bss[i]).Save(string.Format("img-{0}.png", i));
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {        

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

Excel header and footer give additional information of an Excel sheet, such as the page number, author name, topic name and date etc. With the help of Spire.XLS, developers can easily add text header and footer into an excel spreadsheet. Sometimes, the font and size of the header and footer may be different with the font in the excel documents, and it makes the document in disorder. This article will demonstrate how to change the font and size for the text on excel header and footer.

Firstly, check the original font and size on Excel header and footer:

How to change the font and size for Excel header and footer in C#

By using Spire.XLS, we can easily set the new size and font for the header and footer text. Here comes to the steps of how to change the font and size for excel header and footer:

Step 1: Create an excel document and load the Excel with header and footer from file:

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

Step 2: Gets the first worksheet in the Excel file

Worksheet sheet = workbook.Worksheets[0];

Step 3: Set the new font and size for the header and footer

string text = sheet.PageSetup.LeftHeader;
//"Arial Unicode MS" is font name, "18" is font size
text = "&\"Arial Unicode MS\"&18 Header Footer Sample by Spire.XLS ";
sheet.PageSetup.LeftHeader = text;
sheet.PageSetup.RightFooter = text;

Step 4: Save the document to file and preview it

workbook.SaveToFile(@"..\Result.xlsx",ExcelVersion.Version2010);
System.Diagnostics.Process.Start(@"..\Result.xlsx");

Effective screenshot after changing the font and size for the header:

How to change the font and size for Excel header and footer in C#

Full codes:

using Spire.Xls;
namespace Changefontforheaderfooter
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            string text = sheet.PageSetup.LeftHeader;
            //"Arial Unicode MS" is font name, "18" is font size
            text = "&\"Arial Unicode MS\"&18 Header Footer Sample by Spire.XLS ";
            sheet.PageSetup.LeftHeader = text;
            sheet.PageSetup.RightFooter = text;
            //Save workbook and preview it
            workbook.SaveToFile(@"..\Result.xlsx",ExcelVersion.Version2010);
            System.Diagnostics.Process.Start(@"..\Result.xlsx");
        }
    }
}

Every time we create a plain table in a Word document, we may want to change the style of the table so as to make it more vivid and attractive. In our previous article, we have demonstrated how to set Word table formatting with custom style. However, if we do not have much time to do so, we can apply built-in table styles to own a better appearance within a few minutes. This article focuses on how to apply built-in table styles to existing Word tables using Spire.Doc with C#, VB.NET.

In the class of Spire.Doc.Table, it provides Table.ApplyStyle() method which enable us to easily change the layout of tables with default styles. As is shown below, here is a Word document that contains two plain tables in the first page. Let us see how we can format the table style with several lines of code.

Test File:

Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Code Snippet:

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

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

Step 2: Get the two tables from document.

Section section = doc.Sections[0];
Table table1 = section.Tables[0] as Table;
Table table2 = section.Tables[1] as Table;

Step 3: Apply tables with built-in table styles separately.

table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);

Step 4: Save the file.

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

Output:

Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Entire Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
namespace ApplyTableStyles
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document("table.docx", FileFormat.Docx2010);
            Section section = doc.Sections[0];
            Table table1 = section.Tables[0] as Table;
            Table table2 = section.Tables[1] as Table;

            table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
            table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);
            doc.SaveToFile("result.docx", FileFormat.Docx);

        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Namespace ApplyTableStyles
	Class Program

		Private Shared Sub Main(args As String())

			Dim doc As New Document("table.docx", FileFormat.Docx2010)
			Dim section As Section = doc.Sections(0)
			Dim table1 As Table = TryCast(section.Tables(0), Table)
			Dim table2 As Table = TryCast(section.Tables(1), Table)

			table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2)
			table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1)
			doc.SaveToFile("result.docx", FileFormat.Docx)

		End Sub
	End Class
End Namespace

Spire.PDFViewer FAQ

2014-10-23 08:56:00 Written by Koohji

Building Error

Q: When I drag and drop the PdfDocumentViewer control on the winform application and build the project, I get an error like this:

What should I do?

A: To get rid of this error, please delete "licenses.licx" file in Properties folder and rebuild the project.

Set Excel View Mode in C#, VB.NET

2014-10-23 08:33:17 Written by Koohji

Users can change the Excel view mode according to reading habit. By default, there are several view modes we can choose, including Normal View, Page Layout View, Page Break Preview, Full Screen View and Custom Views. Besides, Microsoft Excel also enables us to zoom in/out the document to a specified level. In this article, I'll make a brief introduction about how to set Excel view mode using Spire.XLS in C# and VB.NET.

In this sample, the Excel view mode will be set as Page Break Preview with zoom in 80 percent. Download the Spire.XLS for .NET, add the Spire.Xls.dll as a reference into assemblies, then we can use the following code snippet to achieve this end goal.

Detailed Steps

Step 1: Create a new instance of Workbook and load the sample file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010);

Step 2: Get the first the worksheet from the Excel workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Set view mode as Page Break Preview and Zoom in the sheet with 80 percent.

sheet.ViewMode = ViewMode.Preview;
sheet.ZoomScalePageBreakView = 80;

Step 4: Save the changes to workbook in a new file.

workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);

Output:

Set Excel View Mode in C#, VB.NET

Full Code:

[C#]
using Spire.Xls;
namespace SetExcelViewMode
{
    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010);
            Worksheet sheet = workbook.Worksheets[0];
            ////Page Layout
            //sheet.ViewMode = ViewMode.Layout;
            //sheet.ZoomScalePageLayoutView = 80;
            ////Normal View(Default)
            //sheet.ViewMode = ViewMode.Normal;
            //sheet.ZoomScaleNormal = 80;
            //Preview
            sheet.ViewMode = ViewMode.Preview;
            sheet.ZoomScalePageBreakView = 80;

            workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);

        }

    }
}
[VB.NET]
Imports Spire.Xls
Namespace SetExcelViewMode
	Class Program

		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010)
			Dim sheet As Worksheet = workbook.Worksheets(0)
			'''/Page Layout
			'sheet.ViewMode = ViewMode.Layout;
			'sheet.ZoomScalePageLayoutView = 80;
			'''/Normal View(Default)
			'sheet.ViewMode = ViewMode.Normal;
			'sheet.ZoomScaleNormal = 80;
			'Preview
			sheet.ViewMode = ViewMode.Preview
			sheet.ZoomScalePageBreakView = 80

			workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010)

		End Sub

	End Class
End Namespace

C#: Remove Headers or Footers in Word

2024-10-22 09:04:00 Written by Koohji

If the headers or footers in a Word document contains unnecessary information, such as outdated version numbers, redundant company logos, or incorrect author names, removing them can make the document look more professional and concise. In this article, you will learn how to remove headers or footers in Word in C# 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

Remove Headers in Word in C#

Spire.Doc for .NET supports getting different headers in the first pages, odd pages, and even pages, and then delete all of them through the HeaderFooter.ChildObjects.Clear() method. The following are the detailed steps:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Iterate through all paragraphs in the section, and then all child objects in each paragraph.
  • Get the headers for the first, odd, and even pages using Section.HeadersFooters[HeaderFooterType hfType] property, and then delete them using HeaderFooter.ChildObjects.Clear() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

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

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

            //Iterate through all paragraphs in the section
            foreach (Paragraph para in section.Paragraphs)
            {
                //Iterate through all child objects in each paragraph
                foreach (DocumentObject obj in para.ChildObjects)
                {
                    //Delete header in the first page
                    HeaderFooter header;
                    header = section.HeadersFooters[HeaderFooterType.HeaderFirstPage];
                    if (header != null)
                        header.ChildObjects.Clear();

                    //Delete headers in the odd pages
                    header = section.HeadersFooters[HeaderFooterType.HeaderOdd];
                    if (header != null)
                        header.ChildObjects.Clear();

                    //Delete headers in the even pages
                    header = section.HeadersFooters[HeaderFooterType.HeaderEven];
                    if (header != null)
                        header.ChildObjects.Clear();
                }
            }

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

C#: Remove Headers or Footers in Word

Remove Footers in Word in C#

Deleting footers is similar to that of deleting headers, you can also get the footers on different pages first and then delete them at once. The following are the detailed steps:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Iterate through all paragraphs in the section, and then all child objects in each paragraph.
  • Get the footers for the first, odd, and even pages using Section.HeadersFooters[HeaderFooterType hfType] property, and then delete them using HeaderFooter.ChildObjects.Clear() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

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

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

            //Iterate through all paragraphs in the section
            foreach (Paragraph para in section.Paragraphs)
            {
                //Iterate through all child objects in each paragraph
                foreach (DocumentObject obj in para.ChildObjects)
                {
                    //Delete footer in the first page
                    HeaderFooter footer;
                    footer = section.HeadersFooters[HeaderFooterType.FooterFirstPage];
                    if (footer != null)
                        footer.ChildObjects.Clear();

                    //Delete footer in the odd page
                    footer = section.HeadersFooters[HeaderFooterType.FooterOdd];
                    if (footer != null)
                        footer.ChildObjects.Clear();

                    //Delete footer in the even page
                    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
                    if (footer != null)
                        footer.ChildObjects.Clear();
                }
            }

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

C#: Remove Headers or Footers 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.

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

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

Get information of pagination in Excel document

The main steps of the solution are:

Step 1: Create and load an excel document.

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

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

List> pageInfoList = book.GetSplitPageInfo();

Get information of pagination in Excel document

The full code:

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

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

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

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

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

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

End Module

Why we convert PDF to image?

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

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

How to convert PDF to image in WPF?

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

Detailed steps:

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

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
}

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

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

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

               BitmapSource source;
            Bitmap bmp;

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

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

Output of the first page:

Convert PDF to Image with High Quality in WPF

Full code:

[C#]
using Spire.Pdf;

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

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

            BitmapSource source;
            Bitmap bmp;

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

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

    }
}
page 56