Friday, 23 May 2014 03:38

Convert HTML String to PDF in C#

Besides convert HTML URL to PDF and HTML file to PDF, now Spire.PDF starts to support converting HTML string to PDF. This article will show you how to convert HTML string into PDF file in C#. We support tables, text and Hyperlinks in the HTML strings. Please check the steps as below:

  • Download Spire.PDF for .NET (Version 3.0.27 above) and install it correctly. The Spire.PDF installation is clean, professional and wrapped up in a MSI installer.
  • Add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll".
  • Here comes to the codes:

Step 1: Create a new PDF document.

PdfDocument pdf = new PdfDocument();

Step 2: Set the layout and page setting

PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
//webBrowser load html whether Waiting
htmlLayoutFormat.IsWaiting = false;
//page setting
PdfPageSettings setting = new PdfPageSettings();
setting.Size = PdfPageSize.A4;

Step 3: Load the HTML string code and generate the PDF file.

string htmlCode = File.ReadAllText("..\\..\\2.html");

//use single thread to generate the pdf from above html code
Thread thread = new Thread(() =>
{ pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat);});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

Step 4: Save the file to PDF and preview it.

pdf.SaveToFile("output.pdf");
System.Diagnostics.Process.Start("output.pdf");

Please check the effective screenshot:

Convert HTML String to PDF in C#

Full codes:

using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;

namespace LoadFromHTML
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
            htmlLayoutFormat.IsWaiting = false;
            PdfPageSettings setting = new PdfPageSettings();
            setting.Size = PdfPageSize.A4;
            string htmlCode = File.ReadAllText("..\\..\\2.html");

            Thread thread = new Thread(() =>
            { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            pdf.SaveToFile("output.pdf");
            System.Diagnostics.Process.Start("output.pdf");
        }
    }
}
Published in Conversion

Spire.PDF is an easy-to-use and powerful .NET PDF library. It can do a lot of conversions, and one of them is converting PDF page to image. As to converting PDF page to image, it works conveniently and flexibly. It has 6 overloaded functions named SaveAsImage that can make sure you find one meeting your need.

You can use Spire.PDF to convert any specific page of PDF document to BMP and Metafile image. Check it here.

In this article, we will discuss conversion with specified resolution.

