Wednesday, 06 July 2011 03:26

Draw Circles in PDF in C#/VB.NET

Circles can be defined as the curves traced out by points that move so that its distance from a given point is constant. They are also look as special ellipses in which the two foci are coincident and the eccentricity is “0”. Whatever they are, they are indispensable in PDF document. This section will introduce a solution to draw circles and set their size and position in PDF file via a .NET PDF component Spire.PDF for .NET in C#, VB.NET.

When we draw circles in PDF, we only need to call one method in Spire.PDF: Spire.Pdf.PdfPageBase.Canvas.DrawPie(PdfPen pen, float x, float y, float width, float height, float startAngle, float sweepAngle); Here there are seven parameters in this method. The first one is the class Spire.Pdf.Graphics.PdfPen which can define the color and the outline of the circle. If we change this parameter to be another class Spire.Pdf.Graphics.PdfBrush, we can easily fill the circle with a certain color. The second and third parameters determine the exact distance between the PDF margin and the circle. "float x" decides the distance of left margin with circle, while "float y" means the distance between the top margin with the circle. By setting the fourth and fifth parameters, we can decide the circle width and height. The last two parameters are the start angle and sweep angle when drawing circles. Now please view the circles in PDF as below picture:

Draw Circles in PDF

Here we can quickly download Spire.PDF for .NET . After adding Spire.Pdf dll in the download Bin folder, we can draw circles in PDF file via Spire.PDF by below code.

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

