Wednesday, 19 June 2024 08:10

C#: Convert PDF to TIFF or TIFF to PDF

PDF files are widely used for sharing and viewing documents across different platforms, while TIFF files are preferred for storing high-quality images with detailed graphics or photographs. Converting a PDF file to TIFF can maintain the quality of images within the file. Similarly, converting a TIFF image to PDF ensures that the image can be easily viewed, shared, and printed without compatibility issues. In this article, you will learn how to programmatically convert PDF to TIFF or TIFF to PDF in C# 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 TIFF in C#

The TIFF format allows multiple images to be stored in a single file. With Spire.PDF for .NET, you can convert each page of a PDF file into a separate image, and then call the custom method JoinTiffImages() to combine these images and save them as a single TIFF image.

The following are the steps to convert a PDF into a multi-page TIFF file using C#.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Call custom method SaveAsImage() to convert each page of the PDF to a separate image.
  • Call custom method JoinTiffImages() to merge the converted images into a multi-page TIFF image.
  • C#
using System;
using System.Drawing;
using System.Drawing.Imaging;
using Spire.Pdf;

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

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

            //Convert PDF pages to images
            Image[] images = SaveAsImage(pdf);

            //Combine the images and save them as a multi-page TIFF file
            JoinTiffImages(images, "result.tiff", EncoderValue.CompressionLZW);
        }

        private static Image[] SaveAsImage(PdfDocument document)
        {
            //Create a new image array
            Image[] images = new Image[document.Pages.Count];

            //Iterate through all pages in the document
            for (int i = 0; i < document.Pages.Count; i++)
            {
                //Convert a specific page to an image
                images[i] = document.SaveAsImage(i);
            }
            return images;
        }

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            //Get the image encoders
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
            for (int j = 0; j < encoders.Length; j++)
            {
                //Find the encoder that matches the specified MIME type
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
        }

        public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
        {
            //Set the encoder parameters 
            Encoder enc = Encoder.SaveFlag;
            EncoderParameters ep = new EncoderParameters(2);
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);

            //Get the first image
            Image pages = images[0];
            //Initialize a frame
            int frame = 0;
            //Get an ImageCodecInfo object for processing TIFF image codec information
            ImageCodecInfo info = GetEncoderInfo("image/tiff");

            //Iterate through each Image
            foreach (Image img in images)
            {
                //If it's the first frame, save it to the output file with specified encoder parameters
                if (frame == 0)
                {
                    pages = img;
                    pages.Save(outFile, info, ep);
                }

                else
                {
                    //Save the intermediate frames
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                    pages.SaveAdd(img, ep);
                }
                //If it's the last frame, flush the encoder parameters and close the file
                if (frame == images.Length - 1)
                {
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
        }
    }
}

C#: Convert PDF to TIFF or TIFF to PDF

Convert TIFF to PDF in C#

To convert a multi-page TIFF image to a PDF file, you need to convert each frame of the TIFF image to a separate PDF image. Then draw each image at a specified location on a PDF page through the PdfPageBase.Canvas.DrawImage() method.