[C#]
public Image SaveAsImage(int pageIndex, int dpiX, int dpiY)
  • pageIndex: specify which page to convert, 0 indicates the first page.
  • dpiX: specify the resolution of x coordinate axis in PDF page when converting.
  • dpiX: specify the resolution of y coordinate axis in PDF page when converting.
[C#]
Image image = documemt.SaveAsImage(0, PdfImageType.Bitmap, false, 400, 400)

In the sample code, the size of PDF page is Width = 612.0, Height = 792.0. We set the resolution to 400, 400. And we will get an image with width = 3400, height = 4400.

Here is sample code:

[C#]
PdfDocument documemt = new PdfDocument();
documemt.LoadFromFile(@"..\..\EnglishText.pdf");
Image image = documemt.SaveAsImage(0, PdfImageType.Bitmap, false, 400, 400);
image.Save(@"..\..\result.jpg");
documemt.Close();

Effect Screentshot:

image with specified resolution

Published in Conversion
Tuesday, 12 November 2013 02:56

Convert Multipage Image to PDF in C#

For the function of converting image to PDF, Spire.PDF can handle it quickly and effectively. This .NET PDF library can not only convert images of commonly used formats to PDF document such as jpg, bmp, png, but also convert gif, tif and ico images to PDF. Just download it here.

To convert multipage image to a PDF file with Spire.PDF, just copy the following code to your application and call method ConvertImagetoPDF and you will get it done.

Step 1: Method to split multipage image

Spire.Pdf has a method called DrawImage to convert image to PDF. But it cannot handle multipage image directly. So before conversion, multipage image need to be split into several one-page images.

[C#]
Guid guid = image.FrameDimensionsList[0];
FrameDimension dimension = new FrameDimension(guid);
int pageCount = image.GetFrameCount(dimension);

This step is to get the total number of frames (pages) in the multipage image.

[C#]
image.SelectActiveFrame(dimension, i);

And this step is to select one frame of frames within this image object.

[C#]
image.Save(buffer, format);

Save the selected frame to the buffer.

Step 2: Convert image to PDF

After splitting multipage image, Spire.Pdf can draw these split images directly to PDF using method DrawImage.

[C#]
PdfImage pdfImg = PdfImage.FromImage(img[i])

Load image file as PdfImage.

[C#]
page.Canvas.DrawImage(pdfImg, x, 0, width, height);

Draw PdfImage to PDF. The only thing to do is to specify the location of image on PDF. Width and height is the size of area that image will be drawn on. Sometimes we need to scale up or down the size of the original size of image until it fit the PDF page. x and 0 locate the coordinate.

Check the effective screenshots for the original TIF file.

multi_images

The target PDF file:

multi_images_to_pdf

Full demo:

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

namespace ConvertMultipageImagetoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                ConvertImagetoPDF(@"..\..\Chapter1.tif");
            }
        }      

        public static void ConvertImagetoPDF(String ImageFilename)
        {
            using (PdfDocument pdfDoc = new PdfDocument())
            {
                Image image = Image.FromFile(ImageFilename);

                Image[] img = SplitImages(image, ImageFormat.Png);

                for (int i = 0; i < img.Length; i++)
                {
                    PdfImage pdfImg = PdfImage.FromImage(img[i]);
                    PdfPageBase page = pdfDoc.Pages.Add();
                    float width = pdfImg.Width * 0.3f;
                    float height = pdfImg.Height * 0.3f;
                    float x = (page.Canvas.ClientSize.Width - width) / 2;

                    page.Canvas.DrawImage(pdfImg, x, 0, width, height);
                }

                string PdfFilename = "result.pdf";
                pdfDoc.SaveToFile(PdfFilename);
                System.Diagnostics.Process.Start(PdfFilename);
            }
        }

        public static Image[] SplitImages(Image image, ImageFormat format)
        {
            Guid guid = image.FrameDimensionsList[0];
            FrameDimension dimension = new FrameDimension(guid);
            int pageCount = image.GetFrameCount(dimension);

            Image[] frames = new Image[pageCount];

            for (int i = 0; i < pageCount; i++)
            {
                using (MemoryStream buffer = new MemoryStream())
                {
                    image.SelectActiveFrame(dimension, i);
                    image.Save(buffer, format);
                    frames[i] = Image.FromStream(buffer);
                }
            }
            return frames;        
        }
    }
}
Published in Conversion
Thursday, 31 October 2013 08:17

Convert HTML to PDF with New Plugin

Converting HTML to PDF with C# PDF component is so important that we always try our best to improve our Spire.PDF better and better. We aim to make it is much more convenient for our developers to use. Now besides the previous method of converting HTML to PDF offered by Spire.PDF, we have a new plugin for html conversion to PDF. This section will focus on the new plugin of convert HTML to PDF. With this new plugin, we support to convert the HTML page with rich elements, such as HTTPS, CSS3, HTML5, JavaScript.

You need to download Spire.PDF and install it on your system, add Spire.PDF.dll as reference in the downloaded Bin folder thought the below path '..\Spire.PDF\Bin\NET4.0\Spire.PDF.dll'. And for gain the new plugin, you could get the new plugin from the download file directly: windows-x86.zip windows-x64.zip macosx_x64.zip linux_x64.tar.gz .

On Windows system, you need to unzip the convertor plugin package and copy the folder 'plugins' under the same folder of Spire.Pdf.dll. Before you use QT plugin for converting HTML to PDF, please ensure you have installed Microsoft Visual C++ 2015 Redistributable on your computer.

On Mac and Linux system, you need to copy the zip file under the system and then unzip the convertor plugin package there to use the plugins successfully.

C#  HtmlToPdf.zip and VB.NET  HtmlToPdfVB.zip, you could download and try it.

Calling the plugins is very simple, please check the below C# code for convert HTML to PDF.

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

namespace SPIREPDF_HTMLtoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            HtmlConverter.Convert("http://www.wikipedia.org/", "HTMLtoPDF.pdf",
                
                //enable javascript
                true,

                //load timeout
                100 * 1000,

                //page size
                new SizeF(612, 792),

                //page margins
                new PdfMargins(0, 0));
            System.Diagnostics.Process.Start("HTMLtoPDF.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.HtmlConverter.Qt

Module Module1

    Sub Main()
        HtmlConverter.Convert("http://www.wikipedia.org/", "HTMLtoPDF.pdf", True, 100 * 1000, New SizeF(612, 792), New PdfMargins(0, 0))
        System.Diagnostics.Process.Start("HTMLtoPDF.pdf")
    End Sub

End Module

Please check the effective screenshot as below:

HTML_to_PDF_c#

The following sample will focus on the new plugin of convert HTML string to PDF.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Pdf;
using System.IO;
using Spire.Pdf.HtmlConverter;
using System.Drawing;
namespace HTMLToPDFwithPlugins
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =@"<strong>This is a test for converting HTML string to PDF </strong>
                 <ul><li>Spire.PDF supports to convert HTML in URL into PDF</li>
                 <li>Spire.PDF supports to convert HTML string into PDF</li>
                 <li>With the new plugin</li></ul>";
         
            string outputFile = "ToPDF.pdf";

            Spire.Pdf.HtmlConverter.Qt.HtmlConverter.Convert(input,

            outputFile,
            //enable javascript
            true,
            //load timeout
            10 * 1000,
            //page size
            new SizeF(612, 792),
            //page margins
            new Spire.Pdf.Graphics.PdfMargins(0),
            //load from content type
            LoadHtmlType.SourceCode
            );
            System.Diagnostics.Process.Start(outputFile);
        }
    }
}

Effective screenshot:

HTML_to_PDF_c#

Published in Conversion

XPS is a format similar to PDF but uses XML in layout, appearance and printing information of a file. XPS format was developed by Microsoft and it is natively supported by the Windows operating systems. If you want to work with your PDF files on a Windows computer without installing other software, you can convert it to XPS format. Likewise, if you need to share a XPS file with a Mac user or use it on various devices, it is more recommended to convert it to PDF. This article will demonstrate how to programmatically convert PDF to XPS or XPS to PDF using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF 

Convert PDF to XPS in C# and VB.NET

Spire.PDF for .NET supports converting PDF to various file formats, and to achieve the PDF to XPS conversion, you just need three lines of core code. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Convert the PDF document to an XPS file using PdfDocument.SaveToFile (string filename, FileFormat.XPS) method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace ConvertPdfToXps
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load sample PDF document 
            pdf.LoadFromFile("sample.pdf");

            //Save it to XPS format 
            pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
            pdf.Close();
        }
    }
}

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Convert XPS to PDF in C# and VB.NET

