Pdf Conversion to Image Using MagickNet in C#



Introduction

Sometimes back, I worked on an asp.net MVC application which had a feature request to support conversion of pdf documents to images to allow viewing of the documents on devices that have Javascript disabled and most likely do not have native pdf reader app installed.

Initially, I thought of developing a custom library for this, but could not due to tight deadline of the project. I decided to search Nugget Gallery for hosted libraries that can be used for this purpose, but most of the libraries available on Nugget are limited in functionalities and not usable.

Searching codeplex.com, I came across Magick.net, https://magick.codeplex.com an image processing library built as a wrapper on ImageMagick which can also convert pdf files to images if Ghostscript is installed on the application server. Ghostscript can be downloaded at http://www.ghostscript.com/download/gsdnld.html

The PdfToImageConverter class I wrote for the pdf to image conversion is explained below. Once Ghostscript is installed, MagickNET needs to be aware of the installation path and also a Temp folder needs to be set as it writes some temporary files to disk. The library can read pdf file of any size and convert all the pages in the file to images and save the converted images to the path specified in the method parameter.

See the source listing of the PdfToImageConverter class below.

    public class PdfToImageConverter
    {
        
        public PdfToImageConverter(string filePath)
        {            
            MagickNET.SetGhostscriptDirectory(filePath+"Lib");
            MagickNET.SetTempDirectory(filePath + "\Temp");
        }
        public int ConvertFileToImages(string filePath, string destinationPath)
        {
            int noofPages = 0;
            MagickReadSettings magickReadSettings = new MagickReadSettings();
            magickReadSettings.Density = new Density(300, 300);
            using (MagickImageCollection magickImageCollection = new MagickImageCollection())
            {
                magickImageCollection.Read(filePath, magickReadSettings);
                int page = 1;
                noofPages = magickImageCollection.Count;
                foreach (MagickImage magickImage in magickImageCollection)
                {
                    magickImage.Format = MagickFormat.Png;
                    string imageFilePath = string.Concat(destinationPath,"file-", page, ".png");
                    magickImage.Write(imageFilePath);
                    page++;
                }
            }
            return noofPages;
        }
     }

  




Share this page on


  0 People Like(s) This Page   Permalink  

 Click  To Like This Page

comments powered by Disqus

page