namespace pdf_circles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            // Create one page
            PdfPageBase page = doc.Pages.Add();
            //save graphics state
            PdfGraphicsState state = page.Canvas.Save();
            PdfPen pen = new PdfPen(Color.Red, 1f);
            PdfPen pen1 = new PdfPen(Color.GreenYellow, 2f);
            PdfBrush brush = new PdfSolidBrush(Color.DeepSkyBlue);
            page.Canvas.DrawPie(pen, 30, 30, 80, 90, 360, 360);
            page.Canvas.DrawPie(brush, 150, 30, 100, 90, 360, 360);
            page.Canvas.DrawPie(pen1,290, 30, 70, 90, 360, 360);
            //restor graphics
            page.Canvas.Restore(state);
            doc.SaveToFile("Circles.pdf");
            System.Diagnostics.Process.Start("Circles.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace pdf_circles
	Class Program
		Private Shared Sub Main(args As String())
			'Create a pdf document.
			Dim doc As New PdfDocument()
			' Create one page
			Dim page As PdfPageBase = doc.Pages.Add()
			'save graphics state
			Dim state As PdfGraphicsState = page.Canvas.Save()
			Dim pen As New PdfPen(Color.Red, 1F)
			Dim pen1 As New PdfPen(Color.GreenYellow, 2F)
			Dim brush As PdfBrush = New PdfSolidBrush(Color.DeepSkyBlue)
			page.Canvas.DrawPie(pen, 30, 30, 80, 90, 360, _
				360)
			page.Canvas.DrawPie(brush, 150, 30, 100, 90, 360, _
				360)
			page.Canvas.DrawPie(pen1, 290, 30, 70, 90, 360, _
				360)
			'restor graphics
			page.Canvas.Restore(state)
			doc.SaveToFile("Circles.pdf")
			System.Diagnostics.Process.Start("Circles.pdf")
		End Sub
	End Class
End Namespace

Spire.PDF for .NET is a PDF component that enables users to draw different kinds of shapes in PDF document in C#, VB.NET.

Tuesday, 05 July 2011 06:11

Draw Rectangles in PDF in C#/VB.NET

In Euclidean plane geometry, a rectangle is any quadrilateral with four right angles. The term "oblong" is occasionally used to refer to a non-square rectangle. A rectangle with vertices ABCD would be denoted as ABCD. It’s simple for people to draw rectangles in paper. While how about drawing rectangles in PDF document? This section will show you the exact answer. This section will introduce a solution to draw rectangles and set the size and position of rectangles in PDF via a .NET PDF component Spire.PDF for .NET with C#, VB.NET.

In Spire.PDF, there are two classes: Spire.Pdf.Graphics.PdfPen and Spire.Pdf.Granphics.PdfBrush. By using the first class, we can set the color and decide the outline of the PDF rectangle. While the second class can quickly help us fill the rectangles with a color we want. Now let us see this method: Spire.Pdf.PdfPageBase.Canvas.DrawRectangle(PdfPen pen, RectangleF rectangle); There are two parameters passed. One is the PdfPen which I referred above. The other represents the location and size of a rectangle. By calling this method, we can draw rectangles and set their size and position very quickly. Now let us view the rectangles as below picture:

Draw Rectangles in PDF

Here we can download Spire.PDF for .NET and install it on system. After adding Spire.Pdf dll, we can draw rectangle in our PDF document as below code:

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

namespace PDF_rectangles
{
    class Program
    {
        static void Main(string[] args)
        {   
            //create a PDF 
            PdfDocument pdfDoc = new PdfDocument();
            PdfPageBase page = pdfDoc.Pages.Add();
            //save graphics state
            PdfGraphicsState state = page.Canvas.Save();
            //draw rectangles
            PdfPen pen = new PdfPen(Color.ForestGreen, 0.1f);
            PdfPen pen1 = new PdfPen(Color.Red, 3f);
            PdfBrush brush = new PdfSolidBrush(Color.Orange);
            page.Canvas.DrawRectangle(pen, new Rectangle(new Point(2, 7), new Size(120, 120)));
            page.Canvas.DrawRectangle(pen1, new Rectangle(new Point(350, 7), new Size(160, 120)));
            page.Canvas.DrawRectangle(brush, new RectangleF(new Point(158, 7), new SizeF(160, 120)));
            //restor graphics
            page.Canvas.Restore(state);
            pdfDoc.SaveToFile("Rectangles.pdf");
            System.Diagnostics.Process.Start("Rectangles.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace PDF_rectangles
	Class Program
		Private Shared Sub Main(args As String())
			'create a PDF 
			Dim pdfDoc As New PdfDocument()
			Dim page As PdfPageBase = pdfDoc.Pages.Add()
			'save graphics state
			Dim state As PdfGraphicsState = page.Canvas.Save()
			'draw rectangles
			Dim pen As New PdfPen(Color.ForestGreen, 0.1F)
			Dim pen1 As New PdfPen(Color.Red, 3F)
			Dim brush As PdfBrush = New PdfSolidBrush(Color.Orange)
			page.Canvas.DrawRectangle(pen, New Rectangle(New Point(2, 7), New Size(120, 120)))
			page.Canvas.DrawRectangle(pen1, New Rectangle(New Point(350, 7), New Size(160, 120)))
			page.Canvas.DrawRectangle(brush, New RectangleF(New Point(158, 7), New SizeF(160, 120)))
			'restor graphics
			page.Canvas.Restore(state)
			pdfDoc.SaveToFile("Rectangles.pdf")
			System.Diagnostics.Process.Start("Rectangles.pdf")
		End Sub
	End Class
End Namespace

Spire.PDF for .NET is a .NET PDF component that can draw different kinds of shapes in PDF document such as Circles, Arcs. Ellipse and Five-pointed Star.

As PDF documents become increasingly popular in business, ensuring their authenticity has become a key concern. Signing PDFs with a certificate-based signature can protect the content and also let others know who signed or approved the document. In this article, you will learn how to digitally sign PDF with an invisible or a visible signature, and how to remove digital signatures from PDF by 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 DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Add an Invisible Digital Signature to PDF

The following are the steps to add an invisible digital signature to PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load a pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object based on the certificate.
  • Set the document permissions through the PdfSignature object.
  • Save the document to another PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;

namespace AddInvisibleSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a sample PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Load the certificate 
            PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

            //Create a PdfSignature object 
            PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
          
            //Set the document permission to forbid changes but allow form fill
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;

            //Save to another PDF file 
            doc.SaveToFile("InvisibleSignature.pdf");
            doc.Close();
        }
    }
}

C#/VB.NET: Add or Remove Digital Signatures in PDF

Add a Visible Digital Signature to PDF

The following are the steps to add a visible digital signature to PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load a pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object and specify its position and size on the document.
  • Set the signature details including date, name, location, reason, handwritten signature image, and document permissions.
  • Save the document to another PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Graphics;

namespace AddVisibleSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a sample PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Load the certificate 
            PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

            //Create a PdfSignature object and specify its position and size 
            PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
            RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
            signature.Bounds = rectangleF;
            signature.Certificated = true;

            //Set the graphics mode to ImageAndSignDetail
            signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;

            //Set the signature content 
            signature.NameLabel = "Signer:";
            signature.Name = "Gary";
            signature.ContactInfoLabel = "Phone:";
            signature.ContactInfo = "0123456";
            signature.DateLabel = "Date:";
            signature.Date = DateTime.Now;
            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo = "USA";
            signature.ReasonLabel = "Reason:";
            signature.Reason = "I am the author";
            signature.DistinguishedNameLabel = "DN:";
            signature.DistinguishedName = signature.Certificate.IssuerName.Name;

            //Set the signature image source
            signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");

            //Set the signature font 
            signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));

            //Set the document permission to forbid changes but allow form fill
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;

            //Save to file 
            doc.SaveToFile("VisiableSignature.pdf");
            doc.Close();
        }
    }
}