Conversion from XPS to PDF can also be achieved with Spire.PDF for .NET. While converting, you can set to keep high quality image on the generated PDF file by using the PdfDocument.ConvertOptions.SetXpsToPdfOptions() method. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load an XPS file using PdfDocument.LoadFromFile(string filename, FileFormat.XPS) method or PdfDocument.LoadFromXPS() method.
  • While conversion, set the XPS to PDF convert options to keep high quality images using PdfDocument.ConvertOptions.SetXpsToPdfOptions() method.
  • Save the XPS file to a PDF file using PdfDocument.SaveToFile(string filename, FileFormat.PDF) method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace ConvertXPStoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample XPS file
            pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
            //pdf.LoadFromXPS("Sample.xps");

            //Keep high quality images when converting XPS to PDF
            pdf.ConvertOptions.SetXpsToPdfOptions(true);

            //Save the XPS file to PDF
            pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Apply for a Temporary License

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

Published in Conversion

PDF files have the advantage of being highly interactive and easy to transfer, but in certain cases, it is also necessary to convert PDF to images for embedding in web pages or displaying on some platforms that do not support PDF format. In this article, you will learn how to convert PDF to JPG, PNG or BMP image formats in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF 

Convert a Specific PDF Page to an Image in C# and VB.NET

Spire.PDF for .NET offers the PdfDocument.SaveAsImage() method to convert a particular page in PDF to an image. Then, you can save the image as a JPEG, PNG, BMP, EMF, GIF or WMF file. The following are the detailed steps.

  • Create a Document instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Convert a specific page to an image and set the image Dpi using PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) method.
  • Save the image as a PNG, JPG or BMP file using Image.Save(string filename, ImageFormat format) method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Imaging;

