Thursday, 14 July 2011 06:14

Convert Word to HTML in C#, VB.NET

Word to html conversion enables programmers and developers to create html through editing and degining word. Finally convert word to html. This section will introduce a solution to convert word to html via a .NET Word component with C#, VB.NET.

Spire.Doc for .NET, a professional word component, without installing MS Word, enables you to convert word to html with two lines of key code. One is Document.LoadFromFile(string fileName) method which is used to load your word file from system. The other is Document.SaveToFile(string fileName, FileFormat fileFormat) that is responsible to save word as html file.

Here you can view the effect of word to html conversion task. Please feel free to download Spire.Doc for .NET and view the detail code after the picture above.

Word to HTML

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            //Create word document
            Document document = new Document();
            document.LoadFromFile(@"..\wordtohtml.doc");

            //Save doc file to html
            document.SaveToFile("toHTML.html", FileFormat.Html);
            WordDocViewer("toHTML.html");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }
    }
}

[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace Word_to_HTML
    
    Public Class Form1
        Inherits Form
        
        Public Sub New()
            MyBase.New
            InitializeComponent
        End Sub
        
        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            'Create word document
            Dim document As Document = New Document
            document.LoadFromFile("..\wordtohtml.doc")
            'Save doc file to html
            document.SaveToFile("toHTML.html", FileFormat.Html)
            WordDocViewer("toHTML.html")
        End Sub
        
        Private Sub WordDocViewer(ByVal fileName As String)
            Try 
                System.Diagnostics.Process.Start(fileName)
            Catch  As System.Exception
                
            End Try
        End Sub
    End Class
End Namespace

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, 13 July 2011 06:07

How to Convert Word to Text

Why We Convert Word to Text?

Text is a format usually contains plain text or with minimum formatting. We can get benefits from Word to Text conversion:

  • Much smaller file size to save disk space
  • Compatible with almost all applications
  • Without or with minimum formatting and/or unusual characters

How to Convert Word to Text?

Spire.Doc is a MS Word component which enables user to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document for .NET and Silverlight. It supports converting files from Word Doc to Text, HTML, PDF, XML, RTF, Docx, Dot, etc.

Download Spire.Doc (or Spire.Office) with .NET Framework 2.0 (or above) together and follow the simple code below to convert Word to Text.

Step 1: Create a project in Visual Studio. Add Spire.Doc DLL as reference.

Step 2: Use the following code to load local Word docfile which you want to convert to Txt file.

            Document document = new Document();
            document.LoadFromFile(@"D:\Work\Stephen\2011.12.05\Sample.doc");

Step 3: Save the word doc file as HTML by using the code below:

            document.SaveToFile("Sample.txt", FileFormat.Txt);

Step 4: Write the following full code into your project and press F5 to start it. Then, a Txt file will be automatically generated.

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            //Create word document
            Document document = new Document();
            document.LoadFromFile(@"D:\Work\Stephen\2011.12.05\Sample.doc");

            //Save doc file.
            document.SaveToFile("Sample.txt", FileFormat.Txt);

            //Launching the MS Word file.
            WordDocViewer("Sample.txt");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}
[VB.NET]
Imports System
Imports System.Windows.Forms
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace tohtml_3
	Partial Public Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
			'Create word document
			Dim document As New Document()
			document.LoadFromFile("D:\Work\Stephen\2011.12.05\Sample.doc")

			'Save doc file.
			document.SaveToFile("Sample.txt", FileFormat.Txt)

			'Launching the MS Word file.
			WordDocViewer("Sample.txt")
		End Sub

		Private Sub WordDocViewer(ByVal fileName As String)
			Try
				System.Diagnostics.Process.Start(fileName)
			Catch
			End Try
		End Sub

	End Class
End Namespace

Effective Screenshot:

Word to Text

Wednesday, 13 July 2011 05:45

Generate Excel Charts in C#, VB.NET

Why Generate Excel Chart?

In Microsoft Excel, we can generate different charts based on our data information. These excel charts can easily relay your messages that may otherwise go unnoticed by your audience. Most excel charts can help international audiences to understand because they are universally known and easily explained. On the other hand, it’s very easy to generate excel charts.