C#/VB.NET: Add or Remove Digital Signatures in PDF

Remove Digital Signatures from PDF

The following are the steps to remove digital signatures from PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Get form widgets from the document through PdfDocument.Form property.
  • Loop through the widgets and determine if a specific widget is a PdfSignatureFieldWidget.
  • Remove the signature widget using PdfFieldCollection.RemoveAt() method.
  • Save the document to another PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Widget;

namespace RemoveSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisiableSignature.pdf");

            //Get form widgets from the document
            PdfFormWidget widgets = doc.Form as PdfFormWidget;

            //Loop through the widgets
            for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
            {
                //Get the specific widget
                PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;

                //Determine if the widget is a PdfSignatureFieldWidget
                if (widget is PdfSignatureFieldWidget)
                {
                    //Remove the widget
                    widgets.FieldsWidget.RemoveAt(i);
                }
            }

            //Save the document to another PDF file
            doc.SaveToFile("RemoveSignatures.pdf");
        }
    }
}

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.

Monday, 04 July 2011 08:19

Encrypt PDF Document in C#/VB.NET

Encrypting PDF is a way people commonly used to protect PDF. Whether for a company or for individual, using PDF encryption to place some certain restrictions is indispensable. In order to make the PDF document available to read but unable to modify by unauthorized users, two passwords are required for an encrypted PDF document: owner password and user password. This section will particularly introduce a simple solution to quickly encrypt PDF with C#, VB.NET via Spire.PDF for .NET.

Spire.PDF for .NET as a .NET PDF component, can encrypt your PDF by owner and user password. Owner password is provided to fully access to PDF file such as reset password and restrictions. While user password allows users to open the document as well as subject to the restrictions placed by owner.

In the encryption solution, an object of the PDFSecurity class which is included in the namespace Spire.PDFDocument.Security is used to set the owner and user password. Please feel free to download Spire.PDF for .NET and load your PDF file and then protect it.

Protect PDF by setting password and specify document restrictions.

Step 1: Set PDF key size by the enum."Spire.Pdf.Security.PdfEncryptionKeySize".Three kinds of key size are available here: Key128Bit, Key256Bit and Key40Bit, you can use any one among the three.

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

Step 2: Encrypt PDF file by setting owner and user password. The password size you set should not be over the key size.

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

Step 3: Specify access restrictions of user password. There are nine permissions are available in the solution. You can see them as below picture.

Encrypt PDF Document

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

After running your project, you will be requested a password when you open this encrypted PDF file. Please look at the effective screenshot below:

Encrypt PDF Document

Friday, 01 July 2011 02:51

Marker Designer

Introduction

A Marker Designer represents a single data point or value that gives a mean to Spire.XLS to place relevant data into different cells of the worksheet in a workbook. We make use of Designer spreadsheets in which we write marker designers into different cells. Normally a marker designer consists of DataSource and a Field Name and starts with "&=". The DataSource can be a DataSet, DataTable, DataView or an Object variable etc. You can also make use of dynamic formulas that allows you to insert MS Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. Moreover, you may calculate totals and sub totals of any data field too.

Marker designer is a way to let Spire.XLS know that what information you wish to place in an Excel designer spreadsheet. Marker designers allow you to create templates that contain only relevant information and are formatted to meet your needs.

Designer Spreadsheet and Marker Designers

Designer spreadsheets are standard Excel files that contain the visual formatting, formulas and marker designers. They can contain marker designers that reference one or more data sources such as information from a project and information for related contacts. Marker designers are written into cells where you want information to be filled in.

All marker designers start with "&=", without the quotes. An example of a data marker is &=Party.FullName. If the data marker results in more than one item, i.e. row then following rows will be moved down automatically to make room for all of the new information. Thus sub-totals and totals can be placed on the following row after the data marker to make calculations based on inserted data. In order to make calculations on the rows that are inserted, you must use Dynamic Formulas.

