Convert various Images formats to PDF in .NET

Overview

This article explains how to convert various Images formats to PDF using C#. It covers these topics.

The following code snippet also work with Aspose.PDF.Drawing library.

Format: BMP

Format: CGM

Format: DICOM

Format: EMF

Format: GIF

Format: JPG

Format: PNG

Format: SVG

Format: TIFF

Format: CDR

Format: DJVU

Other topics covered by this article

C# Images to PDF Conversions

Aspose.PDF for .NET allows you to convert different formats of images to PDF files. Our library demonstrates code snippets for converting the most popular image formats, such as - BMP, CGM, DICOM, EMF, JPG, PNG, SVG and TIFF formats.

Convert BMP to PDF

Convert BMP files to PDF document using Aspose.PDF for .NET library.

BMP images are Files having extension. BMP represent Bitmap Image files that are used to store bitmap digital images. These images are independent of graphics adapter and are also called device independent bitmap (DIB) file format. You can convert BMP to PDF files with Aspose.PDF for .NET API. Therefore, you can follow the following steps to convert BMP images:

Steps: Convert BMP to PDF in C#

  1. Initialize a new Document class object.
  2. Load input BMP image.
  3. Finally, save the output PDF file.

So the following code snippet follows these steps and shows how to convert BMP to PDF using C#:

private static void ConvertBMPtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    //Initialize empty PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        
        // Load sample BMP image file
        image.File = dataDir + "BMPtoPDF.bmp";
        document.Pages[1].Paragraphs.Add(image);
        
        // Save output PDF document
        document.Save(dataDir + "BMPtoPDF_out.pdf");
    }
}

Convert CGM to PDF

CGM is a file extension for a Computer Graphics Metafile format commonly used in CAD (computer-aided design) and presentation graphics applications. CGM is a vector graphics format that supports three different encoding methods: binary (best for program read speed), character-based (produces the smallest file size and allows for faster data transfers) or cleartext encoding (allows users to read and modify the file with a text editor).

Check next code snippet for converting CGM files to PDF format.

Steps: Convert CGM to PDF in C#

  1. Create an instance of CgmLoadOptions class.
  2. Create an instance of Document class with mention source filename and options.
  3. Save the document with the desired file name.
private static void ConvertCGMtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    var option = new Aspose.Pdf.CgmLoadOptions();
    using (var document = new Aspose.Pdf.Document(dataDir + "CGMtoPDF.cgm", option))
    {
        document.Save(dataDir + "CGMtoPDF_out.pdf");
    }
}

Convert DICOM to PDF

DICOM format is the medical industry standard for the creation, storage, transmission, and visualization of digital medical images and documents of examined patients.

Aspsoe.PDF for .NET allows you to convert DICOM and SVG images, but for technical reasons to add images you need to specify the type of file to be added to PDF:

Steps: Convert DICOM to PDF in C#

  1. Create an object of the Image class.
  2. Add the image to a page’s Paragraphs collection.
  3. Specify the FileType property.
  4. Specify the file’s path or source.
    • If an image is at a location on the hard drive, specify the path location using the Image.File property.
    • If an image is placed in a MemoryStream, pass the object holding the image to the Image.ImageStream property.

The following code snippet shows how to convert DICOM files to PDF format with Aspose.PDF. You should load DICOM image, place the image on a page in a PDF file and save the output as PDF.

private static void ConvertDICOMtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    // Instantiate Document Object
    using (var document = new Aspose.Pdf.Document())
    {
        // Add a page to pages collection of document
        var page = document.Pages.Add();
        
        var image = new Aspose.Pdf.Image
        {
            FileType = ImageFileType.Dicom,
            File = dataDir + "DICOMtoPDF.dcm"
        };
        document.Pages[1].Paragraphs.Add(image);
        // Save output as PDF format
        document.Save(dataDir + "DICOMtoPDF_out.pdf");
    }
}

Convert EMF to PDF

EMF stores graphical images device-independently. Metafiles of EMF comprises of variable-length records in chronological order that can render the stored image after parsing on any output device. Furthermore, you can convert EMF to PDF image using the below steps:

Steps: Convert EMF to PDF in C#

  1. Firstly, initialize Document class object.
  2. Load EMF image file.
  3. Add the loaded EMF image to a Page.
  4. Save PDF document.

Moreover, the following code snippet shows how to convert an EMF to PDF with C# in your .NET code snippet:

private static void ConvertEMFtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    // Initialize new PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        // Spcify path of input EMF image file
        var imageFile = dataDir + "EMFtoPDF.emf";
        var page = document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        image.File = imageFile;

        // Specify page dimension properties
        page.PageInfo.Margin.Bottom = 0;
        page.PageInfo.Margin.Top = 0;
        page.PageInfo.Margin.Left = 0;
        page.PageInfo.Margin.Right = 0;
        page.PageInfo.Width = image.BitmapSize.Width;
        page.PageInfo.Height = image.BitmapSize.Height;

        page.Paragraphs.Add(image);

        //Save output PDF document
        document.Save(dataDir + "EMFtoPDF_out.pdf");
    }
}

Convert GIF to PDF

Convert GIF files to PDF document using Aspose.PDF for .NET library.

GIF is able to store compressed data without loss of quality in a format of no more than 256 colors. The hardware-independent GIF format was developed in 1987 (GIF87a) by CompuServe for transmitting bitmap images over networks. You can convert GIF to PDF files with Aspose.PDF for .NET API. Therefore, you can follow the following steps to convert GIF images:

Steps: Convert GIF to PDF in C#

  1. Initialize a new Document class object.
  2. Load input GIF image.
  3. Finally, save the output PDF file.

So the following code snippet follows these steps and shows how to convert BMP to PDF using C#:

private static void ConvertGIFtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    using (var document = new Aspose.Pdf.Document())
    {
        //Initialize empty PDF document
        document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        
        // Load sample GIF image file
        image.File = dataDir + "GIFtoPDF.gif";
        document.Pages[1].Paragraphs.Add(image);
        // Save output PDF document
        document.Save(dataDir + "GIFtoPDF_out.pdf");
    }
}

Convert JPG to PDF

No need to wonder how to convert JPG to PDF, because Apose.PDF for .NET library has best decision.

You can very easy convert a JPG images to PDF with Aspose.PDF for .NET by following steps:

Steps: Convert JPG to PDF in C#

  1. Initialize object of Document class.
  2. Add a new Page to PDF document.
  3. Load JPG image and add to paragraph.
  4. Save output PDF.

The code snippet below shows how to convert JPG Image to PDF using C#:

private static void ConvertJPGtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    // Initialize new PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        // Load input JPG file
        var path = dataDir + "JPGtoPDF.jpg";
        // Add empty page in empty document
        var page = document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        image.File = path;
        
        // Add image on a page
        page.Paragraphs.Add(image);
        
        // Save output PDF file
        document.Save(dataDir + "JPGtoPDF_out.pdf");
    }
}

Then you can see how to convert an image to PDF with the same height and width of the page. We will be getting the image dimensions and accordingly set the page dimensions of PDF document with the below steps:

  1. Load input image file.
  2. Set height, width, and margins of a page.
  3. Save the output PDF file.

Following code snippet shows how to convert an Image to PDF with same page height and width using C#:

private static void ConvertJPGtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    using (var document = new Aspose.Pdf.Document())
    {
        var path = dataDir + "JPGtoPDF.jpg";
        // Add an empty page
        var page = document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        image.File = path;
        
        // Read Height of input image
        page.PageInfo.Height = image.BitmapSize.Height;
        // Read Width of input image
        page.PageInfo.Width = image.BitmapSize.Width;
        page.PageInfo.Margin.Bottom = 0;
        page.PageInfo.Margin.Top = 0;
        page.PageInfo.Margin.Right = 0;
        page.PageInfo.Margin.Left = 0;
        page.Paragraphs.Add(image);
        
        // Save output PDF file
        document.Save(dataDir + "JPGtoPDF_out.pdf");
    }
}

Convert PNG to PDF

Aspose.PDF for .NET support feature to convert PNG images to PDF format. Check the next code snippet for realizing you task.

PNG refers to a type of raster image file format that use loseless compression, that makes it popular among its users.

