Passport Loader

How to convert a PDF file to an image using .NET

Introduction

Sometimes, your business workflows require an image file as input. In these cases, you’ll need to convert your PDF documents to JPEG, PNG, or TIFF.
This tutorial will teach us to convert a PDF document into an image using PassportPDF and .NET.

You should have your machine already set up using instructions from our getting started guide.

How to convert a PDF to an image using PassportPDF

To convert a PDF to an image, you have multiple options in PassportPDF depending on the image format you need.
Currently, PassportPDF supports converting PDF files into JPEG, PNG, and TIFF formats. We will be exploring all of these options in this tutorial.

We will use the following endpoints:

  • DocumentLoadFromURIAsync to load a document from a URI.
  • SaveAsPNGFileAsync to save the PDF file as a PNG image.
  • SaveAsJPEGFileAsync to save the PDF file as a JPEG image.
  • SaveAsTIFFFileAsync to save the PDF file as a TIFF image.

Below you can see how these endpoints are used to convert and save the same PDF file into three different formats and then save the output images to your local disk.

using PassportPDF.Api;
using PassportPDF.Client;
using PassportPDF.Model;
 
namespace PdfConversion
{
 
    public class ConvertPDF
    {
        static async Task Main(string[] args)
        {
            GlobalConfiguration.ApiKey = "YOUR-PASSPORT-CODE";
 
            PassportManagerApi apiManager = new();
            PassportPDFPassport passportData = await apiManager.PassportManagerGetPassportInfoAsync(GlobalConfiguration.ApiKey);
 
            if (passportData == null)
            {
                throw new ApiException("The Passport number given is invalid, please set a valid passport number and try again.");
            }
            else if (passportData.IsActive is false)
            {
                throw new ApiException("The Passport number given is not active, please go to your PassportPDF dashboard and choose a plan.");
            }
 
            string uri = "https://passportpdfapi.com/test/invoice_with_barcode.pdf";
 
            DocumentApi documentApi = new();
 
            Console.WriteLine("Loading document into PassportPDF...");
            DocumentLoadResponse document = await documentApi.DocumentLoadFromURIAsync(new LoadDocumentFromURIParameters(uri));
            Console.WriteLine("Document loaded.");
 
            PDFApi pdfApi = new();
 
            Console.WriteLine("Convert and save document as a PNG...");
 
            try
            {
                string savePath = Path.Join(Directory.GetCurrentDirectory(), "converted.png");
 
                var fileStream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
 
                await pdfApi.SaveAsPNGFileAsync(new PdfSaveAsPNGParameters(document.FileId), fileStream);
 
                Console.WriteLine("PDF file converted and saved as PNG successfully!");
            }
            catch(Exception ex)
            {
                Console.WriteLine("Could not save stream to PNG file! Error : {0}", ex);
            }
 
            Console.WriteLine("Convert and save document as a JPEG...");
 
            try
            {
                string savePath = Path.Join(Directory.GetCurrentDirectory(), "converted.jpeg");
 
                var fileStream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
 
                await pdfApi.SaveAsJPEGFileAsync(new PdfSaveAsJPEGParameters(document.FileId), fileStream);
 
                Console.WriteLine("PDF file converted and saved as JPEG successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not save stream to JPEG file! Error : {0}", ex);
            }
 
            Console.WriteLine("Convert and save document as a TIFF...");
 
            try
            {
                string savePath = Path.Join(Directory.GetCurrentDirectory(), "converted.tiff");
 
                var fileStream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
 
                await pdfApi.SaveAsTIFFFileAsync(new PdfSaveAsTIFFParameters(document.FileId), fileStream);
 
                Console.WriteLine("PDF file converted and saved as TIFF successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not save stream to TIFF file! Error : {0}", ex);
            }
        }
    }
}

If no issues are encountered, you should see something like this in your console:

Loading document into PassportPDF...
Document loaded.
Convert and save document as a PNG...
PDF file converted and saved as PNG successfully!
Convert and save document as a JPEG...
PDF file converted and saved as JPEG successfully!
Convert and save document as a TIFF...
PDF file converted and saved as TIFF successfully!

Images in PNG, JPEG, and TIFF formats are saved in your local disk.

If your PDF file contains multiple pages, you can choose a specific page to convert to an image. To do this, you must set the PageRange parameter to the page number you want to convert.

For example, let’s say your PDF file contains two pages, and you would like to convert only the first page. In this case, instead of using this:

await pdfApi.SaveAsPNGFileAsync(new PdfSaveAsPNGParameters(document.FileId), fileStream);

You would be using this:

await pdfApi.SaveAsPNGFileAsync(new PdfSaveAsPNGParameters(document.FileId) { PageRange = "1" }, fileStream);

For the full project code, check out the github repository.

Saving a multipage PDF file to multipage TIFF

If you want to save a multipage PDF as a multipage TIFF file, you will need to use the endpoint SaveAsTIFFMultipageFileAsync instead of SaveAsTIFFFileAsync.

The code for saving a multipage PDF as a multipage TIFF file is similar to the previous code. The only difference is that the line:

await pdfApi.SaveAsTIFFFileAsync(new PdfSaveAsTIFFParameters(document.FileId) { PageRange = "1" }, fileStream);

should be changed to:

await pdfApi.SaveAsTIFFMultipageFileAsync(new PdfSaveAsTIFFMultipageParameters(document.FileId) { PageRange = "*" }, fileStream);

Final remarks

You can use PassportPDF to convert PDF documents to images.
Currently, we support three image formats: PNG, JPEG, and TIFF. You have a lot of control over the conversion process. For example, you can choose a specific page in your PDF document to convert to an image. You can also control the quality of the output image as well as its resolution.
You can find out more about these options by visiting the endpoints documentation.