Marker designers consist of the Data Source and Field Name parts for most information. Special information may also be passed with variables and variable arrays. Variables always fill only one cell whereas variable arrays may fill several ones. You may only use one data marker per cell. Unused marker designers will be removed.

Marker designer may also contain parameters. Parameters allow you to modify how the information will be laid out. They are appended to the end of marker designer in parenthesis as a comma separated list.

Marker designer Options

&=DataSource.FieldName 
&=[Data Source].[Field Name] 
&=VariableName

Formulas

Formulas allow you to insert Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. And they can repeat for each inserted row or use only the cell where the data marker is placed for it.

If value of a cell referred to other cells, such as (copy:rc6), it means the value of the cell will be referred by cells of column 6. Multiple refer can be used like this: (copy:rc5,copy:rc7).

Note: Separate them with comma

Cell "G6" contains the formula = D6*E6, cell "G7" contains = D7*E7 and cell "G8" contains = D8*E8, etc.

The following illustrates a repeating dynamic formula and the resulting Excel worksheet.

Excel Marker Designer

Result:

Excel Marker Designer

Sum and Subtotal

Below is showing you how to use these 2 formulas:

Excel Marker Designer

Result:

Excel Marker Designer

Code:

          Workbook workbook = new Workbook();

            workbook.LoadFromFile(@"..\..\..\..\..\..\Data\MarkerDesignerSample1.xls");
			DataTable dt = (DataTable)dataGrid1.DataSource;

			Worksheet sheet = workbook.Worksheets[0];
            //fill parameter
            workbook.MarkerDesigner.AddParameter("Variable1", 1234.5678);
            //fill DataTable
			workbook.MarkerDesigner.AddDataTable("Country",dt);
			workbook.MarkerDesigner.Apply();

            //AutoFit
			sheet.AllocatedRange.AutoFitRows();
			sheet.AllocatedRange.AutoFitColumns();

			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);

Marker Designer Full Demo

Friday, 24 June 2011 06:06

Add Header in PDF with C#/VB.NET

PDF header presents consistent information of a PDF document. It can be automatic page number, a date, a section title, an icon or an image. Whatever it is, it is an important part for a PDF file. This article will introduce how to add a header when programmatically creating a PDF document from scratch.

You can add both text and image in your PDF header by using Spire.PDF for .NET. In order to display the header content appropriately, you can also set text format and image size. The picture below shows the output after adding header in PDF:

Add Header in PDF with C#, VB.NET

Main Steps:

Step 1: Define a custom function CreateHeaderTemplate() to create a page template element that servers as header, and return a PdfPageDocumentElement object.

In the code below, we first initialize a page template object that can be used as header, then call DrawString() method, DrawImage() method and DrawLine() method to insert text,image and line into the header space.

static PdfPageTemplateElement CreateHeaderTemplate(PdfDocument doc, PdfMargins margins)
{
    //get page size
    SizeF pageSize = doc.PageSettings.Size;

    //create a PdfPageTemplateElement object as header space
    PdfPageTemplateElement headerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Top);
    headerSpace.Foreground = false;

    //declare two float variables
    float x = margins.Left;
    float y = 0;

    //draw image in header space 
    PdfImage headerImage = PdfImage.FromFile("logo.png");
    float width = headerImage.Width / 3;
    float height = headerImage.Height / 3;
    headerSpace.Graphics.DrawImage(headerImage, x, margins.Top - height - 2, width, height);

    //draw line in header space
    PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
    headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2);

    //draw text in header space
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 25f, FontStyle.Bold));
    PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
    String headerText = "HEADER TEXT";
    SizeF size = font.MeasureString(headerText, format);
    headerSpace.Graphics.DrawString(headerText, font, PdfBrushes.Gray, pageSize.Width - x - size.Width-2, margins.Top- (size.Height+5), format);

    //return headerSpace
    return headerSpace;
}

Step 2: Create a PDF document, call the method CreateHeaderTemplate() to create a header template and apply it to the document.

static void Main(string[] args)
{
    //create a PDF document
    PdfDocument doc = new PdfDocument();
    doc.PageSettings.Size = PdfPageSize.A4;

    //reset the default margins to 0
    doc.PageSettings.Margins = new PdfMargins(0);

    //create a PdfMargins object, the parameters indicate the page margins you want to set
    PdfMargins margins = new PdfMargins(60, 60, 60, 60);

    //create a header template with content and apply it to page template
    doc.Template.Top = CreateHeaderTemplate(doc, margins);
    
    //apply blank templates to other parts of page template
    doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Bottom);
    doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
    doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

    //save the file
    doc.SaveToFile("PdfHeader.pdf");
}