You can convert PNG to PDF image using the below steps:

Steps: Convert PNG to PDF in C#

  1. Load input PNG image.
  2. Read height and width values.
  3. Create new Document object and add Page.
  4. Set page dimensions.
  5. Save output file.

Moreover, the code snippet below shows how to convert PNG to PDF with C# in your .NET applications:

private static void ConvertPNGtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    using (var document = new Aspose.Pdf.Document())
    {
        // Load input PNG file
        var path = dataDir + "PNGtoPDF.png";
        // Add an empty page
        var page = document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        image.File = path;
        
        // Read Height of input image
        page.PageInfo.Height = image.BitmapSize.Height;
        // Read Width of input image
        page.PageInfo.Width = image.BitmapSize.Width;
        page.PageInfo.Margin.Bottom = 0;
        page.PageInfo.Margin.Top = 0;
        page.PageInfo.Margin.Right = 0;
        page.PageInfo.Margin.Left = 0;
        page.Paragraphs.Add(image);
        
        // Save output PDF
        document.Save(dataDir + "PNGtoPDF_out.pdf");
    }
}

Convert SVG to PDF

Aspose.PDF for .NET explains how to convert SVG images to PDF format and how to get dimensions of the source SVG file.

Scalable Vector Graphics (SVG) is a family of specifications of an XML-based file format for two-dimensional vector graphics, both static and dynamic (interactive or animated). The SVG specification is an open standard that has been under development by the World Wide Web Consortium (W3C) since 1999.

SVG images and their behaviors are defined in XML text files. This means that they can be searched, indexed, scripted, and if required, compressed. As XML files, SVG images can be created and edited with any text editor, but it is often more convenient to create them with drawing programs such as Inkscape.

To convert SVG files to PDF, use the class named SvgLoadOptions which is used to initialize the LoadOptions object. Later, this object is passed as an argument during the Document object initialization and helps the PDF rendering engine to determine the input format of the source document.

Steps: Convert SVG to PDF in C#

  1. Create an instance of SvgLoadOptions class.
  2. Create an instance of Document class with mention source filename and options.
  3. Save the document with the desired file name.

The following code snippet shows the process of converting SVG file into PDF format with Aspose.PDF for .NET.

private static void ConvertSVGtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    var option = new Aspose.Pdf.SvgLoadOptions();
    using (var document = new Aspose.Pdf.Document(dataDir + "SVGtoPDF.svg", option))
    {
        document.Save(dataDir + "SVGtoPDF_out.pdf");
    }
}

Get SVG dimensions

It is also possible to get the dimensions of the source SVG file. This information can be useful if we want the SVG to cover the entire page of the output PDF. The SvgLoadOption class’ AdjustPageSize property fulfills this requirement. The default value of this property is false. If the value is set to true, the output PDF will have the same size (dimensions) as the source SVG.

The following code snippet shows the process of getting the source SVG file’s dimensions and generating a PDF file.

private static void ConvertSVGtoPDF()
{
    // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
    // The path to the documents directory.
    var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
    var loadopt = new Aspose.Pdf.SvgLoadOptions();
    loadopt.AdjustPageSize = true;
    using (var document = new Aspose.Pdf.Document(dataDir + "SVGtoPDF.svg", loadopt))
    {
        document.Pages[1].PageInfo.Margin.Top = 0;
        document.Pages[1].PageInfo.Margin.Left = 0;
        document.Pages[1].PageInfo.Margin.Bottom = 0;
        document.Pages[1].PageInfo.Margin.Right = 0;
        document.Save(dataDir + "SVGtoPDF_out.pdf");
    }
    
}

SVG Supported Features

SVG Tag

Sample Use

circle

< circle id="r2" cx="10" cy="10" r="10" stroke="blue" stroke-width="2"> 

defs

<defs> 
<rect id="r1" width="15" height="15" stroke="blue" stroke-width="2" /> 
<circle id="r2" cx="10" cy="10" r="10" stroke="blue" stroke-width="2"/> 
<circle id="r3" cx="10" cy="10" r="10" stroke="blue" stroke-width="3"/> 
</defs> 
<use x="25" y="40" xlink:href="#r1" fill="red"/> 
<use x="35" y="15" xlink:href="#r2" fill="green"/> 
<use x="58" y="50" xlink:href="#r3" fill="blue"/>

