Monday, June 10, 2013

Convert PDF to image (C# .NET sample)



Our .NET component Apitron PDF Rasterizer for.NET v.3.0  has been recently released and I’m going to show you how it can be used for PDF processing. 

STEP 1

Download component package from company website http://www.apitron.com/Downloads and unzip to desired folder.

STEP 2

Except folders for each framework version (it also has a specific build that works with Xamarin.Android – I plan additional post on how to use that) there is a Samples folder in unzipped directory containing several example projects. Go ahead and open ConvertPdfToImage.csproj.

I decided to go with my own file instead of default test PDF file provided with package and downloaded one from adobe website http://acroeng.adobe.com/Test_Files/viewing//3BigPreview.pdf and put in Samples\Documents folder.

The code is very simple but clearly demonstrates the process:

namespace ConvertPDFtoBitmap{
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;

    using Apitron.PDF.Rasterizer;
    using Apitron.PDF.Rasterizer.Configuration;

    internal class Program
    {
        private static void Main(string[] args)
        {
            // open and load the file
            using (FileStream fs = new FileStream(@"..\..\..\Documents\3BigPreview.pdf", FileMode.Open))
            {
                // this object represents a PDF document
                Document document = new Document(fs);
               
                // default rendering settings
                RenderingSettings settings = new RenderingSettings();

                // process and save pages one by one
                for (int i = 0; i < document.Pages.Count; i++)
                {
                    Page currentPage = document.Pages[i];

                    // we use original page's width and height for image as well as default rendering settings
                    using (Bitmap bitmap = currentPage.Render((int)currentPage.Width, (int)currentPage.Height,settings))
                    {
                        bitmap.Save(string.Format("{0}.png", i), ImageFormat.Png);
                    }
                }
                // preview first rendered page
                Process.Start("0.png");
            }
        }
    }
}


STEP 3

Enjoy the result:


This component can also be used for PDF to TIFF conversion, as well as reading PDF document properties like Author, Title or creation date.As you may see from the image above, advanced  CJK text rendering is nicely supported and many other drawing features that PDF specification describes.Patterns, shadings, images in various colorspaces, transparency..etc.



No comments:

Post a Comment