namespace PDFtoImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document
            pdf.LoadFromFile("E:\\Files\\input.pdf");

            //Convert the first page to an image and set the image Dpi
            Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500);

            //Save the image as a JPG file
            image.Save("ToJPG.jpg", ImageFormat.Jpeg);

            //Save the image as a PNG file
            //image.Save("ToPNG.png", ImageFormat.Png);

            //Save the image as a BMP file
            //image.Save("ToBMP.bmp", ImageFormat.Bmp);
        }
    }
}

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Convert an Entire PDF Document to Multiple Images in C# and VB.NET

If you want to convert the whole PDF document into multiple individual images, you can loop through all the pages in the PDF and then save them as JPG, PNG or BMP images. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Loop through all pages of the document and set the image Dpi when converting them to images using PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) method.
  • Save images as PNG files using Image.Save() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace PDFtoImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document
            pdf.LoadFromFile("input.pdf");

            //Loop through each page in the PDF
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                //Convert all pages to images and set the image Dpi
                Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);

                //Save images as PNG format to a specified folder 
                String file = String.Format("Image\\ToImage-{0}.png", i);
                image.Save(file, ImageFormat.Png);
              
            }
        }
    }
}

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Apply for a Temporary License

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

Published in Conversion
Monday, 29 July 2013 06:31

Convert XPS Files to PDF format in C#

XPS is short for XML Paper Specification developed by Microsoft, which is a specification for a page description language and a fixed-document format. It comes out by Microsoft’s initiative to associate file creation with reading in its Windows operating system. Like PDF, XPS plays a loyal role to preserve document with offering device-independent document appearance. Editing in XPS or in PDF seems difficult.

As a flexible and professional component, Spire.PDF for .NEToffers a large variety conversion, among which the conversion from XPS to PDF is one of its popular feature. In addition, Spire.PDF for .NET can be applied in WinForm, ASP.NET and Console Application.

The following code example shows how to convert XPS files to PDF document.

Step 1: Introduce a class named pdfDocument which is used to initialize a Spire.PDF.PdfDocument, and load a XPS file by calling the method of LoadForm File.

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(xpsFile,FileFormat.XPS);

Step 2: Only needs one row of simple code. Call the SavetoFile method of Spire.PDF.pdfDocument to save all the data as PDF formart.

[C#]
doc.SaveToFile(pdfFile, FileFormat.PDF);

After this code, run this application and you will see the PDF converted from XPS.

Screenshot before converting XPS to PDF:

Screenshot after converting XPS to PDF:

Published in Conversion
Wednesday, 30 March 2022 06:26

C#/VB.NET: Convert Images to PDF

Images are a device-friendly file format that can be easily shared across a variety of devices. However, in some circumstances, a more professional format such as PDF is needed to replace images. In this article, you will learn how to convert an image to PDF in C# and VB.NET using Spire.PDF for .NET.

Spire.PDF does not provide a straightforward method to convert images to PDF. But you could create a new PDF document and draw images at the specified locations of a certain page. Depending on whether to generate PDF in a page size equal to that of the image, this topic can be divided into the following two subtopics.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Add an Image to PDF at a Specified location

The following are the steps to add an image as a part of a new PDF document using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Set the page margins using PdfDocument.PageSettings.SetMargins() method.
  • Add a page using PdfDocument.Pages.Add() method
  • Load an image using Image.FromFile() method, and get the image width and height.
  • If the image width is larger than the page (the content area) width, resize the image to make it to fit to the page width.
  • Create a PdfImage object based on the scaled image or the original image.
  • Draw PdfImage object on the first page at (0, 0) using PdfPageBase.Canvas.DrawImage() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

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

            //Set the margins
            doc.PageSettings.SetMargins(20);

            //Add a page
            PdfPageBase page = doc.Pages.Add();

            //Load an image 
            Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\announcement.jpg");

            //Get the image width and height
            float width = image.PhysicalDimension.Width;
            float height = image.PhysicalDimension.Height;
       
            //Declare a PdfImage variable
            PdfImage pdfImage;

            //If the image width is larger than page width
            if (width > page.Canvas.ClientSize.Width)
            {
                //Resize the image to make it to fit to the page width
                float widthFitRate = width / page.Canvas.ClientSize.Width;
                Size size = new Size((int)(width / widthFitRate), (int)(height / widthFitRate));
                Bitmap scaledImage = new Bitmap(image, size);

                //Load the scaled image to the PdfImage object
                pdfImage = PdfImage.FromImage(scaledImage);
            } else
            {
                //Load the original image to the PdfImage object
                pdfImage = PdfImage.FromImage(image);
            }

            //Draw image at (0, 0)
            page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);

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

