Thursday, 16 October 2014 08:19

Convert PDF to Image with High Quality in WPF

Why we convert PDF to image?

  • PDF requires an external application like Adobe Acrobat Reader while image does not.
  • Browsers have the built-in capability to display images while handling PDF documents requires an external application or plug-in.

So, in some specific cases converting your PDF documents to an image format like PNG or JPEG could be the solution we are looking for.

How to convert PDF to image in WPF?

For developers, we can easily render PDF pages to images with high quality by using Spire.PDF for WPF, which is a professional PDF component providing tons of useful methods to manipulate PDF document in your WPF applications. Now, follow the below steps to achieve this purpose.

Detailed steps:

Step 1: Create a new project by choosing WPF Application in Visual Studio, add a button in MainWindow, double click the button to write code.

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
}

Step 2: Create a new instance of Spire.Pdf.Document and load the sample PDF file.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("sample.pdf");

Step 3: To convert PDF to image, we need firstly save PDF pages as BitmapSource by calling the method pdf.SaveAsImage, then convert BitmapSource to Bitmap, then save the Bitmap as image with a specified format using Image.Save().

               BitmapSource source;
            Bitmap bmp;

            for(int i=0;i<pdf.Pages.Count;i++)
            {
                source = pdf.SaveAsImage(i);
                bmp = SourceToBitmap(source);
                bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png);
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {
            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }

Output of the first page:

Convert PDF to Image with High Quality in WPF

Full code:

[C#]
using Spire.Pdf;

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("1.pdf");

            BitmapSource source;
            Bitmap bmp;

            for(int i=0;i<pdf.Pages.Count;i++)
            {
                source = pdf.SaveAsImage(i);
                bmp = SourceToBitmap(source);
                bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png);
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {
            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }

    }
}
Published in Program Guide WPF
Thursday, 09 January 2014 08:32

How to Add PDF Text Watermark in WPF

Watermark is a recognizable text or image that appears under document text. A watermark is useful in the examination of paper because it can be widely used for trademarks, locations and so on. This article aims at introducing how to add PDF text watermark for WPF through a simple WPF PDF API Spire.PDF for WPF. Also it can implement PDF watermark by image.

First we need to complete the preparatory work:

  • Download the latest Spire.PDF and install it on your machine.
  • Add the Spire.PDF.WPF.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.PDF as namespace.

Here comes to the explanation of the code.

Step 1: Create an instance of Spire.PDF.Document

[C#]
PdfDocument doc = new PdfDocument();

Step 2: Load the file base on a specified file path

[C#]
doc.LoadFromFile(@"..\..\Sample1.pdf");

Step 3: Add the text watermark to the first page

[C#]
PdfPageBase page = doc.Pages[0];
PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width/2, page.Canvas.ClientSize.Height/3));
brush.Graphics.SetTransparency(0.3f);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(-45);
brush.Graphics.DrawString("Spire.Pdf Demo",new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0,new PdfStringFormat(PdfTextAlignment.Center));
brush.Graphics.Restore();
brush.Graphics.SetTransparency(1);
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));

Step 4: Save the PDF file

