Monday, 10 September 2012 06:41

Add PDF Hyperlink in WPF

This section will introduce a solution to add two types of hyperlinks in PDF document via a WPF PDF component. One is a hyperlink directly displayed as url address in the PDF file, suppose it is named Hyperlink1; The other is a hyperlink in place of text, you can call it hyperlink2. Both of the two hyperlinks can automatically take you to a webpage, a file or an image when you click them. Before you start, it is very necessary to know some information of this PDF component

Spire.PDF for WPF enables you to directly generate, read, write and manipulate PDF files in your WPF applications without installing Adobe Acrobat or any third party library. Using Spire.PDF for WPF, you can easily add PDF hyperlink by three key steps. Please Download Spire.PDF for WPF and view the effective screenshot of this task as below picture:

Add Hyperlink in PDF

Step 1: Set the link location in PDF page.

After you loading an existing PDF file or creating a new PDF file(a PDF file is imported from system in this step), please set the approximate location of hyperlink in PDF page by calling the Spire.Pdf.PdfPageBase: Canvas.ClientSize.Height.

            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\image to pdf.pdf");
            PdfPageBase page = doc.Pages[0];
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Verdana", 17));
            float space = font.Height * 0.75f;
            float y = page.Canvas.ClientSize.Height*0.6f - margin.Bottom + space;
           Dim doc As New PdfDocument()
	   doc.LoadFromFile("D:\michelle\my file\image to pdf.pdf")
	   Dim page As PdfPageBase = doc.Pages(0)
	   Dim unitCvtr As New PdfUnitConvertor()
	   Dim margin As New PdfMargins()
	   margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	   margin.Bottom = margin.Top
	   margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	   margin.Right = margin.Left
	   Dim font As New PdfTrueTypeFont(New Font("Verdana", 17))
	   Dim space As Single = font.Height * 0.75F
	   Dim y As Single = page.Canvas.ClientSize.Height * 0.6F - margin.Bottom + space

Step 2: Add Hyperlink1 in PDF.

In this step, you can draw a string in PDF page by calling Spire.Pdf. PdfPageBase method: PdfPageBase.Canvas.DrawString(string s, PdfFontBase font, PdfBrush brush, float x, float y, PdfStringFormat format) method. As the string format is a url address, a link can be drawn. Also by calculating the string width of label, link and PDF page, both link label location and link location can be set. In this method, link label and link are set in the middle.

            String label = "Image Source: ";
            PdfStringFormat format = new PdfStringFormat();
            format.MeasureTrailingSpaces = true;
            float x1 = font.MeasureString(label, format).Width;
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Verdana", 17, System.Drawing.FontStyle.Bold));
            String url1 = "";
            float x2 = font2.MeasureString(url1, format).Width;
            float x =( page.Canvas.ClientSize.Width-x1-x2)/2;
            page.Canvas.DrawString(label, font, PdfBrushes.DeepSkyBlue, x, y, format);
            x += x1;
            page.Canvas.DrawString(url1, font2, PdfBrushes.DeepSkyBlue, x, y);
            y = y + font2.MeasureString(url1).Height;
           Dim label As [String] = "Image Source: "
	   Dim format As New PdfStringFormat()
	   format.MeasureTrailingSpaces = True
	   Dim x1 As Single = font.MeasureString(label, format).Width
	   Dim font2 As New PdfTrueTypeFont(New Font("Verdana", 17, System.Drawing.FontStyle.Bold))
	   Dim url1 As [String] = ""
	   Dim x2 As Single = font2.MeasureString(url1, format).Width
	   Dim x As Single = (page.Canvas.ClientSize.Width - x1 - x2) / 2
	   page.Canvas.DrawString(label, font, PdfBrushes.DeepSkyBlue, x, y, format)
	   x += x1
	   page.Canvas.DrawString(url1, font2, PdfBrushes.DeepSkyBlue, x, y)
	   y = y + font2.MeasureString(url1).Height

Step 3: Add hyperlink 2 in place of text.

Use the method in step2 to draw a link label and add hyperlink2 in place of text by the method Spire.Pdf.Annotations. PdfTextWebLink to set link properties such as text, url and so on. Finally, invoke DrawTextWebLink(PdfCanvas graphics, PointF location) method to draw the PDF hyperlink in place of text.

            label = "Simple Link: ";
            x -= x1;
            page.Canvas.DrawString(label, font, PdfBrushes.DarkViolet, x, y, format);
            float xoffset2 = font.MeasureString(label, format).Width;
            x += xoffset2;
            String text = "e-iceblue";
            PdfTextWebLink link2 = new PdfTextWebLink();
            link2.Text = text;
            link2.Url = url1;
            link2.Font = font2;
            link2.Brush = PdfBrushes.DarkViolet;
            link2.DrawTextWebLink(page.Canvas, new PointF(x, y));
        label = "Simple Link: "
	x -= x1
	page.Canvas.DrawString(label, font, PdfBrushes.DarkViolet, x, y, format)
	Dim xoffset2 As Single = font.MeasureString(label, format).Width
	x += xoffset2
	Dim text As [String] = "e-iceblue"
	Dim link2 As New PdfTextWebLink()
	link2.Text = text
	link2.Url = url1
	link2.Font = font2
	link2.Brush = PdfBrushes.DarkViolet
	link2.DrawTextWebLink(page.Canvas, New PointF(x, y))