C#/VB.NET: Convert Images to PDF

Convert an Image to PDF with the Same Width and Height

The following are the steps to convert an image to PDF with the same page width and height as the image using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.PageSettings.SetMargins() method.
  • Load an image using Image.FromFile() method, and get the image width and height.
  • Add a page to PDF based on the size of the image using PdfDocument.Pages.Add() method.
  • Create a PdfImage object based on the image.
  • Draw PdfImage object on the first page from the coordinate (0, 0) using PdfPageBase.Canvas.DrawImage() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

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

            //Set the margins to 0
            doc.PageSettings.SetMargins(0);

            //Load an image 
            Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\announcement.jpg");

            //Get the image width and height
            float width = image.PhysicalDimension.Width;
            float height = image.PhysicalDimension.Height;

            //Add a page of the same size as the image
            PdfPageBase page = doc.Pages.Add(new SizeF(width, height));

            //Create a PdfImage object based on the image
            PdfImage pdfImage = PdfImage.FromImage(image);
 
            //Draw image at (0, 0) of the page
            page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);

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

C#/VB.NET: Convert Images to PDF

Apply for a Temporary License

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

Published in Conversion
Monday, 01 August 2022 03:47

C#/VB.NET: Convert Text Files to PDF

A text file is a type of computer file that contains plain text. It can be viewed on almost any computer but has very basic and limited functionalities. If you would like to perform more manipulations on text files, such as inserting annotations or form fields, you can convert them to PDF. In this article, we will demonstrate how to convert text files to PDF in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Convert Text Files to PDF in C# and VB.NET

The following are the main steps to convert a text file to PDF using Spire.PDF for .NET:

  • Read the text in the text file into a string object using File.ReadAllText() method.
  • Create a PdfDocument instance and add a page to the PDF file using PdfDocument.Pages.Add() method.
  • Create a PdfTextWidget instance from the text.
  • Draw the text onto the PDF page using PdfTextWidget.Draw() method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.IO;

namespace ConvertTextToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Read the text from the text file
            string text = File.ReadAllText(@"Input.txt");

            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Add a page
            PdfPageBase page = pdf.Pages.Add();

            //Create a PdfFont instance
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);

            //Create a PdfTextLayout instance
            PdfTextLayout textLayout = new PdfTextLayout();
            textLayout.Break = PdfLayoutBreakType.FitPage;
            textLayout.Layout = PdfLayoutType.Paginate;

            //Create a PdfStringFormat instance
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Justify;
            format.LineSpacing = 20f;

            //Create a PdfTextWidget instance from the text
            PdfTextWidget textWidget = new PdfTextWidget(text, font, PdfBrushes.Black);
            //Set string format
            textWidget.StringFormat = format;

            //Draw the text at the specified location of the page
            RectangleF bounds = new RectangleF(new PointF(10, 25), page.Canvas.ClientSize);
            textWidget.Draw(page, bounds, textLayout);

            //Save the result file
            pdf.SaveToFile("TextToPdf.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Convert Text Files to PDF

Apply for a Temporary License

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

Published in Conversion
Monday, 21 February 2022 08:45

C#/VB.NET: Convert HTML to PDF

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

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

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF 

Download Plugin

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

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

C#/VB.NET: Convert HTML to PDF

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

C#/VB.NET: Convert HTML to PDF

Convert a URL to PDF with QT Plugin

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

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

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

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

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

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

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

Convert an HTML String to PDF with QT Plugin

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

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

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

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

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

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

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

            //Set plugin path
            HtmlConverter.PluginPath = pluginPath;

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

Convert a URL to PDF Without Plugin

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

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

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

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

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

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

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

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

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

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

Convert an HTML String to PDF Without Plugin

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

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

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

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

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

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

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

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

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

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

Apply for a Temporary License

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

Published in Conversion
Page 3 of 3