Full Code:

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


namespace AddPDFHeader
{
    class Program
    {
        static void Main(string[] args)
        {
            //create a PDF document
            PdfDocument doc = new PdfDocument();
            doc.PageSettings.Size = PdfPageSize.A4;

            //reset the default margins to 0
            doc.PageSettings.Margins = new PdfMargins(0);

            //create a PdfMargins object, the parameters indicate the page margins you want to set
            PdfMargins margins = new PdfMargins(60, 60, 60, 60);

            //create a header template with content and apply it to page template
            doc.Template.Top = CreateHeaderTemplate(doc, margins);

            //apply blank templates to other parts of page template
            doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Bottom);
            doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
            doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

            //save the file
            doc.SaveToFile("PdfHeader.pdf");
        }
        static PdfPageTemplateElement CreateHeaderTemplate(PdfDocument doc, PdfMargins margins)
        {
            //get page size
            SizeF pageSize = doc.PageSettings.Size;

            //create a PdfPageTemplateElement object as header space
            PdfPageTemplateElement headerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Top);
            headerSpace.Foreground = false;

            //declare two float variables
            float x = margins.Left;
            float y = 0;

            //draw image in header space 
            PdfImage headerImage = PdfImage.FromFile("logo.png");
            float width = headerImage.Width / 3;
            float height = headerImage.Height / 3;
            headerSpace.Graphics.DrawImage(headerImage, x, margins.Top - height - 2, width, height);

            //draw line in header space
            PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
            headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2);

            //draw text in header space
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 25f, FontStyle.Bold));
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
            String headerText = "HEADER TEXT";
            SizeF size = font.MeasureString(headerText, format);
            headerSpace.Graphics.DrawString(headerText, font, PdfBrushes.Gray, pageSize.Width - x - size.Width - 2, margins.Top - (size.Height + 5), format);

            //return headerSpace
            return headerSpace;
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing


Namespace AddPDFHeader
	Class Program
		Private Shared Sub Main(args As String())
			'create a PDF document
			Dim doc As New PdfDocument()
			doc.PageSettings.Size = PdfPageSize.A4

			'reset the default margins to 0
			doc.PageSettings.Margins = New PdfMargins(0)

			'create a PdfMargins object, the parameters indicate the page margins you want to set
			Dim margins As New PdfMargins(60, 60, 60, 60)

			'create a header template with content and apply it to page template
			doc.Template.Top = CreateHeaderTemplate(doc, margins)

			'apply blank templates to other parts of page template
			doc.Template.Bottom = New PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Bottom)
			doc.Template.Left = New PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height)
			doc.Template.Right = New PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height)

			'save the file
			doc.SaveToFile("PdfHeader.pdf")
		End Sub
		Private Shared Function CreateHeaderTemplate(doc As PdfDocument, margins As PdfMargins) As PdfPageTemplateElement
			'get page size
			Dim pageSize As SizeF = doc.PageSettings.Size

			'create a PdfPageTemplateElement object as header space
			Dim headerSpace As New PdfPageTemplateElement(pageSize.Width, margins.Top)
			headerSpace.Foreground = False

			'declare two float variables
			Dim x As Single = margins.Left
			Dim y As Single = 0

			'draw image in header space 
			Dim headerImage As PdfImage = PdfImage.FromFile("logo.png")
			Dim width As Single = headerImage.Width / 3
			Dim height As Single = headerImage.Height / 3
			headerSpace.Graphics.DrawImage(headerImage, x, margins.Top - height - 2, width, height)

			'draw line in header space
			Dim pen As New PdfPen(PdfBrushes.Gray, 1)
			headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2)

			'draw text in header space
			Dim font As New PdfTrueTypeFont(New Font("Impact", 25F, FontStyle.Bold))
			Dim format As New PdfStringFormat(PdfTextAlignment.Left)
			Dim headerText As [String] = "HEADER TEXT"
			Dim size As SizeF = font.MeasureString(headerText, format)
			headerSpace.Graphics.DrawString(headerText, font, PdfBrushes.Gray, pageSize.Width - x - size.Width - 2, margins.Top - (size.Height + 5), format)

			'return headerSpace
			Return headerSpace
		End Function
	End Class
