Friday, 24 August 2012 02:43

Split Huge PDF Document by Pages in WPF

PDF Split is always needed by programmers and developers. It is very convenient to split a PDF file to multiple files by using online PDF split tools, you can split PDF in a page range as well as only extract a unique page. However, if you want to split a huge PDF document to hundreds of files, you have to try at least dozens of times, which, undoubtedly, takes too much time. Furthermore, when the network goes slowly, an error is likely to occur, sometimes, the file is reported to be damaged or corrupted. While using Spire.PDF for WPF, you can easily split huge PDF document up to hundreds of pages without any worry of the document safety in your WPF application.

By using Spire.PDF, you can achieve the effect as below:

Split PDF Document

Spire.PDF for WPF, as a WPF PDF component, allows users to create, read, write and manipulate PDF documents without using Adobe Acrobat or any third party component library. As for PDF split task, you can realize it by below methods:

doc.Split(pattern):

When splitting a PDF document to multiple PDF files, each PDF file is made of one page from the original PDF file. Split method works well since it can quickly split your PDF file and there is only one parameter passed to provide a template name of the destination PDF file.

String.Format(pattern, doc.Pages.Count - 1):

"String.Format" method provides great convenience for you to preview an existing file by returning the PDF file name that you want to process. The second parameter String.Format method is used to point out the index item which starts from 0.

The key step of PDF split task only requires four lines of code, before your start your PDF split project, please download Spirel.PDF for WPF first, then you can invoke the key code below to split any PDF you want.