The following are the steps to convert a TIFF image to a PDF file using C#.

  • Create a PdfDocument object.
  • Load a TIFF image using Image.FromFile() method.
  • Call custom method SplitTiffImage() to split the TIFF image into separate images.
  • Iterate through the split images, and then convert each into a PDF image.
  • Add a page to the PDF document using PdfDocument.Pages.Add() method.
  • Draw the PDF image at a specified location on the page using PdfPageBase.Canvas.DrawImage() method.
  • Save the result PDF file using PdfDocument.SaveToFile() method.
  • C#
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Spire.Pdf;
using Spire.Pdf.Graphics;

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

            //Load a TIFF image
            Image tiffImage = Image.FromFile("result.tiff");

            //Split the Tiff image into separate images
            Image[] images = SplitTiffImage(tiffImage);

            //Iterate through the images
            for (int i = 0; i < images.Length; i++)
            {
                //Convert a specified image into a PDF image
                PdfImage pdfImg = PdfImage.FromImage(images[i]);

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

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

                //Draw the image at a specified location on the page
                page.Canvas.DrawImage(pdfImg, 0, 0, width, height);
            }

            //Save the result file
            pdf.SaveToFile("TiffToPdf.pdf");
        }

        public static Image[] SplitTiffImage(Image tiffImage)
        {
            //Get the number of frames in the Tiff image
            int frameCount = tiffImage.GetFrameCount(FrameDimension.Page);
            //Create an image array to store the split tiff images
            Image[] images = new Image[frameCount];
            //Gets the GUID of the first frame dimension
            Guid objGuid = tiffImage.FrameDimensionsList[0];
            //Create a FrameDimension object
            FrameDimension objDimension = new FrameDimension(objGuid);

            //Iterate through each frame
            for (int i = 0; i < frameCount; i++)
            {
                //Select a specified frame
                tiffImage.SelectActiveFrame(objDimension, i);
                //Save the frame in TIFF format to a memory stream
                MemoryStream ms = new MemoryStream();
                tiffImage.Save(ms, ImageFormat.Tiff);
                //Load an image from memory stream
                images[i] = Image.FromStream(ms);
            }
            return images;
        }
    }
}

C#: Convert PDF to TIFF or TIFF 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
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
Monday, 12 June 2023 07:27

Convert PDF to Images in C# | .NET

Converting PDF files to images is a common requirement for applications that involve document previews, thumbnails generation, or PDF content archiving. For .NET developers, the Spire.PDF library offers a robust and efficient way to achieve this PDF to image conversion with high fidelity. Its key advantages include:

  • High-Fidelity Rendering: Preserve original layouts and graphics.
  • Multi-Format Support: Export to PNG, JPEG, BMP, TIFF, and more.
  • Cross-Platform: Works with .NET Framework, .NET Core, and .NET 6+.

Visual guide for converting PDF to images Using C#

In this guide, you’ll learn how to use the Spire.PDF for .NET library to convert PDF to JPG or PNG images in C#, with installation guide, practical code snippets, and conversion optimization tips.

Install the PDF to Image Converter Library

Before you can start using C# to convert PDF to PNG or PDF to JPG, it’s necessary to install the Spire.PDF for .NET library first. You can do this via NuGet Package Manager:

  • Open your project in Visual Studio
  • Go to “Tools > NuGet Package Manager > Manage NuGet Packages for Solution”
  • Search for "Spire.PDF"
  • Select and install the package

Alternatively, use the Package Manager Console:

PM> Install-Package Spire.PDF

Once installed, you're ready to start writing code to handle PDF to image conversions.

Convert PDF to JPG Images in C#: Basic Example

The SaveAsImage(int pageIndex, PdfImageType type) method of the PdfDocument class can be used to convert a specified PDF page to an image. The two parameters are:

  1. pageIndex (Int32)
  • Description: The index of the PDF page to be converted (page index starts from 0).
  • Example:
    • 0 = First page
    • 1 = Second page
  1. type (PdfImageType)
  • Description: Specifies the type of the PdfImage.
  • Enum Values:
    • Bitmap
    • Metafile

The following code demonstrates how to convert the first page of a PDF to a JPEG image using Spire.PDF:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Imaging;

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

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

            // Convert the first page to a bitmap image
            Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap);

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

            // Disposes PDF resources
            pdf.Dispose();
        }
    }
}

Convert a PDF page to a JPG image

Advanced PDF to Image Conversion Options

1. Set Image Resolution

Spire.PDF offers another overload of the SaveAsImage() method that takes four parameters: the page index, image type, horizontal (dpiX) and vertical (dpiY) resolution. This allows you to control the quality and size of the output image by customizing the DPI settings.

The following code example converts the first page of a PDF to a high-resolution PNG image (300 DPI):

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("input.pdf");

            // Convert the first page to an image and with specified image resolution
            Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 300, 300);

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

            // Disposes PDF resources
            pdf.Dispose();

        }
    }
}

Convert a PDF page to a PNG image

Note: Higher DPI improves image quality but slow down conversion.

2. Convert an Entire PDF File to Images

Loop through all pages in the PDF and then convert each one to a separate image.

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

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

3. Convert to Different Image Formats