End Namespace
Friday, 24 June 2011 05:51

Add PDF Footer in C#/VB.NET

A PDF header or footer presents consistent information (For example: a date, page numbering, the title of the overall document, or author’s name) in the page margins throughout a PDF. In this article, you will learn to add text and automatic page numbering to footer space when creating a PDF document from scratch.

Spire.PDF has a class named PdfPageTemplateElement, which represents a page template element that can be used as header, footer, watermark or stamp. The template can contain text, image as well as dynamic fields like PdfPageCountField, PdfPageNumberField, etc.

Step 1: Define a custom function CreateFooterTemplate() to create a page template element that servers as footer, and return a PdfPageDocumentElement object.

static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
{
    //get page size
    SizeF pageSize = doc.PageSettings.Size;

    //create a PdfPageTemplateElement object which works as footer space
    PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
    footerSpace.Foreground = false;

    //declare two float variables
    float x = margins.Left;
    float y = 0;

    //draw line in footer space
    PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
    footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y);

    //draw text in footer space
    y = y + 5;
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 10f), true);
    PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
    String footerText = "E-iceblue Technology Co., Ltd.\nTel:028-81705109\nWebsite:http://www.e-iceblue.com";
    footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format);

    //draw dynamic field in footer space
    PdfPageNumberField number = new PdfPageNumberField();
    PdfPageCountField count = new PdfPageCountField();
    PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count);
    compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
    SizeF size = font.MeasureString(compositeField.Text);
    compositeField.Bounds = new RectangleF(pageSize.Width - x , y, size.Width, size.Height);
    compositeField.Draw(footerSpace.Graphics);

    //return footerSpace
    return footerSpace;
}

Step 2: Create a PDF document, call the method CreateFooterTemplate() to create a footer template and apply it to the document.

static void Main(string[] args)
{
    //create a PDF document
    PdfDocument doc = new PdfDocument();
    doc.PageSettings.Size = PdfPageSize.A4;

    //reset the default margins to 0
    doc.PageSettings.Margins = new PdfMargins(0);

    //create a PdfMargins object, the parameters indicate the page margins you want to set
    PdfMargins margins = new PdfMargins(60, 60, 60, 60);

    //create a footer template with content and apply it to bottom page template
    doc.Template.Bottom = CreateFooterTemplate(doc, margins);

    //apply blank templates to other parts of page template
    doc.Template.Top = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top);
    doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
    doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

    //add two pages in the document
    doc.Pages.Add();
    doc.Pages.Add();

    //save the file
    doc.SaveToFile("PdfFooter.pdf");
}

Output:

Add PDF Footer in C#, VB.NET

Full Code:

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


namespace AddPDFFooter
{
    class Program
    {
        static void Main(string[] args)
        {
            //create a PDF document
            PdfDocument doc = new PdfDocument();
            doc.PageSettings.Size = PdfPageSize.A4;

            //reset the default margins to 0
            doc.PageSettings.Margins = new PdfMargins(0);

            //create a PdfMargins object, the parameters indicate the page margins you want to set
            PdfMargins margins = new PdfMargins(60, 60, 60, 60);

            //create a footer template with content and apply it to page template
            doc.Template.Bottom = CreateFooterTemplate(doc, margins);

            //apply blank templates to other parts of page template
            doc.Template.Top = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top);
            doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
            doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

            //add two pages in the document
            doc.Pages.Add();
            doc.Pages.Add();

            //save the file
            doc.SaveToFile("PdfFooter.pdf");
        }
        static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
        {
            //get page size
            SizeF pageSize = doc.PageSettings.Size;

            //create a PdfPageTemplateElement object which works as footer space
            PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
            footerSpace.Foreground = false;

            //declare two float variables
            float x = margins.Left;
            float y = 0;

            //draw line in footer space
            PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
            footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y);

            //draw text in footer space
            y = y + 5;
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 10f), true);
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
            String footerText = "E-iceblue Technology Co., Ltd.\nTel:028-81705109\nWebsite:http://www.e-iceblue.com";
            footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format);

            //draw dynamic field in footer space
            PdfPageNumberField number = new PdfPageNumberField();
            PdfPageCountField count = new PdfPageCountField();
            PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count);
            compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
            SizeF size = font.MeasureString(compositeField.Text);
            compositeField.Bounds = new RectangleF(pageSize.Width - x, y, size.Width, size.Height);
            compositeField.Draw(footerSpace.Graphics);

            //return footerSpace
            return footerSpace;
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.AutomaticFields
Imports Spire.Pdf.Graphics
Imports System.Drawing


