Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert PDF to images using C# and ImageMagick?

I would like to convert a PDF file to .GIF using C# and magicknet.dll. I have added the reference to the MagickNet Dll to my project.

MagickNet.Magick.Init();
MagickNet.Image img = new MagickNet.Image("d:/aa.pdf");
img.Write("d:/bb.gif");
MagickNet.Magick.Term();
img.Dispose();
System.Runtime.InteropServices.SEHException was unhandled by user code
  Message="External component has thrown an exception."
  Source="ImageMagickNET"
  ErrorCode=-2147467259
  StackTrace:
       at Magick.Image.{ctor}(Image* , basic_string\,std::allocator >* )
       at ImageMagickNET.Image..ctor(String imageSpec)
       at Test1._Default.Button1_Click(Object sender, EventArgs e) in C:\Users\PANKAJ\Documents\Visual Studio 2008\Projects\Test1\Test1\Default.aspx.cs:line 31
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 
like image 988
ankush Avatar asked Feb 01 '10 11:02

ankush


2 Answers

ImageMagick requires GhostScript to Interpret PDF files. If you want you can call the GhostScript dll directly (contact me via my profile, I will send you a c# wrapper)

Alternatively you can use the GhostScript command line or a commercial 3rd party component, eg the PDF libraries from Tall Components.

like image 133
Mark Redman Avatar answered Oct 05 '22 23:10

Mark Redman


Magic.Net is a C# port for popular library ImageMagick. Install Magick.net using Nuget package from url https://www.nuget.org/packages/Magick.NET-Q16-AnyCPU/ . This way you can use C#. See code below

Note it will append images vertically. Similarly you can append horizontally i.e. substitute images.AppendHorizontally

using ImageMagick;

string inputPdf= @"C:\my docs\input.pdf";
string outputPng= @"C:\my docs\output.png";

using (MagickImageCollection images = new MagickImageCollection())
{
    images.Read(inputPdf);
    using (IMagickImage vertical = images.AppendVertically())
        {
            vertical.Format = MagickFormat.Png;
            vertical.Density = new Density(300);  
            vertical.Write(outputPng);
        }
}
like image 31
Sujit Singh Avatar answered Oct 06 '22 01:10

Sujit Singh