Monday, 11 July 2011 06:05

Convert XML to PDF in C#, VB.NET

A lot of reasons can be attributed to the common requirement of Office OpenXML to PDF conversion. Office OpenXML(Extensible Markup Language),is a document format that is both human-readable and machine-readable. Even it emphasizes simplicity, generality, and usability over the internet, it is not as conveniently applied, widely supported and safely managed as PDF document format. So this article introduces a solution of three lines of key code to quickly convert Office OpenXML to PDF.

Spire.Doc for .NET is a professional Word component for .NET, which allows users to realize the task of Office OpenXML to PDF conversion through three lines of key code. The first line is for you to load your Office OpenXML file from system by calling Spire.Doc.Document class instance method LoadFromFile; the second is to save the Office OpenXML file as Doc file format by invoking the method SaveToFile to pass a parameter FileFormat.Doc; with the last line, you can save your Doc as PDF file format by the same method SaveToFile to pass the other parameter FileFormat.PDF.

Please Download Spire.Doc for .NET and view the effective screenshot of converting Office OpenXML to PDF below first.

XML to PDF

Code sample of  converting Office OpenXML to PDF

[C#]
using Spire.Doc;

namespace XML2PDf
{
    class Program
    {
        static void Main(string[] args)
        {
            Document mydoc = new Document();
            mydoc.LoadFromFile(@"..\sample.xml", FileFormat.Xml);
            mydoc.SaveToFile("Test.doc", FileFormat.Doc);
            mydoc.SaveToFile("test.pdf", FileFormat.PDF);
            System.Diagnostics.Process.Start("Test.pdf");

        }
    }
}      
[VB.NET]
Imports Spire.Doc
Namespace XMLPDf
	Class Program
		Private Shared Sub Main(args As String())
			Dim mydoc As New Document()
			mydoc.LoadFromFile("..\sample.xml", FileFormat.Xml)
			mydoc.SaveToFile("Test.doc", FileFormat.Doc)
			mydoc.SaveToFile("test.pdf", FileFormat.PDF)
			System.Diagnostics.Process.Start("Test.pdf")

		End Sub
	End Class
End Namespace

Besides converting Office OpenXML to PDF, Spire.Doc also can convert Word to PDF, RTF to PDF, Word to Image/EPUB/HTML/Text/Office OpenXML/RTF/Tiff as well as convert HTML to Word/Image, RTF to HTML and Office OpenXML to Word. Click to know more about this Word .NET Component.

Friday, 08 July 2011 05:23

Excel to PDF in C#, VB.NET

In order to convert Excel to PDF in C#/VB.NET, you may have searched a lot, finding huge lines of codes but not perfect in quality. Here is the nice solution you are looking for. Within this section, we will demonstrate how to convert Excel to PDF using C#/VB.NET. This conversion will be successfully managed within just several lines of codes, but the quality will be absolutely perfect; As the PDF will be the same as your Excel file.

Spire.XLS for .NET is .NET Excel component which enables your .NET applications to fast generate, read, write and modify Excel document without Microsoft Office Excel Automation. It also fully supports converting files from Excel to PDF, Excel to HTML, Excel to CSV, Excel to Text, Excel to Image and Excel to XML. Any kind of trial and evaluation is always welcomed. Please feel free to download Spire.XLS for .NET to have a trial.

Spire.XLS now offers a new method to convert excel to PDF, which supports convert chart, shape and smart art in excel file to PDF. Please refer to new method of convert Excel to PDF.

The following is the code samples for converting Excel to PDF in C#/VB.NET. You can directly copy and paste into your project to have a try and convert your Excel to PDF for personal use.

[C#]
using Spire.Xls;
using Spire.Pdf;
using Spire.Xls.Converter;

namespace ExceltoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
           // load Excel file
           Workbook workbook = new Workbook();
           workbook.LoadFromFile("D:\\test.xlsx");
 
           // Set PDF template
           PdfDocument pdfDocument = new PdfDocument();
           pdfDocument.PageSettings.Orientation = PdfPageOrientation.Landscape;
           pdfDocument.PageSettings.Width = 970;
           pdfDocument.PageSettings.Height = 850;

           //Convert Excel to PDF using the template above
           PdfConverter pdfConverter = new PdfConverter(workbook);
           PdfConverterSettings settings = new PdfConverterSettings();
           settings.TemplateDocument = pdfDocument;
           pdfDocument = pdfConverter.Convert(settings);

           // Save and preview PDF
           pdfDocument.SaveToFile("sample.pdf");
           System.Diagnostics.Process.Start("sample.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Xls
Imports Spire.Pdf
Imports Spire.Xls.Converter

Namespace ExceltoPDF
	Class Program
		Private Shared Sub Main(args As String())
			' load Excel file
			Dim workbook As New Workbook()
			workbook.LoadFromFile("D:\test.xlsx")

			' Set PDF template
			Dim pdfDocument As New PdfDocument()
			pdfDocument.PageSettings.Orientation = PdfPageOrientation.Landscape
			pdfDocument.PageSettings.Width = 970
			pdfDocument.PageSettings.Height = 850

			'Convert Excel to PDF using the template above
			Dim pdfConverter As New PdfConverter(workbook)
			Dim settings As New PdfConverterSettings()
			settings.TemplateDocument = pdfDocument
			pdfDocument = pdfConverter.Convert(settings)

			' Save and preview PDF
			pdfDocument.SaveToFile("sample.pdf")
			System.Diagnostics.Process.Start("sample.pdf")
		End Sub
	End Class
End Namespace

After this code, you can run this application and you will see the PDF converted from Excel. Below is a comparison of the original Excel and target PDF, please have a check.

Excel to PDF

Friday, 08 July 2011 03:47

Convert Text to PDF in C#, VB.NET

Converting text to PDF is based on the reason below: text is listed as the simplest file format, which limits users only to edit words. However, in most cases, people need do more tasks such as protect files, store the documents on a company's server, view document by freeware. All these functions are hardly to be realized neither by text nor other formats. Thus, convert text to PDF is indispensable. Different from other tools, Spire.PDF, as a professional PDF component, allows you not only to easily convert text to PDF via C#, VB.NET but also to Extract text and images out of the PDF file.

Using Spire.PDF, you can realize the whole task on any platform of .NET, Silverlight and WPF. Before you start, please Download Spire.PDF first, and then, follow code samples to convert Text to PDF in C#, VB.NET

[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Pdf;
using System.IO;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace TexttoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = File.ReadAllText("TestDocument.txt");
            PdfDocument doc = new PdfDocument();
            PdfSection section = doc.Sections.Add();
            PdfPageBase page = section.Pages.Add();
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
            PdfStringFormat format = new PdfStringFormat();
            format.LineSpacing = 20f;
            PdfBrush brush = PdfBrushes.Black;
            PdfTextWidget textWidget = new PdfTextWidget(text, font, brush);
            float y = 0;
            PdfTextLayout textLayout = new PdfTextLayout();
            textLayout.Break = PdfLayoutBreakType.FitPage;
            textLayout.Layout = PdfLayoutType.Paginate;
            RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize);
            textWidget.StringFormat = format;
            textWidget.Draw(page, bounds, textLayout);
            doc.SaveToFile("TxtToPDf.pdf", FileFormat.PDF);
        }
    }
[VB.NET]
Imports Spire.Pdf.Graphics
Imports Spire.Pdf
Imports System.IO
Imports System.Drawing

Module Module1

    Sub Main()
        Dim text As String = File.ReadAllText("TestDocument.txt")
        Dim doc As New PdfDocument()
        Dim section As PdfSection = doc.Sections.Add()
        Dim page As PdfPageBase = section.Pages.Add()
        Dim font As New PdfFont(PdfFontFamily.Helvetica, 11)
        Dim format As New PdfStringFormat()
        format.LineSpacing = 20.0F
        Dim brush As PdfBrush = PdfBrushes.Black
        Dim textWidget As New PdfTextWidget(text, font, brush)
        Dim y As Single = 0
        Dim textLayout As New PdfTextLayout()
        textLayout.Break = PdfLayoutBreakType.FitPage
        textLayout.Layout = PdfLayoutType.Paginate
        Dim bounds As New RectangleF(New PointF(0, y), page.Canvas.ClientSize)
        textWidget.StringFormat = format
        textWidget.Draw(page, bounds, textLayout)
        doc.SaveToFile("TxtToPDf.pdf", FileFormat.PDF)

    End Sub

End Module

Below is an effective screenshot of text to PDF, please have a look.

Text to PDF

Thursday, 07 July 2011 05:38

Draw Ellipses in PDF in C#, VB.NET

In geometry, an ellipse is a plane curve that results from the intersection of a cone by a plane in a way that produces a closed curve. Circles are special cases of ellipses, obtained when the cutting plane is orthogonal to the cone's axis. An ellipse is also the locus of all points of the plane whose distances to two fixed points add to the same constant. In this section, I will introduce a solution to draw ellipses in PDF document and set ellipses size, color and position via Spire.PDF for .NET in C#, VB.NET. First let us see the ellipses I draw in PDF document as below picture:

Draw Ellipses in PDF

For Spire.PDF for .NET users, we can easily draw ellipses and set ellipses size and position by this method: Spire.Pdf.PdfPageBase.Canvas.DrawEllipse(PdfPen pen, PdfBrush brush, float x, float y, float width, float height); There are six parameters passed in this method. The first parameter is a class in Spire.PDF: Spire.Pdf.Graphics.PdfPen which is responsible for drawing ellipses. When drawing PDF ellipses, we also can set the outline color and outline thickness by classes provided by Microsoft: System.Drawing.Color and System.Single. The second parameter is a class Spire.Pdf.Graphics.PdfBrush, when we define this class, we can set the ellipse color. The third and fourth parameters are the distance between the left and top margin with ellipse, which certainly decide the position of ellipse we draw. The last two parameters are ellipse width and height. To say in other word, the last two parameters can determine ellipse size.

Here we can download download Spire.PDF for .NET. After installing it on system, we can begin our task as below code:

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

namespace PDFellipses
{
    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();
            //draw ellipses in PDF and set ellipse size and position
            PdfPen pen = new PdfPen(Color.Red, 1f);
            PdfBrush brush = new PdfSolidBrush(Color.Yellow);
            PdfPen pen1 = new PdfPen(Color.DeepPink, 1f);
            PdfBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue);
            PdfPen pen2 = new PdfPen(Color.Cornsilk, 1f);
            PdfBrush brush2 = new PdfSolidBrush(Color.Red);
            PdfPen pen3 = new PdfPen(Color.SpringGreen, 1f);
            PdfBrush brush3 = new PdfSolidBrush(Color.SeaGreen);
            PdfPen pen4 = new PdfPen(Color.YellowGreen, 1f);
            PdfBrush brush4 = new PdfSolidBrush(Color.Orange);
            page.Canvas.DrawEllipse(pen, brush, 50, 70, 20, 60);
            page.Canvas.DrawEllipse(pen1, brush1, 100, 100, 20, 70);
            page.Canvas.DrawEllipse(pen2, brush2, 150, 150, 20, 70);
            page.Canvas.DrawEllipse(pen3, brush3, 200, 100, 20, 70);
            page.Canvas.DrawEllipse(pen4, brush4, 250, 70, 20, 60);
            //restor graphics
            page.Canvas.Restore(state);
            doc.SaveToFile("Ellipse.pdf");
            System.Diagnostics.Process.Start("Ellipse.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace PDFellipses
	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()
			'draw ellipses in PDF and set ellipse size and position
			Dim pen As New PdfPen(Color.Red, 1F)
			Dim brush As PdfBrush = New PdfSolidBrush(Color.Yellow)
			Dim pen1 As New PdfPen(Color.DeepPink, 1F)
			Dim brush1 As PdfBrush = New PdfSolidBrush(Color.DeepSkyBlue)
			Dim pen2 As New PdfPen(Color.Cornsilk, 1F)
			Dim brush2 As PdfBrush = New PdfSolidBrush(Color.Red)
			Dim pen3 As New PdfPen(Color.SpringGreen, 1F)
			Dim brush3 As PdfBrush = New PdfSolidBrush(Color.SeaGreen)
			Dim pen4 As New PdfPen(Color.YellowGreen, 1F)
			Dim brush4 As PdfBrush = New PdfSolidBrush(Color.Orange)
			page.Canvas.DrawEllipse(pen, brush, 50, 70, 20, 60)
			page.Canvas.DrawEllipse(pen1, brush1, 100, 100, 20, 70)
			page.Canvas.DrawEllipse(pen2, brush2, 150, 150, 20, 70)
			page.Canvas.DrawEllipse(pen3, brush3, 200, 100, 20, 70)
			page.Canvas.DrawEllipse(pen4, brush4, 250, 70, 20, 60)
			'restor graphics
			page.Canvas.Restore(state)
			doc.SaveToFile("Ellipse.pdf")
			System.Diagnostics.Process.Start("Ellipse.pdf")
		End Sub
	End Class
End Namespace

Spire.PDF for .NET is a professional PDF library that enables users draw different kinds of shapes in PDF document such as rectangles, arcs, circles, ellipse, five-pointed star etc.

Wednesday, 06 July 2011 03:48

Draw PDF Arc in C#, VB.NET

An 'arc' is part of the circumference of a circle. In geometry, an arc is a closed segment of a differentiable curve in the two-dimensional plane; for example, a circular arc is a segment of the circumference of a circle. If the arc is part of a great circle (or great ellipse), it is called a great arc. This article will introduce a solution to draw PDF arc and set arc position and size via this .NET PDF component Spire.PDF for .NET in C#, VB.NET. First let us see the PDF arc which is drawn by code in the end of this section:

Draw Arcs in PDF

When we draw PDF arcs, we first need to know this method provided by Spire.PDF for .NET: Spire.Pdf.PdfPageBase.Canvas.DrawArc(PdfPen pen, float x, float y, float width, float height, float startAngle, float sweepAngle); As we see, there are seven parameters passed in this method. The first parameter is a class: Spire.Pdf.Graphics.PdfPen. By using this class, we can draw arc in PDF. If we want to set the color of PDF arc and the thickness of the arc line, we can use another two classes which are offered by Microsoft: System.Drawing.Color and System.Single. The second and third parameters: "float x" and "float y" determine the distance between the arcs and PDF left and top margin. The fourth and fifth parameters are the width and height of PDF arc. The last two parameters start angle and sweep angle which decide which kind of arc we draw.

Here we can download Spire.PDF for .NET; and install it on system. After adding Spire.Pdf dll, we can start our task according to below code:

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

namespace pdfcircle
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            // Create one page
            PdfPageBase page = doc.Pages.Add();
            //draw PDF arcs and set its size and position
            PdfGraphicsState state = page.Canvas.Save();
            PdfPen pen = new PdfPen(Color.DeepSkyBlue, 4f);
            PdfPen pen1 = new PdfPen(Color.Red, 4f);
            PdfPen pen2 = new PdfPen(Color.Red, 4f);
            PdfPen pen3 = new PdfPen(Color.DeepSkyBlue, 4f);
            PdfPen pen4 = new PdfPen(Color.Black, 4f);
            PdfPen pen5 = new PdfPen(Color.Black, 4f);
            PdfPen pen6 = new PdfPen(Color.Black, 4f);
            PdfPen pen7 = new PdfPen(Color.Black, 4f);
            PdfPen pen8 = new PdfPen(Color.Red, 1f);
            PdfPen pen9= new PdfPen(Color.Red, 1f);
            page.Canvas.DrawArc(pen, 130, 100, 20, 90, 20, 300);
            page.Canvas.DrawArc(pen1, 60, 100, 20, 90, 20,300);
            page.Canvas.DrawArc(pen2, 90, 100, 20, 90, 218, 300);
            page.Canvas.DrawArc(pen3, 160, 100, 20, 90, 218, 300);
            page.Canvas.DrawArc(pen4, 70, 130, 5, 5, 0, 360);
            page.Canvas.DrawArc(pen5, 95, 130, 5, 5, 0, 360);
            page.Canvas.DrawArc(pen6, 140, 130, 5, 5, 0, 360);
            page.Canvas.DrawArc(pen7, 161, 130, 5, 5, 0, 360);
            page.Canvas.DrawArc(pen8, 83, 145, 5, 5, 350,200);
            page.Canvas.DrawArc(pen9, 150, 145, 5, 5, 350, 200);
            //restor graphics
            page.Canvas.Restore(state);
            doc.SaveToFile("Arcs.pdf");
            System.Diagnostics.Process.Start("Arcs.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace pdfcircle
	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()
			'draw PDF arcs and set its size and position
			Dim state As PdfGraphicsState = page.Canvas.Save()
			Dim pen As New PdfPen(Color.DeepSkyBlue, 4F)
			Dim pen1 As New PdfPen(Color.Red, 4F)
			Dim pen2 As New PdfPen(Color.Red, 4F)
			Dim pen3 As New PdfPen(Color.DeepSkyBlue, 4F)
			Dim pen4 As New PdfPen(Color.Black, 4F)
			Dim pen5 As New PdfPen(Color.Black, 4F)
			Dim pen6 As New PdfPen(Color.Black, 4F)
			Dim pen7 As New PdfPen(Color.Black, 4F)
			Dim pen8 As New PdfPen(Color.Red, 1F)
			Dim pen9 As New PdfPen(Color.Red, 1F)
			page.Canvas.DrawArc(pen, 130, 100, 20, 90, 20, _
				300)
			page.Canvas.DrawArc(pen1, 60, 100, 20, 90, 20, _
				300)
			page.Canvas.DrawArc(pen2, 90, 100, 20, 90, 218, _
				300)
			page.Canvas.DrawArc(pen3, 160, 100, 20, 90, 218, _
				300)
			page.Canvas.DrawArc(pen4, 70, 130, 5, 5, 0, _
				360)
			page.Canvas.DrawArc(pen5, 95, 130, 5, 5, 0, _
				360)
			page.Canvas.DrawArc(pen6, 140, 130, 5, 5, 0, _
				360)
			page.Canvas.DrawArc(pen7, 161, 130, 5, 5, 0, _
				360)
			page.Canvas.DrawArc(pen8, 83, 145, 5, 5, 350, _
				200)
			page.Canvas.DrawArc(pen9, 150, 145, 5, 5, 350, _
				200)
			'restor graphics
			page.Canvas.Restore(state)
			doc.SaveToFile("Arcs.pdf")
			System.Diagnostics.Process.Start("Arcs.pdf")
		End Sub
	End Class
End Namespace

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

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.

Digital signature is the alternative way of signing documents in era of electronic exchange of documents. Creating digital signature in PDF, without any doubt, becomes one of the most popular ways to protect PDF file from editing and tampering. This section will introduce a solution to create digital signature in PDF via a .NET PDF component.

Spire.PDF for .NET, with rich features to protect and manipulate PDF documents, allows you to keep your PDF secure by creating digital signature in PDF with C#, VB.NET. As long as the digital signature is signed, the signer's identity has been verified and your PDF document can be safe and cannot be modified.

Please download Spire.PDF for .NET and view the screenshot of this task as below picture:

Create Digital Signature

In the key code, first you are required to create one instance of Spire.Pdf.Security.PdfCertificate class with two parameters passed: a certificate file and the file password. This instance is named to be digi. After that, digi is used as a parameter of another instance in a different class: PdfSignature class. Here it is called signature. In order to sign PDF digital signature in any page, a "page" parameter is provided. Through DocumentPermission, you can restrict the PDF permission to be AllowComments, AllowFormFill and ForbidChanges.

[C#]
PdfDocument doc = new PdfDocument("Sample.pdf");
PdfPageBase page = doc.Pages[0];

PdfCertificate cert = new PdfCertificate("Demo.pfx", "e-iceblue");

PdfSignature signature = new PdfSignature(doc, page, cert, "demo");

signature.ContactInfo = "Harry";
signature.Certificated = true;

signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

doc.SaveToFile("Result.pdf");
[VB.NET]
Private Sub SurroundingSub()
    Dim doc As PdfDocument = New PdfDocument("Sample.pdf")
    Dim page As PdfPageBase = doc.Pages(0)
    Dim cert As PdfCertificate = New PdfCertificate("Demo.pfx", "e-iceblue")
    Dim signature As PdfSignature = New PdfSignature(doc, page, cert, "demo")
    signature.ContactInfo = "Harry"
    signature.Certificated = True
    signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill
    doc.SaveToFile("Result.pdf")
End Sub

Spire.PDF for .NET is a .NET PDF component which can secure your PDF by encrypting PDF and creating PDF digital signature. When you need to unlock PDF file, it also enables you to decrypt PDF in a fast way.

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