tref

<defs> 
    <text id="ReferencedText"> 
      Referenced character data 
    </text> 
</defs> 
<text x="10" y="100" font-size="15" fill="red" > 
    <tref xlink:href="#ReferencedText"/> 
</text>

use

<defs> 
    <text id="Text" x="400" y="200" 
          font-family="Verdana" font-size="100" text-anchor="middle" > 
      Masked text 
    </text> 
<use xlink:href="#Text" fill="blue"  />

ellipse 

<ellipse cx="2.5" cy="1.5" rx="2" ry="1" fill="red" />

<g fill="none" stroke="dimgray" stroke-width="1.5" > 
                <line x1="-7" y1="-7" x2="-3" y2="-3"/> 
                <line x1="7" y1="7" x2="3" y2="3"/> 
                <line x1="-7" y1="7" x2="-3" y2="3"/> 
                <line x1="7" y1="-7" x2="3" y2="-3"/> 
</g> 

image

<image id="ShadedRelief" x="24" y="4" width="64" height="82" xlink:href="relief.jpg" /> 

line

<line style="stroke:#eea;stroke-width:8" x1="10" y1="30" x2="260" y2="100"/> 

path

<path style="fill:#daa;fill-rule:evenodd;stroke:red" d="M 230,150 C 290,30 10,255 110,140 z "/> 

style

<path style="fill:#daa;fill-rule:evenodd;stroke:red" d="M 230,150 C 290,30 10,255 110,140 z "/>

polygon

<polygon style="stroke:#24a;stroke-width:1.5;fill:#eefefe" points="10,10 180,10 10,250 10,10" />

polyline

<polyline fill="none" stroke="dimgray" stroke-width="1" points="-3,-6 3,-6 3,1 5,1 0,7 -5,1 -3,1 -3,-5"/>

rect 

<rect x="0" y="0" width="400" height="600" stroke="none" fill="aliceblue" />

svg

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10cm" height="5cm" >

text

<text font-family="sans-serif" fill="dimgray" font-size="22px" font-weight="bold" x="58" y="30" pointer-events="none">Map Title</text>

font

<text x="10" y="100" font-size="15" fill="red" > 
    Sample text 
</text>

tspan

<tspan dy="25" x="25">six ink color input value. Here it will </tspan>

Convert TIFF to PDF

Aspose.PDF file format supported, be it a single frame or multi-frame TIFF image. It means that you can convert the TIFF image to PDF in your .NET applications.

TIFF or TIF, Tagged Image File Format, represents raster images that are meant for usage on a variety of devices that comply with this file format standard. TIFF image can contain several frames with different images. Aspose.PDF file format is also supported, be it a single frame or multi-frame TIFF image.

You can convert TIFF to PDF in the same manner as the rest raster file formats graphics:

Steps: Convert TIFF to PDF in C#

  1. Create new Document class object and add Page.
  2. Load input TIFF image.
  3. Save PDF document.
private static void ConvertTIFFtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    //Initialize empty PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        document.Pages.Add();
        var image = new Aspose.Pdf.Image();
        
        // Load sample Tiff image file
        image.File = dataDir + "TIFFtoPDF.tiff";
        document.Pages[1].Paragraphs.Add(image);
        
        // Save output PDF document
        document.Save(dataDir + "TIFFtoPDF_out.pdf");
    }
}

In case you need to convert multi-page TIFF image to multi-page PDF document and control some params, i.g. width or aspect ratio, please follow these steps:

  1. Instantiate an instance of Document class.
  2. Load input TIFF image.
  3. Get FrameDimension of the frames.
  4. Add new page for each frame.
  5. Finally, save images to PDF pages.

The following code snippet shows how to convert multi-page or multi-frame TIFF image to PDF with C#:

private static void ConvertTIFFtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    using (var document = new Aspose.Pdf.Document())
    {
        using (var bitmap = new System.Drawing.Bitmap(File.OpenRead(dataDir + "TIFFtoPDF.tif")))
        {
            // Convert multi page or multi frame TIFF to PDF
            var dimension = new FrameDimension(bitmap.FrameDimensionsList[0]);
            var frameCount = bitmap.GetFrameCount(dimension);

            // Iterate through each frame
            for (int frameIdx = 0; frameIdx <= frameCount - 1; frameIdx++)
            {
                var page = document.Pages.Add();

                bitmap.SelectActiveFrame(dimension, frameIdx);

                using (var currentImage = new MemoryStream())
                {
                    bitmap.Save(currentImage, ImageFormat.Tiff);

                    var imageht = new Aspose.Pdf.Image
                    {
                        ImageStream = currentImage,
                        //Apply some other options
                        //ImageScale = 0.5
                    };
                    page.Paragraphs.Add(imageht);
                }
            }
        }

        // Save output PDF file
        document.Save(dataDir + "TIFFtoPDF_out.pdf");
    }
}

Convert CDR to PDF

CDR is a file format that was developed by the Corel Corporation and is used mainly for vector graphic images and drawings. The CDR file format is recognized by the majority of image editing programs. The CDR format is the default format for Corel Draw Applications.

Check next code snippet for converting CDR files to PDF format.

Steps: Convert CDR to PDF in C#

  1. Create an instance of CdrLoadOptions class.
  2. Create an instance of Document class with mention source filename and options.
  3. Save the document with the desired file name.
private static void ConvertCDRtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    using (var document = new Aspose.Pdf.Document(dataDir + "CDRtoPDF.cdr", new CdrLoadOptions()))
    {
        document.Save(dataDir + "CDRtoPDF_out.pdf");
    }
}

Convert DJVU to PDF

DjVu is a compressed image format which was developed by LizardTech. This file format was primarily designed to store different kinds of scanned documents; especially documents that contain a combination of text, pictures, indexed color images, and line drawings.

Check next code snippet for converting DJVU files to PDF format.

Steps: Convert DJVU to PDF in C#

  1. Create an instance of DjvuLoadOptions class.
  2. Create an instance of Document class with mention source filename and options.
  3. Save the document with the desired file name.
private static void ConvertDJVUtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
    
    using (var document = new Aspose.Pdf.Document(dataDir + "CDRtoPDF.djvu", new DjvuLoadOptions()))
    {
        document.Save(dataDir + "CDRtoPDF_out.pdf");
    }
}

Convert HEIC to PDF

A HEIC file is a High-Efficiency Container Image file format that can store multiple images as a collection in a single file. For loading heic images you need to add a reference to the https://www.nuget.org/packages/FileFormat.Heic/ nuget package. Convert HEIC images to PDF using Aspose.PDF:

private static void ConvertHEICtoPDF()
{
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    using (var fs = new FileStream(dataDir + "HEICtoPDF.heic", FileMode.Open))
    {
        var image = FileFormat.Heic.Decoder.HeicImage.Load(fs);
        var pixels = image.GetByteArray(PixelFormat.Rgb24);
        var width = (int)image.Width;
        var height = (int)image.Height;

        using (var document = new Aspose.Pdf.Document())
        {
            var page = document.Pages.Add();
            var asposeImage = new Aspose.Pdf.Image();
            asposeImage.BitmapInfo = new Aspose.Pdf.BitmapInfo(pixels, width, height, Aspose.Pdf.BitmapInfo.PixelFormat.Rgb24);
            page.PageInfo.Height = height;
            page.PageInfo.Width = width;
            page.PageInfo.Margin.Bottom = 0;
            page.PageInfo.Margin.Top = 0;
            page.PageInfo.Margin.Right = 0;
            page.PageInfo.Margin.Left = 0;

            page.Paragraphs.Add(asposeImage);
            document.Save(dataDir + "HEICtoPDF_out.pdf");
        }
    }
}

Applies to

Platform Supported Comments
Windows .NET Framework 2.0-4.6
Windows .NET Core 2.0-3.1
.NET 5 Windows
Linux .NET Core 2.0-3.1
.NET 5 Linux

See Also

This article also covers these topics. The codes are same as above.

Format: BMP

Format: CGM

Format: DICOM

Format: EMF

Format: DjVu

Format: CDR