[C#]
doc.SaveToFile("TextWaterMark.pdf");

Full code:

[C#]
private void button1_Click(object sender, RoutedEventArgs e)
 {
  PdfDocument doc = new PdfDocument();
  doc.LoadFromFile(@"..\..\Sample1.pdf");
  PdfPageBase page = doc.Pages[0];
  PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width/2, page.Canvas.ClientSize.Height/3));
  brush.Graphics.SetTransparency(0.3f);
  brush.Graphics.Save();
  brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
  brush.Graphics.RotateTransform(-45);
  brush.Graphics.DrawString("Spire.Pdf Demo",new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
  brush.Graphics.Restore();
  brush.Graphics.SetTransparency(1);
  page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
  doc.SaveToFile("TextWaterMark.pdf");          
 }

Effect screenshot:

add pdf text watermark for wpf

Published in Program Guide WPF
Friday, 22 February 2013 03:40

Delete PDF Page in WPF

This section is designed to provide a solution for developers on how to delete PDF page for WPF via this PDF library Spire.PDF for WPF.

Spire.PDF for WPF enables users to delete any PDF page only by one line of code: RemoveAt(int index). As you see, there is only one parameter in this method. This parameter determines which page will be deleted in PDF file. Now let us see the whole task in detail.

Delete PDF Page for WPF

Step 1: Prepare a template PDF File

I pick a PDF file from my system and it has 73 pages, we can see it below:

Delete PDF Page

Step 2: Download and Install Spire.PDF for WPF

Spire.PDF for WPF is a PDF component applied in WPF applications. It enables developers to create, read, edit and handle PDF files with fast speed. Here you can download Spire.PDF for WPF. After installing it on system, Spire.PDF for WPF will run in evaluation mode. This evaluation mode has no time limit and has no bad influence on performing the task.

Step 3: Start a new Project and Add References

Start your Visual Studio and create a new project in Visual C# WPF Application or VB。NET WPF Application. Here is an example of Visual C# in WPF Application. Please do not forget to add a button in the MainWindow.

We will use Spire.PDF for WPF, so we have to add Spire.Pdf for Wdf.dll and Spire.License.dll in our project in Bin folder. The detail Path is "..\Spire.Pdf\Bin\WPF4.0\ Spire.Pdf.Wpf.dll".

Step 4: Delete PDF Page

Below is the complete code in my project:

[C#]
//Initialize a new instance of PdfDocument
PdfDocument document = new PdfDocument();
//Open a template PDF file
document.LoadFromFile(@"..\Report.pdf");
//Remove the second Page
document.Pages.RemoveAt(1);
//Save the PDF file to disk
document.SaveToFile("DeletePDFPage.pdf");
//Launch the PDF file
System.Diagnostics.Process.Start("DeletePDFPage.pdf ");
[VB.NET]
'Initialize a new instance of PdfDocument
Dim document As New PdfDocument()
'Open a template PDF file
document.LoadFromFile("..\Report.pdf")
'Remove the second Page
document.Pages.RemoveAt(1)
'Save the PDF file to disk
document.SaveToFile("DeletePDFPage.pdf")
'Launch the PDF file
System.Diagnostics.Process.Start("DeletePDFPage.pdf ")

Output PDF File

After executing above code, the second page of the template PDF file has been deleted, and there are only 72 pages in the target PDF file, we can see here:

Delete PDF Page

In this section, I have expounded the solution on how to delete PDF page in WPF application. I wish it can help you and give you some insight on your development.

Spire.PDF for WPF is a PDF component which is designed to meet customers’ requirements on programming with high efficiency and reliability.

We welcome any kind of queries, comments and advices at E-iceblue Forum. Our professionals will be there to give prompt reply.

Published in Program Guide WPF
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.

[C#]
            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;
[VB.NET]
           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.

[C#]
            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 = "http://www.e-iceblue.com";
            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;
[VB.NET]
           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] = "http://www.e-iceblue.com"
	   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.

[C#]
            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));
[VB.NET]
        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.

Published in Program Guide WPF
Friday, 24 August 2012 02:43

Split Huge PDF Document by Pages in WPF

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

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

Split PDF Document

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

doc.Split(pattern):

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

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

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

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

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

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

Published in Program Guide WPF
Thursday, 16 August 2012 01:00

Create PDF Digital Signature in WPF

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

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

Create Digital Signature

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

Core Code:

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

Encrypt PDF for Security in WPF

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

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

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

Step1: Set PDF password size

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

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

Step 2: Secure PDF file by passwords

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

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

Step 3: Restrict certain permissions of user password

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

Encrypt PDF Document

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

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

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

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

Encrypt PDF Document

Published in Program Guide WPF

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

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

Image to PDF

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

Step 1: Load an image file from system

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

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

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

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

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

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

Image to PDF

Published in Program Guide WPF
Wednesday, 08 August 2012 01:06

Convert Webpage to PDF in WPF

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

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

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

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

Webpage to PDF

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

[C#]
using Spire.Pdf;

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

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

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

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

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

Published in Program Guide WPF
Wednesday, 01 August 2012 03:15

Convert Text to PDF in WPF

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

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

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

Text to PDF

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

Step1: Read all text information to s string

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

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

Step2: Draw string to PDF document with custom layout.

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

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

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

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

Published in Program Guide WPF
Page 2 of 3