By changing the ImageFormat parameter of the Image.Save() method, you can convert PDF to JPG, PNG, BMP, or Gif formats:

// Save to JPEG format
image.Save("PDFtoJPG.jpg", ImageFormat.Jpeg);

// Save to PNG format
image.Save("PDFtoPNG.png", ImageFormat.Png);

// Save to BMP format
image.Save("PDFtoBMP.bmp", ImageFormat.Bmp);

// Save to EMF format
image.Save("PDFtoEMF.emf", ImageFormat.Emf);

// Save to GIF format
image.Save("PDFtoGIF.gif", ImageFormat.Gif);

4. Using MemoryStream

For scenarios requiring stream handling, use the following code:

// Create a MemoryStream object
MemoryStream ms = new MemoryStream();

// Convert the first page to an image with specified dpi
Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 300, 300);

// Save the image to stream in PNG format
image.Save(ms, ImageFormat.Png);

// Write the Stream object to a byte array for further processing
byte[] imageBytes = ms.ToArray();

Performance Optimization Tips

  • Memory Management: Convert pages one by one to avoid memory overload for large PDFs.
  • DPI Optimization: High DPI settings improve image quality, but also increase file size and processing time.
  • Dispose Resources: Call the Dispose() method of PdfDocument class to free resources.

Conclusion

Spire.PDF provides a straightforward and efficient way to convert PDF files to images in C#. With its rich feature set, high-quality rendering, and support for multiple image formats, it’s a reliable choice for both simple and complex PDF-to-image conversion tasks. By following the examples in this article, you can quickly implement PDF converter functionality in your .NET applications.

FAQs

Q1: How to remove the watermarks on the output images?

A: You can request a free 30-day trial license here to remove the red watermark and fully evaluate the Spire.PDF library. Or you can use its Free version (with certain page limitations).

Q2: Can I convert PDFs to multi-page TIFF files with Spire.PDF?

A: Yes! A detailed guide for this can be found at: Convert PDF to TIFF in C#

Q3: Can I convert PDF to SVG using Spire.PDF?

A: Yes! Spire.PDF for .NET offers the SaveToFile(String, FileFormat.SVG) method to convert a PDF file to a SVG file. You can check out the article for a comprehensive guide.

Q4. Where can I find additional documentation or support?

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

Images (JPG, PNG, BMP, etc.) are common for data capture, but PDFs provide better security, compression, and cross-platform consistency. In .NET development, developers may often need a reliable C# image to PDF solution to streamline workflows like report generation, document archiving, and digital record management.

Visual guide for Convert Images to PDF in C#

This guide demonstrates how to efficiently convert images to PDF in C#/ ASP.NET using Spire.PDF for .NET, a powerful library that simplifies this process with robust features and excellent compatibility.

Set Up Your Project

Before we start writing code to convert images such as PNG to PDF, we need to set up our C# project and add the Spire.PDF library.

Step 1: Create a New C# Project

Open Visual Studio and create a new C# project. You can choose a Console Application, Windows Forms Application, or any other project type depending on your needs.

Step 2: Install Spire.PDF

There are a few ways to add the PDF converter library to your project. One common method is through NuGet Package Manager.

  • In Visual Studio, right-click on your project in the Solution Explorer, select "Manage NuGet Packages".
  • In the NuGet Package Manager window, search for "Spire.PDF".
  • Then, click "Install" to add the latest version of the library to your project.

Once the installation is complete, you'll be able to reference the necessary namespaces in your C# code.

How to Convert Image to PDF in C#

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. The following are two code examples for single/multiple image conversion.

Converting a Single Image to PDF

This example shows how to convert a JPG image to a PDF document, with the PDF page match the exact dimensions of the image.

C# code for JPG to PDF conversion:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace ConvertImageToPdf
{
    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));

            // Load a JPG image and draw it at (0, 0) of the page
            PdfImage pdfImage = PdfImage.FromImage(image);
            page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);

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

Explanation:

  • PdfDocument: Represents the PDF file.
  • PdfPageBase: A page in the PDF document.
  • PdfImage.FromImage: Converts an Image object to a PDF image.
  • DrawImage: Renders the image on the PDF page.