Namespace AddPDFFooter
	Class Program
		Private Shared Sub Main(args As String())
			'create a PDF document
			Dim doc As New PdfDocument()
			doc.PageSettings.Size = PdfPageSize.A4

			'reset the default margins to 0
			doc.PageSettings.Margins = New PdfMargins(0)

			'create a PdfMargins object, the parameters indicate the page margins you want to set
			Dim margins As New PdfMargins(60, 60, 60, 60)

			'create a footer template with content and apply it to page template
			doc.Template.Bottom = CreateFooterTemplate(doc, margins)

			'apply blank templates to other parts of page template
			doc.Template.Top = New PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top)
			doc.Template.Left = New PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height)
			doc.Template.Right = New PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height)

			'add two pages in the document
			doc.Pages.Add()
			doc.Pages.Add()

			'save the file
			doc.SaveToFile("PdfFooter.pdf")
		End Sub
		Private Shared Function CreateFooterTemplate(doc As PdfDocument, margins As PdfMargins) As PdfPageTemplateElement
			'get page size
			Dim pageSize As SizeF = doc.PageSettings.Size

			'create a PdfPageTemplateElement object which works as footer space
			Dim footerSpace As New PdfPageTemplateElement(pageSize.Width, margins.Bottom)
			footerSpace.Foreground = False

			'declare two float variables
			Dim x As Single = margins.Left
			Dim y As Single = 0

			'draw line in footer space
			Dim pen As New PdfPen(PdfBrushes.Gray, 1)
			footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y)

			'draw text in footer space
			y = y + 5
			Dim font As New PdfTrueTypeFont(New Font("Impact", 10F), True)
			Dim format As New PdfStringFormat(PdfTextAlignment.Left)
			Dim footerText As [String] = "E-iceblue Technology Co., Ltd." & vbLf & "Tel:028-81705109" & vbLf & "Website:http://www.e-iceblue.com"
			footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format)

			'draw dynamic field in footer space
			Dim number As New PdfPageNumberField()
			Dim count As New PdfPageCountField()
			Dim compositeField As New PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count)
			compositeField.StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top)
			Dim size As SizeF = font.MeasureString(compositeField.Text)
			compositeField.Bounds = New RectangleF(pageSize.Width - x, y, size.Width, size.Height)
			compositeField.Draw(footerSpace.Graphics)

			'return footerSpace
			Return footerSpace
		End Function
	End Class
End Namespace
Wednesday, 22 June 2011 08:53

Spire.PDF for .NET Program Guide Content

Spire.PDF for .NET is a professional PDF API applied to creating, writing, editing, handling and reading PDF files without any external dependencies within .NET (C#, VB.NET, ASP.NET, .NET Core, .NET 5.0, .NET 6.0, .NET 7.0, MonoAndroid and Xamarin.iOS) application. Using this .NET PDF library, you can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely through C#/VB.NET without installing Adobe Acrobat.

Many rich features can be supported by the .NET PDF API, such as adding digital signature, including timestamp in signature, adding dynamic/image stamp, adding text/image watermark, creating PDF Portfolio, extracting text/attachment/images, PDF merging/spliting, metadata updating, section, graph/image drawing and inserting, table creation and processing, cropping pages, copying pages, and importing data etc.

Monday, 21 February 2022 08:45

C#/VB.NET: Convert HTML to PDF

Converting HTML content into PDF offers many advantages, including the ability to read it offline, as well as preserving the content and formatting with high fidelity. Spire.PDF provides two methods to convert HTML to PDF, one is to use QT Web plugin, the other is not to use plugin. We recommend that you use QT plugin to do the conversion.

The following sections demonstrate how to render an HTML webpage (URL) or an HTML string to a PDF document using Spire.PDF for .NET with or without QT plugin.

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 

Download Plugin

If you choose the plugin method, please download the plugin that fits in with your operating system from the following link.

Unzip the package somewhere on your disk to get the "plugins" folder. In this example, we saved the plugin under the path "F:\Libraries\Plugin\plugins-windows-x64\plugins‪‪".‬‬

C#/VB.NET: Convert HTML to PDF

Also, we recommend that you set the "Platform target" of your project to x64 or x86 accordingly.

C#/VB.NET: Convert HTML to PDF

Convert a URL to PDF with QT Plugin

The following are the steps to convert a URL to PDF using Spire.PDF with QT plugin.

  • Specify the URL path to convert.
  • Specify the path of the generated PDF file.
  • Specify the plugin path, and assign it as the value of the HtmlConverter.PluginPath property.
  • Call HtmlConverter.Convert(string url, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, PdfMargins margins) method to convert a URL to a PDF document.
  • C#
  • VB.NET
using Spire.Pdf.Graphics;
using Spire.Additions.Qt; 
using System.Drawing;

namespace ConvertUrlToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the URL path
            string url = "https://www.wikipedia.org/";

            //Specify the output file path
            string fileName = "UrlToPdf.pdf";

            //Specify the plugin path
             string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";

            //Set the plugin path
             HtmlConverter.PluginPath = pluginPath;

            //Convert URL to PDF
            HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
        }
    }
}