Spire.PDF is a PDF document creation component that enables your WPF applications to read, write and manipulate PDF documents without using Adobe Acrobat. Now, the new version added Silverlight platform which makes it more powerful.

Monday, 10 September 2012 05:39

Set PDF Properties in Silverlight

This section is designed to introduce the quickest solution to set PDF properties in Silverlight. As is known to all, PDF property shows the basic information of a PDF document, such as PDF document name, title, author, subject, keywords, creation/ modify date and so on. The vital reason to call it the quickest solution is that all the PDF properties referred above can be respectively set by only one line of key code via a Silverlight PDF component.

Spire.PDF for Silverlight is a PDF component, which enables you to create, read, write and manipulate PDF document in your Silverlight applications. Using Spire.PDF for Silverlight, you can set your PDF properties by calling the method: public PdfDocumentInformation DocumentInformation. Please preview the effect of your PDF property setting as below picture:

Set PDF Properties

Now, please Download Spire.PDF for Silverlight and then, view the key code below.

Sample Code:

document.DocumentInformation.Title = "image to PDF";
document.DocumentInformation.Author = "E-iceblue";
document.DocumentInformation.Subject = "convert image to PDF";
document.DocumentInformation.Producer = "Spire.PDF";
document.DocumentInformation.Keywords = "C# JPG/PNG/BMP/GIF/TIF to PDF";
document.DocumentInformation.ModificationDate = new DateTime(2012, 9, 10, 14, 30, 50);
document.DocumentInformation.Title = "image to PDF"
document.DocumentInformation.Author = "E-iceblue"
document.DocumentInformation.Subject = "convert image to PDF"
document.DocumentInformation.Producer = "Spire.PDF"
document.DocumentInformation.Keywords = "C# JPG/PNG/BMP/GIF/TIF to PDF"
document.DocumentInformation.ModificationDate = New DateTime(2012, 9, 10, 14, 30, 50)

Spire.PDF for Silverlight is a PDF Silverlight component that enables your Silverlight applications to read, write and manipulate PDF documents without using Adobe Acrobat.

Thursday, 30 August 2012 03:30

Insert Image in Word Document in WPF

Word Image can make one document more interesting and impressive. Sometimes, image can be used explain contents. For example, if one document focuses on describing appearance one kind of birds, readers can learn more clearly with a bird picture.

Spire.Doc for WPF, a professional component to manipulate Word documents with WPF, enables users to insert image in Word with WPF. And this guide will show a method about how to insert image Word in WPF quickly.

Users can invoke paragraph.AppendPicture(image) method to insert image in Word directly. If you want to set image height/width to make picture display appropriately in document, you can use Height and Width property provided by DocPicture class which Spire.Doc for .NET offers. Below, there is the result after inserting image in Word.

Insert Word Image

Download and install Spire.Doc for WPF. Then, add a button in MainWindow. Double click this button and use the following code to insert image in Word.

Code Sample:

          //Create Document
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph Imageparagraph = section.AddParagraph();

            //Insert Image
            Image image = Image.FromFile(@"E:\work\Documents\Image\street.jpg");
            DocPicture picture =Imageparagraph.AppendPicture(image);

            //Set Image
            picture.Height = 360;
            picture.Width = 525;
        'Create Document
        Dim document As New Document()
        Dim section As Section = document.AddSection()
        Dim Imageparagraph As Paragraph = section.AddParagraph()

        'Insert Image
        Dim image As Image = image.FromFile("E:\work\Documents\Image\street.jpg")
        Dim picture As DocPicture = Imageparagraph.AppendPicture(image)

        'Set Image
        picture.Height = 360
        picture.Width = 525

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

Thursday, 30 August 2012 01:41

Clearly Convert RTF to PDF in WPF

Whatever solution you use to convert RTF to PDF before, the solution that will be introduced is the easiest method to clearly realize your RTF to PDF conversion task. The whole process can be accomplished through three lines of key code in your WPF application via a Word component Spire.Doc for WPF.

Spire.Doc for WPF, different from RTF to PDF converters, is a WPF Word component, which can generate, read, write and modify word documents in your WPF applications. Apart from converting RTF to PDF, Spire.Doc for WPF can convert word to many other commonly used formats such as PDF, HTML, Text, XML, Image and so on. Please first preview the effective screenshot of the target PDF file:


Now, please download Spire.Doc for WPF and convert your RTF to PDF by the code below:

using Spire.Doc;
namespace WPFRTFtoPDF
      public partial class MainWindow : Window
        public MainWindow()

        private void button1_Click(object sender, RoutedEventArgs e)
            Document doc = new Document();
            doc.LoadFromFile(@"..\WPFRTFtoPDF.rtf", FileFormat.Rtf);
            doc.SaveToFile("test.pdf", FileFormat.PDF);