Output:

Convert a JPG image to a PDF file

Converting Multiple Images to a Single PDF

If you have multiple images that you want to combine into a single PDF document, the process is similar to the single-image conversion, but with a loop to handle each image.

C# code to convert JPG, PNG, TIFF, BMP to PDF:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

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

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

            // Specify the images to be converted
            string[] imagePaths = {"Image-1.png", "Image-2.jpg", "Image-3.bmp", "Image-4.tiff"};

            // Iterate through each image
            foreach (string path in imagePaths)
            {
                // Load a particular image 
                Image image = Image.FromFile(path);

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

                // Add a page that has the same size as the image
                PdfPageBase page = pdf.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 the PDF file
            pdf.SaveToFile("CombinaImagesToPdf.pdf");
            pdf.Dispose();
        }
    }
}

This C# code loops through an array of image files in different formats, loads each image, adds it to a new page in the PDF document, and then saves the final PDF with all the images.

Output:

Convert multiple images (jpg, png, bmp, tiff) to a PDF file


Image to PDF Customization Options

Adjust Page Settings

While conversion, you can customize PDF page properties such as orientation, margins, and size according to the nature of your images:

// Create a PDF document
PdfDocument pdf = new PdfDocument();

// Set page orientation
pdf.PageSettings.Orientation = PdfPageOrientation.Landscape;
            
// Set page margins (in points, 1 point = 1/72 inch)
pdf.PageSettings.SetMargins(20);

// Set page size
pdf.PageSettings.Size = PdfPageSize.A4;

Resize Images for Optimal Fit

If you need to maintain a fixed PDF page size, you can scale the image to make it fit to page:

// Set fixed page size (e.g., A4)  
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4);

//Load an image 
Image image = Image.FromFile("sample.jpg");

// Get the width and heigh of the page
float pageWidth = page.Canvas.ClientSize.Width;
float pageHeight = page.Canvas.ClientSize.Height;

// Scale the image 
float scale = Math.Min(pageWidth / image.Width, pageHeight / image.Height);
float scaledWidth = image.Width * scale;
float scaledHeight = image.Height * scale;

// Draw the scaled image on the page
page.Canvas.DrawImage(PdfImage.FromImage(image), 0, 0, scaledWidth, scaledHeight);

FAQs (TIFF to PDF, SVG to PDF)

Q1: What image formats does Spire.PDF support?

A: Spire.PDF seamlessly supports all major image formats:

  • JPG/ JPEG
  • PNG
  • BMP
  • TIFF
  • GIF
  • EMF
  • WMF

Ensure your input image is in a supported format for seamless conversion.

Q2: Can I convert a multi-page TIFF image to PDF?

A: Yes! Iterate through TIFF frames to convert. The full code example can be found at: Convert a Multi-Page TIFF Image to a PDF File in C#

Q3: Can I convert SVG image to PDF?

A: Yes! You can load an SVG file with LoadFromSvg() and then save it as a PDF through the SaveToFile(String, FileFormat.PDF) method.

using Spire.Pdf;

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

            // Load a sample SVG file
            doc.LoadFromSvg("Sample.svg");

            // Save SVG to PDF document
            doc.SaveToFile("SVGtoPDF.pdf", FileFormat.PDF);
            doc.Dispose();
        }
    }
}

Q4: Where can I find the VB.NET demos for image to PDF conversion?

A: Spire.PDF fully supports VB.NET. You can convert the C# code samples provided above to VB.NET via code converter tools (e.g. Telerik Code Converter).


Conclusion

With Spire.PDF for .NET, converting images to PDF in C# becomes simple and flexible. This guide shows you how to:

  • Convert a single or multiple images into a PDF document.
  • Customize page size, margins, and layout for your PDF output.

By following the examples in this guide, you can seamlessly integrate image-to-PDF conversion into your .NET applications.

For advanced features (encryption, annotation), explore Spire.PDF’s online documentation.

Get a Free License

Need to remove watermarks on output files and get rid of restrictions? You can request a 30-day full-featured trial license. A tutorial on how to use the license file is available here.

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
Page 3 of 4