[C#]
        String pattern = "SplitDocument-{0}.pdf";
        doc.Split(pattern);
        String lastPageFileName= String.Format(pattern, doc.Pages.Count - 1);
        doc.Close();
[VB.NET]
	Dim pattern As String = "SplitDocument-{0}.pdf"
	doc.Split(pattern)
	Dim lastPageFileName As String = String.Format(pattern, doc.Pages.Count - 1)
	doc.Close()

Obviously, using this WPF PDF component, PDF can be split absolutely according to your requirements. Enjoy fast speed, high quality and free choices to build your application to split PDF right now.

Thursday, 23 August 2012 06:30

Insert OLE Object in Word in C#, VB.NET

Word OLE (Object Linking and Embedding) object is used to make contents, created in one program, available in Word document. For example, users can insert an Excel worksheet in a Word document.

Both Linked object and Embedded object can be used between Word and other programs. The data of Embedded objects is saved in Word and should be updated manually, while data of Linked object remains as separate file and will be updated when source data is changed.

Spire.Doc for .NET , a professional component to manipulate Word documents with .NET, enables users to insert OLE objects in Word by using C#/VB.NET. This guide will show you how to insert one kind of OLE objects, Linked objects (an Excel Worksheet) in Word.

Users can invoke paragraph.AppendOleObject(string pathToFile, olePicture, OleObjectType) method to insert OLE objects in Word. The parameters, olePicture and OleObjectType are properties of DocOleObject class which is provided by Spire.Doc for .NET.

The following steps present details to insert OLE Objects in Word. The following demonstrate a document before insert the OLE Object into Word, and at the bottom, you can find the result screenshot after inserting. Before starting with the steps, download and install Spire.Doc for .NET on system.

Insert Word OLE Objects

Code Detail:

Step 1: Define a GetExcelImage(string ExcelFile) method to get olePicture. Actually, the olePicture is image of data information in original Excel worksheet. The image is generated from Excel through Spire.XLS for .NET that will be shown in documents after inserting OLE object in Word. Double click this picture and you can get the original worksheet.

[C#]
 
private static Image GetExcelImage(String ExcelFile)
 {
  //Load Excel File
  Workbook workbook = new Workbook();
  workbook.LoadFromFile(ExcelFile);
  Worksheet sheet = workbook.Worksheets[0];

  //Set Image Range
  int lastRow = sheet.LastRow;
  int lastColumn = sheet.LastColumn;
  return workbook.Worksheets[0].SaveToImage(1, 1, lastRow, lastColumn);
}
[VB.NET]
   
Private Shared Function GetExcelImage(ByVal ExcelFile As String) As Image
  'Load Excel File
  Dim workbook As New Workbook()
  workbook.LoadFromFile(ExcelFile)
  Dim sheet As Worksheet = workbook.Worksheets(0)

  'Set Image Range
  Dim lastRow As Integer = sheet.LastRow
  Dim lastColumn As Integer = sheet.LastColumn
  Return workbook.Worksheets(0).SaveToImage(1, 1, lastRow, lastColumn)
End Function
 

Step 2: Insert OLE object. After adding paragraph in Word document, declare a new DocPicture. Then, use GetExcelImage(string ExcelFile) method which is defined in step 1 to get image source and then use picture.LoadImage(Image) method to load this image. Finally, insert OLE objects.

[C#]
       
para = mysec.AddParagraph();
DocPicture picture = new DocPicture(mydoc);
Image image = GetExcelImage(@"E:\work\Documents\ExcelFiles\Customers.xlsx");//Get Image Source
picture.LoadImage(image);//Load Image
DocOleObject obj = para.AppendOleObject(@"E:\work\Documents\ExcelFiles\Customers.xlsx", picture, Spire.Doc.Documents.OleObjectType.ExcelWorksheet);
[VB.NET]
  
'Insert OLE Object
para = mysec.AddParagraph()
Dim picture As New DocPicture(mydoc)
Dim image As Image = GetExcelImage("E:\work\Documents\ExcelFiles\Customers.xlsx") 'Get Image Source
picture.LoadImage(image) 'Load Image
Dim obj As DocOleObject = para.AppendOleObject("E:\work\Documents\ExcelFiles\Customers.xlsx", picture, Spire.Doc.Documents.OleObjectType.ExcelWorksheet)

After this coding, you can run this application and a result will show up as below:

Insert Word OLE Objects

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Thursday, 16 August 2012 01:00

Create PDF Digital Signature in WPF

Digital signature is more advanced and more popular to detect forgery and tampering today compared with traditional handwritten signature. Especially in business world, digital signature becomes an effective method to safeguard and authenticate your documents. As long as a digital signature is created and singed, the document has not been tampered and the recipients can view both the document version history and any changes that were made to it. Now, it is time to see how to create a PDF digital signature via a WPF PDF component Spire.PDF for WPF.

Spire.PDF for WPF, as a PDF component, enables you to create PDF digital signature in a simple way which can not only ensure your data information has not been altered since it was sent but also verify the signer's digital identity. The key procedure only requires six lines of code. Please preview the effective screenshot below, and then, view the key code.

Create Digital Signature

Please feel free to Download Spire.PDF for WPF first before the key code below. In this solution, for constructing one instance of a Spire.Pdf.Sercurity.PdfCertificate class named cert, we reference a certificate file and its file protect password as parameters. Then, cert is applied to create an instance of a PdfSignature class we name it signature. Setting signature “page” parameter allows you to sign the digital signature of any PDF page. And DocumentPermissions, one property of signature, can be set: AllowComments, AllowFormFill and ForbidChanges.

Core Code:

[C#]
String pfxPath = @"..\Data\Demo.pfx";
PdfCertificate cert = new PdfCertificate(pfxPath, "e-iceblue");
PdfSignature signature = new PdfSignature(doc, page, cert, "demo");
signature.ContactInfo = "Harry Hu";
signature.Certificated = true;
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;
[VB.NET]
Dim pfxPath As String = "..\Data\Demo.pfx"
Dim cert As New PdfCertificate(pfxPath, "e-iceblue")
Dim signature As New PdfSignature(doc, page, cert, "demo")
signature.ContactInfo = "Harry Hu"
signature.Certificated = True
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill
Friday, 10 August 2012 06:04

Encrypt PDF for Security in WPF

For PDF security, people are more likely to encrypt PDF file by setting up to two passwords: owner password and user password. The essential difference between these two passwords is that people can fully control the document by owner password, while only can open or have to subject to some restrictions by user password. This section will introduce a solution to easily encrypt your PDF by the two passwords via Spire.PDF for WPF.

Spire.PDF for WPF is a WPF PDF component, which can encrypt your PDF not only by owner password but also by restricting nine permissions when setting user password. In the solution, these two passwords are set by an object of PDFSecurity class which is contained in the namespace Spire.PDFDocument.Security.

Before you start, please feel free to download Spire.PDF for WPF first and encrypt your PDF file by below key steps after loading it.

Step1: Set PDF password size

In this step, three kinds of key size are applicable by the enum Spire.Pdf.Security.PdfEncryptionKeySize. They are: Key128Bit, Key256Bit and Key40Bit. You can choose any of the three according to your own situation.

[C#]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
[VB.NET]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit

Step 2: Secure PDF file by passwords

Owner password and user password are set to encrypt your PDF file. Please make sure that the password size should not be over the key size you set in last step.

[C#]
doc.Security.OwnerPassword = "e-iceblue";
doc.Security.UserPassword = "pdf";
[VB.NET]
doc.Security.OwnerPassword = "e-iceblue"
doc.Security.UserPassword = "pdf"

Step 3: Restrict certain permissions of user password

Nine access permissions of user password can be specified in the step, you can view them as below picture:

Encrypt PDF Document

  • AccessibilityCopyContent: copy accessibility content.
  • AssembleDocument: assemble document permission. (Only for 128 bits key).
  • CopyContent: copy content.
  • Default: default value means users are authorized all permissions.
  • EditAnnotations: add or modify text annotations, fill in interactive form fields.
  • EditContent: edit content.
  • FillFields: fill form fields. (Only for 128 bits key).
  • FullQualityPrint: print document with full quality.
  • Print: print document.

Here, three permissions are authorized: AccessibilityCopyContent, Print and EditAnnotations. Now, see following code:

[C#]
doc.Security.Permissions = PdfPermissionsFlags.AccessibilityCopyContent | PdfPermissionsFlags.Print | PdfPermissionsFlags.EditAnnotations;
[VB.NET]
doc.Security.Permissions = PdfPermissionsFlags. AccessibilityCopyContent Or PdfPermissionsFlags. Print Or PdfPermissionsFlags.EditAnnotations

After you run the project, appears a dialog box in which you need to input password before opening the PDF document. You can look at the effective screenshot below:

Encrypt PDF Document

This section will introduce an easy solution to convert image to PDF in WPF. In my method, image to PDF conversion is just a piece of cake since various image formats such as jpg, png and bmp, even images of gif, tif and ico can be converted to PDF through two key steps for Spire.PDF users.

Spire.PDF for WPF,a professional WPF PDF component, enables your WPF applications to read, write and manipulate PDF document without Adobe Acrobat or any third party component library. As for image to PDF conversion, apart from clearly converting images of different formats to PDF, Spire.PDF for WPF also allows you to directly load your images to PDF files from stream. Please feel free to Download Spire.PDF and give it a try following our programming guide below. The following is a picture which we will convert to PDF. At the bottom of this  article, a target PDF will be presented.

Image to PDF

Now it's time for the key procedure of image to PDF conversion. To realize the key procedure, we need below two steps.

Step 1: Load an image file from system

An image file is required in this step. The image format can be any format among jpg, png, bmp, gif, tif and ico. Here a jpg image is loaded.

[C#]
//Load a jpg image from system
PdfImage image = PdfImage.FromFile(@"..\sky.jpg");
[VB.NET]
'Load a jpg image from system
Dim image As PdfImage = PdfImage.FromFile("..\sky.jpg") 

Step 2: Set the image location and size to fit PDF page

Spire.PDF for WPF contains a namespace “Spire.Pdf.Graphics” in which image size and location are set through four parameters: Width/Height for image size and fitWidth/fitHeight for image location.

[C#]
  //Set image display location and size in PDF
float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
float fitRate = Math.Max(widthFitRate, heightFitRate);
float fitWidth = image.PhysicalDimension.Width / fitRate;
float fitHeight = image.PhysicalDimension.Height / fitRate;
page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);
[VB.NET]
'Set image display location and size in PDF
Dim widthFitRate As Single = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width
Dim heightFitRate As Single = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height
Dim fitRate As Single = Math.Max(widthFitRate, heightFitRate)
Dim fitWidth As Single = image.PhysicalDimension.Width / fitRate
Dim fitHeight As Single = image.PhysicalDimension.Height / fitRate
page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight)

After this coding, run your application, you can find a target PDF as below.

Image to PDF

Apart from Spire.PDF for WPF, Spire.PDF also packs Spire.PDF for .NET and Spire.PDF for Silverlight, which enables you to directly edit PDF in your .NET/Silverlight applications through equally simple method. Click to know more about the other two PDF .NET component and PDF Silverlight component.

Wednesday, 08 August 2012 01:06

Convert Webpage to PDF in WPF

HTML to PDF solution can be quite a few when people search on google. However, most solutions are not proper in use since what you view on webpage is not always completely same with what you get on your PDF. Some information such as dynamic image and anchor text in HTML are easily lost. This section will introduce a simple method to clearly convert HTML to PDF without any cut on WPF platform.

Spire.PDF for WPF, as a professional PDF component, allows you to clearly convert HTML to PDF only by three lines of key code on WPF platform. In the solution, you only need to load HTML file with four parameters:

  • URL, the url of the webpage which will be converted to PDF file.
  • Enable JavaScrpit, indicates whether enables the JavaScript of the webpage.
  • Enable hyperlink, indicates whether enables the hyperlink of the webpage.
  • Auto detect page break, indicates whether splits auto the web page in the result PDF file.

Then, save your html as PDF to file by calling the method PdfDocument.LoadFromHTM. Please preview the result screenshot of the whole project first as prove:

Webpage to PDF

Before demonstrating the code, please feel free to download Spire.PDF and install it on system. Now, you can view the full code below:

[C#]
using Spire.Pdf;

namespace WPFhtmltopdf
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        [STAThread]
        private void button1_Click(object sender, RoutedEventArgs e)
        {

            //Create a new pdf document.
            PdfDocument doc = new PdfDocument();
            //load the webpage 
            String url = "http://msdn.microsoft.com/";
            doc.LoadFromHTML(url, false, true, true);
            //Save html webpage as pdf file.
            doc.SaveToFile("sample.pdf");
            doc.Close();
        }
    }
}
[VB.NET]
Imports Spire.Pdf

Namespace WPFhtmltopdf
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub
		 _
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)

			'Create a new pdf document.
			Dim doc As New PdfDocument()
			'load the webpage 
			Dim url As  = "http://msdn.microsoft.com/"
			doc.LoadFromHTML(url, False, True, True)
			'Save html webpage as pdf file.
			doc.SaveToFile("sample.pdf")
			doc.Close()
		End Sub
	End Class
End Namespace

Obviously, using this WPF PDF component, the webpage is easily converted to PDF. Both text and images are clearly shown in PDF file. Besides, Spire.PDF for WPF is a 100% secure PDF component software. No Malware, No Spyware and No Virus.

Tuesday, 07 August 2012 06:39

Insert Page Break in Word in WPF

Word Page Break is used to start with contents in a new page, which can be inserted anywhere in Word document. Generally speaking, page break can be generated automatically when one page is filled with contents, or users can specify where Microsoft Word positions automatic page break. Also, users can insert manual page breaks in document to keep some paragraphs together in a single page.

Spire.Doc for WPF, a professional WPF component on manipulating Word document, enables users to insert page break in Word with WPF. Users can invoke paragraph.Append(BreakType.PageBreak) method directly to insert page break in Word.

Spire.Doc presents an easy way to insert a page break. Just follow the simple steps below to insert a page break.

The following screenshot presents document before inserting page break.

Download and install Spire.Doc for WPF. Add button in MainWindow and double click this button to use the following code to insert page break with WPF in Word.

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

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load Document
            Document doc = new Document();
            doc.LoadFromFile(@"E:\work\documents\Blues Introduction.docx");

            //Get Paragraph Position
            Section section = doc.Sections[0];
            Paragraph paragraph = section.Paragraphs[1];

            //Insert Page Break
            paragraph.AppendBreak(BreakType.PageBreak);

            //Save and Launch
            doc.SaveToFile("PageBreak.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("PageBreak.docx");
        }
    }
}
[VB.NET]
Imports System.Windows
Imports Spire.Doc
Imports Spire.Doc.Documents

Class MainWindow

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'Load Document
        Dim doc As New Document()
        doc.LoadFromFile("E:\work\documents\Blues Introduction.docx")

        'Get Paragraph Position
        Dim section As Section = doc.Sections(0)
        Dim paragraph As Paragraph = section.Paragraphs(1)

        'Insert Page Break
        paragraph.AppendBreak(BreakType.PageBreak)

        'Save and Launch
        doc.SaveToFile("PageBreak.docx", FileFormat.Docx)
        System.Diagnostics.Process.Start("PageBreak.docx")

    End Sub
End Class

Effective Screenshot:

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Wednesday, 01 August 2012 03:15

Convert Text to PDF in WPF

This section is designed to introduce a simple method to clearly convert text to PDF for WPF. During the text to PDF conversion task, font, font color, line space and other text format also can be quickly set according to your own need via a WPF PDF component Spire.PDF for WPF.

Spire.PDF for WPF will display a solution of two key steps to realize text to PDF task as well as customize text in PDF. Compared with some text to PDF converters, Spire.PDF for WPF not only has the function of convert HTML, text and image to PDF, but also owns the ability to read, write and manipulate PDF document without Adobe Acrobat or any third party component library.

Below screenshot gives you a clear view of the text to PDF conversion effect:

Text to PDF

Please download Spire.PDF for WPF on system. Then, perform your text to PDF by below key steps.

Step1: Read all text information to s string

In this step, you need to read all the text from a text file to a string.

[C#]
string text = File.ReadAllText(@"..\texttopdf.txt");
[VB.NET]
Dim text As String = File.ReadAllText("..\texttopdf.txt")

Step2: Draw string to PDF document with custom layout.

This step allows you to set the text font, font color, text format and position in PDF document at your own will by below code:

[C#]
  PdfPageBase page = section.Pages.Add();
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
            PdfStringFormat format = new PdfStringFormat();
            format.LineSpacing = 20f;
            float pageWidth = page.Canvas.ClientSize.Width;
            PdfBrush brush = PdfBrushes.DarkBlue;
            float y = 30;
            PdfStringLayouter textLayouter = new PdfStringLayouter();
            PdfStringLayoutResult result
                = textLayouter.Layout(text, font, format, new SizeF(pageWidth, 0));
            foreach (LineInfo line in result.Lines)
            {
                page.Canvas.DrawString(line.Text, font, brush, 0, y, format);
                y = y + result.LineHeight;
            }
[VB.NET]
Dim page As PdfPageBase = section.Pages.Add()
	Dim font As New PdfFont(PdfFontFamily.Helvetica, 11)
	Dim format As New PdfStringFormat()
	format.LineSpacing = 20F
	Dim pageWidth As Single = page.Canvas.ClientSize.Width
	Dim brush As PdfBrush = PdfBrushes.DarkBlue
	Dim y As Single = 30
	Dim textLayouter As New PdfStringLayouter()
	Dim result As PdfStringLayoutResult = textLayouter.Layout(text, font, format, New SizeF(pageWidth, 0))

	For Each line As LineInfo In result.Lines
		page.Canvas.DrawString(line.Text, font, brush, 0, y, format)
		y = y + result.LineHeight
	Next

Now that is all the core codes for draw text in PDF.  Apart from converting text to PDF, Spire.PDF for WPF also can extract PDF text.

Tuesday, 31 July 2012 03:24

Insert Text Watermark to Word in WPF

Word watermark can be text or image, which appears behind document contents and will not influence integrity of document body. It often adds interest or identifies document status, for example, marking document as private or important. This is the guide you are looking for about how to insert text watermark in Word with WPF.

Spire.Doc for WPF, a professional WPF component on manipulating Word document, enables users to insert text watermark in Word document and set format for this watermark. Comparing with “Insert Watermark” Command in Microsoft Word, Spire.Doc for WPF provides a Spire.Doc.TextWatermark class. Firstly initialize a new instance of Textwatermark with TextWatermark TXTWatermark = new TextWatermark() and then set text watermark as document watermark type by code:document.Watermark = TXTWatermark.

Besides, TextWatermark class includes several parameters for watermark formatting setting, including text, font style, layout etc. The following screenshot is the document without watermark. After the code below, you will find a result screenshot with text watermark being adding at the bottom of the page.

Word Text Watermark

Download Spire.Doc for WPF and install it on your system. After adding button in MainWindow, double click this button to use the following code to insert text watermark in Word with WPF.

[C#]
using System.Windows;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\Documents\New Zealand.docx");

            //Insert Text Watermark and Set Format
            TextWatermark TXTWatermark = new TextWatermark();
            TXTWatermark.Text = "NZ Brief Introduction ";
            TXTWatermark.FontSize = 45;
            TXTWatermark.FontName = "Broadway BT";
            TXTWatermark.Layout = WatermarkLayout.Diagonal;
            TXTWatermark.Color = Color.Purple;
            document.Watermark = TXTWatermark;

            //Save and Launch
            document.SaveToFile("TXTWatermark.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("TXTWatermark.docx");
        }
    }
}
[VB.NET]
Imports System.Windows
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Class MainWindow

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'Load Document
        Dim document As New Document()
        document.LoadFromFile("E:\work\Documents\New Zealand.docx")

        'Insert Text Watermark and Set Format
        Dim TXTWatermark As New TextWatermark()
        TXTWatermark.Text = "NZ Brief Introduction"
        TXTWatermark.FontSize = 45
        TXTWatermark.FontName = "Broadway BT"
        TXTWatermark.Layout = WatermarkLayout.Diagonal
        TXTWatermark.Color = Color.Purple
        document.Watermark = TXTWatermark

        'Save and Launch
        document.SaveToFile("TXTWatermark.docx", FileFormat.Docx)
        System.Diagnostics.Process.Start("TXTWatermark.docx")

    End Sub
End Class

After running, you can get the result as following:

Word Text Watermark

Spire.Doc is a Microsoft Word component which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF.NET and Silverlight.

Setting Excel header and footer to add information to a spreadsheet is a pretty attractive choice. This is the solution for how to set Excel header and footer in C#, VB.NET. Within this solution, you can either set Excel header and footer in C#, VB.NET at design mode or runtime mode.

Headers and Footers are the lines of text that are displayed below the top margin or above the bottom margin respectively. They can be used to display any kind of useful information on the pages like page number, author name, topic name or date/time etc.

Spire.XLS for .NET allows adding headers and footer to the worksheets and setting them at runtime. At the same time, you can also set headers and footers manually in the pre-designed file for printing and then load it as a template. For example, you can use Microsoft Excel as a GUI tool to set headers and footers easily to reduce your efforts and development time and then upload it by using Spire.XLS for .NET. The image below displays the effect of setting Excel header and footer in C#, VB.NET. You can also freely download Spire.XLS for .NET and have a trial.

Add Excel Header and Footer

The next part is the code for setting Excel header and footer in C#, VB.NET.

[C#]
using Spire.Xls;

namespace HeaderAndFooterForXls
{
    class Program
    {
        static void Main(string[] args)
        {
            //create your excel document           
            Workbook myworkbk = new Workbook();
            //Gets first worksheet
            Worksheet mysht = myworkbk.Worksheets[0];
            //Writes hello world to A1
            mysht.Range["A1"].Text = "Hello ";
            //set header&footer
            mysht.PageSetup.LeftHeader = "Header Footer Sample by E-iceblue Co.,Ltd";        
            mysht.PageSetup.CenterFooter = "footer";
            //Save workbook and preview it
            myworkbk.SaveToFile(@"..\Sample.xls",ExcelVersion.Version97to2003);                     
            System.Diagnostics.Process.Start(@"..\Sample.xls");
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace HeaderAndFooterForXls
	Class Program
		Private Shared Sub Main(args As String())
			'create your excel document           
			Dim myworkbk As New Workbook()
			'Gets first worksheet
			Dim mysht As Worksheet = myworkbk.Worksheets(0)
			'Writes hello world to A1
			mysht.Range("A1").Text = "Hello "
			'set header&footer
			mysht.PageSetup.LeftHeader = "Header Footer Sample by E-iceblue Co.,Ltd"
			mysht.PageSetup.CenterFooter = "footer"
			'Save workbook and preview it
			myworkbk.SaveToFile("..\Sample.xls",ExcelVersion.Version97to2003)
			System.Diagnostics.Process.Start("..\Sample.xls")
		End Sub
	End Class
End Namespace

As for headers and footers manually in the pre-designed file, please refer how to use Excel template in C#, VB.NET.

Spire.XLS for .NET is a professional Excel component which enables developers/programmers to fast generate, read, write and modify Excel document for .NET. It supports C#, VB.NET, ASP.NET, ASP.NET MVC.