Imports Spire.Doc
Namespace WPFRTFtoPDF
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			Dim doc As New Document()
			doc.LoadFromFile("..\WPFRTFtoPDF.rtf", FileFormat.Rtf)
			doc.SaveToFile("test.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace

For comparison, I put the original RTF file below:


Spire.Doc is a standalone word component, which enables users to perform a wide range of word document processing tasks in WPF, .NET and Silverlight without installing MS Word on system.

Wednesday, 29 August 2012 07:45

Find and Highlight Text in Word in WPF

Word Find function can enable users to search for specific text or phrase quickly. Generally speaking, the found text will be highlighted automatically in order to distinguish from other contents. Also, users can format found text, such as set it as italic, bold etc.

Spire.Doc for WPF, a professional WPF component on manipulating Word, enables users to find and highlight text in Word with WPF. With this Word WPF component, developers can invoke doc.FindAllString(text string, bool caseSensitive, bool wholeWord) method directly to find text in Word. And for highlighting found text, developers need Firstly, use TextSelection, the class Spire.Doc for WPF provides, to save found string. Then, use foreach sentence to get each selection in this TextSelection. Finally, set HighlightColor, one properties of TextRange.CharacterFormat, for text in selection.

Below, the screenshot shows a Word document whose specified text has be found and highlighted.

Find and Highlight Word Text

Download and install Spire.Doc for WPF and then use the codes below to Find and Highlight Text in Word

Code Sample:

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.Windows;

namespace WpfApplication1
    public partial class MainWindow : Window
        public MainWindow()
        private void button1_Click(object sender, RoutedEventArgs e)

            //Load Document
            Document doc = new Document();
            doc.LoadFromFile(@"E:\work\Documents\A GOOD MAN IS HARD TO FIND.docx");

            //Find Text
            TextSelection[] textSelections = doc.FindAllString("Bailey", true, true);

            //Highlight Text
            foreach (TextSelection selection in textSelections)
                selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green;

            //Save Document
            doc.SaveToFile("FindText.docx", FileFormat.Docx2010);

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports System.Windows

Namespace WpfApplication1
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
		End Sub
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)

			'Load Document
			Dim doc As New Document()
			doc.LoadFromFile("E:\work\Documents\A GOOD MAN IS HARD TO FIND.docx")

			'Find Text
			Dim textSelections As TextSelection() = doc.FindAllString("Bailey", True, True)

			'Highlight Text
			For Each selection As TextSelection In textSelections
				selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green

			'Save Document
			doc.SaveToFile("FindText.docx", FileFormat.Docx2010)
		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.

Friday, 24 August 2012 02:43

Split Huge PDF Document by Pages in WPF

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

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

Split PDF Document

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


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

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

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

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

        String pattern = "SplitDocument-{0}.pdf";
        String lastPageFileName= String.Format(pattern, doc.Pages.Count - 1);
	Dim pattern As String = "SplitDocument-{0}.pdf"
	Dim lastPageFileName As String = String.Format(pattern, doc.Pages.Count - 1)

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

Thursday, 23 August 2012 06:30

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

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

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

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

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

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

Insert Word OLE Objects

Code Detail:

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

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

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

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

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

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

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

Insert Word OLE Objects

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

Thursday, 16 August 2012 01:00

Create PDF Digital Signature in WPF

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

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

Create Digital Signature

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

Core Code:

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

Encrypt PDF for Security in WPF

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

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

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

Step1: Set PDF password size

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

doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit

Step 2: Secure PDF file by passwords

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

doc.Security.OwnerPassword = "e-iceblue";
doc.Security.UserPassword = "pdf";
doc.Security.OwnerPassword = "e-iceblue"
doc.Security.UserPassword = "pdf"

Step 3: Restrict certain permissions of user password

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

Encrypt PDF Document

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

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

doc.Security.Permissions = PdfPermissionsFlags.AccessibilityCopyContent | PdfPermissionsFlags.Print | PdfPermissionsFlags.EditAnnotations;
doc.Security.Permissions = PdfPermissionsFlags. AccessibilityCopyContent Or PdfPermissionsFlags. Print Or PdfPermissionsFlags.EditAnnotations

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

Encrypt PDF Document

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

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

Image to PDF

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

Step 1: Load an image file from system

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

//Load a jpg image from system
PdfImage image = PdfImage.FromFile(@"..\sky.jpg");
'Load a jpg image from system
Dim image As PdfImage = PdfImage.FromFile("..\sky.jpg") 

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

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

  //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);
'Set image display location and size in PDF
Dim widthFitRate As Single = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width
Dim heightFitRate As Single = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height
Dim fitRate As Single = Math.Max(widthFitRate, heightFitRate)
Dim fitWidth As Single = image.PhysicalDimension.Width / fitRate
Dim fitHeight As Single = image.PhysicalDimension.Height / fitRate
page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight)

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

Image to PDF

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