How to Use .NET to Generate Excel Chart?

With Microsoft Excel, users can generate Excel charts including Pie Chart, Column Chart, Bar Chart, Line Chart, Radar Chart, etc. And with Spire.XLS for .NET, users can use .NET generate those charts either. 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.

Suppose we are generating an excel pie chart. Spire.XLS presents you an easy way to create a pie chart in the Excel workbook. First, you should create a pie chart with the sheet.Charts.Add method. You may control the resource of the data and title of the chart by setting DataRange and ChartTitle properties. What's more, we create an object to operate more about the chart. You may set the label and value of the pie with the properties cs.CategoryLabels and cs.Values. If you want to hide the value of the pie, you may set the cs.DataPoints.DefaultDataPoint.DataLabels.HasValue property false. In this demo, in order to reflect the effect of the chart, we set the grid lines of the worksheet invisible by assigning the sheet.GridLinesVisible false.

After running the demo, you may find a pie appear in the document:

Generate Excel Charts

Spire.XLS allows users use .NET generate excel charts including Pie Chart, Column Chart, bar chart, line chart, radar chart, Cone chart, Cylinder chart, Doughnut chart, pyramid chart, scatter chart, stock chart and surface chart.

Effective Screenshots

Spire.XLS use .NET Generate Bar Chart

Generate Excel Charts

Spire.XLS use .NET Generate Column Chart

Generate Excel Charts

Spire.XLS use .NET Generate Line Chart

Generate Excel Charts

Spire.XLS use .NET Generate Radar Chart

Generate Excel Charts

Monday, 11 July 2011 06:26

Convert Image to PDF in C#, VB.NET

When it comes to the conversion of image to PDF, people are commonly bothered by various problems such as: hardly load images to PDF files from streams or files on disk directly; some special image formats are neither supported by your tools nor clearly shown when they are converted to PDF. However, all these are not conversion problems at all for Spire.PDF users.

Spire.PDF, as a PDF component allows its users to not only to convert images of commonly used formats to PDF document such as jpg, bmp, png, but also to convert gif, tif and ico images to PDF, which can be the most special feature during the conversion task of image to PDF. Besides, Spire.PDF supports to load images from stream and files on disk. These distinct characters, not have the slightest doubt, provides great convenience for developers.

Below shows the effect of converting image to PDF via Spire.PDF through a screenshot.

Image to PDF

Apart from helping you accomplish your image to PDF conversion task in a quick and fast way via C#, VB.NET, Spire.PDF also can Extract text and images from PDF files. That is to say, you never worry about where your images located, you can load them to PDF as well as extract from PDF. Please Download Spire.PDF before you start your work. Below steps are for you to convert your image to PDF with clear effect. The screenshot is displayed after the procedure.

Step1: Use C#/VB.NET to create a PDF document

In this step, you need to create a new PDF file first, then, add a section in the newly built PDF, at last, add a page in the section that you just added.

[C#]
// Create a pdf document with a section and page added.
 PdfDocument doc = new PdfDocument();
 PdfSection section = doc.Sections.Add();
 PdfPageBase page = doc.Pages.Add();

[VB.NET]
 ' Create a pdf document with a section and page added.
 Dim doc As New PdfDocument()
 Dim section As PdfSection = doc.Sections.Add()
 Dim page As PdfPageBase = doc.Pages.Add()

Step2: Load an image to PDF and set image location

First, load an image of any format among jpg, bmp, png, gif, tif and ico from system. A tiff image is loaded and its location is being set in this method.

[C#]
//Load a tiff image from system
 PdfImage image = PdfImage.FromFile(@"D:\images\bear.tif");
//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]
'Load a tif image from system
 Dim image As PdfImage = PdfImage.FromFile("D:\images\bear.tif")
 '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)

Step3: Save the image to PDF file and launch the file

[C#]
 //save and launch the file
 doc.SaveToFile("image to pdf.pdf");
 doc.Close();
 System.Diagnostics.Process.Start("image to pdf.pdf");
[VB.NET]
 'save and launch the file
 doc.SaveToFile("image to pdf.pdf")
 doc.Close()
 System.Diagnostics.Process.Start("image to pdf.pdf")
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.

Page 124 of 126