Convert an HTML String to PDF with QT Plugin

The following are the steps to convert an HTML string to PDF using Spire.PDF with QT plugin.

  • Get the HTML string from a .html file.
  • Specify the path of the generated PDF file.
  • Specify the plugin path, and assign it as the value of the HtmlConverter.PluginPath property.
  • Call HtmlConverter.Convert(string htmlString, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, PdfMargins margins, Spire.Pdf.HtmlConverter.LoadHtmlType htmlType) method to convert HTML string to a PDF document.

Note: Only inline CSS style and internal CSS style can be rendered correctly on PDF. If you have an external CSS style sheet, please convert it to inline or internal CSS style.

  • C#
  • VB.NET
using System.IO;
using Spire.Additions.Qt; 
using System.Drawing;
using Spire.Pdf.Graphics;

namespace ConvertHtmlStringToPdfWithPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the HTML string from a .html file
            string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");

            //Specify the output file path
            string fileName = "HtmlStringToPdf.pdf";

            //Specify the plugin path
            string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";

            //Set plugin path
            HtmlConverter.PluginPath = pluginPath;

            //Convert HTML string to PDF
            HtmlConverter.Convert(htmlString, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0), LoadHtmlType.SourceCode);       
        }
    }
}

Convert a URL to PDF Without Plugin

The following are the steps to convert a URL to PDF using Spire.PDF without plugin.

  • Create a PdfDocument object.
  • Create a PdfPageSettings object, and set the page size and margins through it.
  • Create a PdfHtmlLayoutFormat object, and set the IsWaiting property of it to true.
  • Specify the URL path to convert.
  • Load HTML from the URL path using PdfDocument.LoadFromHTML() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using System.Threading;
using Spire.Pdf.HtmlConverter;
using System.Drawing;

namespace ConverUrlToPdfWithoutPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Create a PdfPageSettings object
            PdfPageSettings setting = new PdfPageSettings();

            //Save page size and margins through the object
            setting.Size = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            //Create a PdfHtmlLayoutFormat object
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            //Set IsWaiting property to true
            htmlLayoutFormat.IsWaiting = true;

            //Specific the URL path to convert
            String url = "https://www.wikipedia.org/";

            //Load HTML from a URL path using LoadFromHTML method
            Thread thread = new Thread(() =>
            { doc.LoadFromHTML(url, true, true, false, setting, htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //Save the document to a PDF file
            doc.SaveToFile("UrlToPdf.pdf");
            doc.Close();
        }
    }
}

Convert an HTML String to PDF Without Plugin

The following are the steps to convert an HTML string to PDF using Spire.PDF without plugin.

  • Create a PdfDocument object.
  • Create a PdfPageSettings object, and set the page size and margins through it.
  • Create a PdfHtmlLayoutFormat object, and set the IsWaiting property of it to true.
  • Read the HTML string from a .html file.
  • Load HTML from the HTML string using PdfDocument.LoadFromHTML() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;
using System.Drawing;

namespace ConvertHtmlStringToPdfWithoutPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Create a PdfPageSettings object
            PdfPageSettings setting = new PdfPageSettings();

            //Save page size and margins through the object
            setting.Size = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            //Create a PdfHtmlLayoutFormat object
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            //Set IsWaiting property to true
            htmlLayoutFormat.IsWaiting = true;

            //Read html string from a .html file
            string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");

            //Load HTML from html string using LoadFromHTML method
            Thread thread = new Thread(() =>
            { doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //Save to a PDF file
            doc.SaveToFile("HtmlStringToPdf.pdf");
        }
    }
}

Apply for a Temporary License

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

Page 242 of 242