QuestionsAnswered.net
What's Your Question?

How to Convert a JPG to a PDF
Sometimes the need arises to change a photo or image file saved in the .jpg format to the PDF digital document format. With the right software, this conversion can be made quickly and easily.
What Is a JPG?
First, some definitions. A .jpg computer file — also sometimes spelled out as JPG or JPEG — is a file format used to store digital photos or other images, such as graphics. It’s an acronym for the Joint Photographic Experts Group. The main advantage of a .jpg file is that it allows for lossy compression, which reduces the .jpg’s file size while decreasing image quality somewhat. For this reason, .jpgs are usually used for digital photos rather than graphics. Even though .jpgs are useful, it’s sometimes necessary to convert them into a different computer file format, like a PDF.
What is a PDF?
A PDF is short for Portable Document Format, and was developed by Adobe in the early 1990s as a method of digitally storing, distributing, viewing, and printing documents in a format that would remain consistent across all platforms (computer types, operating systems, etc…). PDFs have become a standard for processing digital documents, and can be viewed in many web browsers, or in Adobe’s own (free) Acrobat Reader DC.
Open the .jpg in Photoshop
Here is one good method for converting a .jpg into a PDF, using Adobe’s own Photoshop. Photoshop is capable of reading and saving many different types of image files, and it also includes support for PDF files.
- To get started, launch Adobe Photoshop on your computer.
- Click File, and then select Open.>li
- Locate the .jpg file you’d like to convert to a PDF, and double-click it.
- Photoshop opens the .jpg for you.
Prepare to Convert the .jpg to PDF
Now you can begin the actual conversion to PDF.
- Click File, and choose Save As (not Save).
- Navigate to the location where you would like to save your new PDF file.
- In the File name field, enter a new file name for the PDF.
- In the “Save as type” drop-down menu, choose Photoshop PDF from the many options.
- Click the Save button.
Choose the PDF Settings
Now Photoshop brings up the Save Adobe PDF dialog box. There are a number of different settings here that you can use to control the final output qualities and settings of your new PDF. For example, there are settings that control the compression of the new PDF, which can be used to reduce file size or increase quality. Photoshop also includes some presets for common settings. When you have everything set the way you want, click the Save PDF button. Photoshop converts the .jpg into a PDF and stores the new file in the destination you chose earlier. Nice work, and you’re all done.
MORE FROM QUESTIONSANSWERED.NET

How To Convert PDFs to Images for ML Projects Using Ghostscript and Multiprocessing

TLDR; Run the following Ghostscript command to convert a pdf file to a series of png files.
PDF files frequently contain data (text, images, tables, logs etc) valuable for training machine learning algorithms. However, most ML models are designed to process datasets (training or inference) represented as RGB images (JPEG, PNG), text, tabular data or combinations of these base modalities. A first step in utilizing pdf files for machine learning is to convert PDF files to images and then explore subsequent tasks (e.g. image classification, object detection, text extraction, etc).
I recently had to assemble a dataset of images from PDF files and this post documents the process I followed - Ghostscript !
Ghostscript
Ghostscript is an interpreter for PostScript and Portable Document Format (PDF) files. Ghostscript consists of a PostScript interpreter layer, and a graphics library. The graphics library is shared with all the other products in the Ghostscript family, so all of these technologies are sometimes referred to as Ghostscript, rather than the more correct GhostPDL.
If you are on a Mac, Ghostscript is installed by default (included in the Apple OS X package). On other platforms, follow the installation guide here . Verify that Ghostscript is installed and working (available on your path) by running the following command gs on your terminal.
Ghostscript from the command line
Once Ghostscript is installed, you can run the following script from the command line to convert a pdf file to a series of images:
The scripts above will take the specified pdf document.pdf , convert to a series of images and save them to the current directory. -dNOPAUSE tells Ghostscript to not pause after each page is rendered. -r600 specifies the resolution (dpi) of the output images. -sOutputFile=document-%02d.png specifies the output file name and the %02d is a placeholder for the page number. -sDEVICE=png16m and -sDEVICE=jpg specifies the output format.
Ghostscript in Python
We take the above script and convert it to a Python script using subprocess .
Convert all PDFs in a directory
Similarly, you can walk through a directory of pdf files and convert them to images.
and here are the results:
All well and good! We now have a series of images in the output directory. However, each pdf file takes about 1.5 seconds to convert each document. 1 minute and 45 seconds to convert 70 documents (note that conversion speed depends on the resolution parameter i.e., reducing your resolution will lead to faster conversion).
When the goal is to convert hundreds of thousands of documents, this can be slow. Hey multiprocessing!
Ghostscript with Python and multiprocessing
We can use the python multiprocessing library to speed up the conversion process. We can define a pool of processes and use the map function to run the conversion on each document in parallel. Luckily, converting files is an embarrassingly parallel task where all of the data and logic to complete the task can be encapsulated in a single function without any shared state.
and the output ..
We have shaved our time down from 1 minute 45 seconds to 15.7 seconds (6.7x speed up).
And that's it! Happy data generating!
RELATED POSTS | machine learning , how to

Read the Newsletter.
I write a monthly newsletter on Applied AI and HCI. Subscribe to get notified on new posts.
Feel free to reach out! Twitter , GitHub , LinkedIn

- TECHNOLOGIES
- An Interview Question

Convert PDF File Into Image File(png,jpg,jpeg) Using GhostScript

- Oct 04, 2016
In this blog, I will explain how to convert PDF file into an image file.

- Please install Ghostscript in your computer according to its bit rate, that is32/64 bit. Please refer this link and always install and use the latest version. You might get confused here that if I already have installed the Ghostscript in my Solution, then what is the need of installing it again. The reason behind is that while converting the PDF file to an image file, we need Ghostscript in our computer; and to access the Ghostscript properties, we have to install it in our Visual Studio Solution.
- If we haven't installed the Ghostscript in our computer and are trying to run the application directly, then we can encounter the error which is shown in the below picture,

- In the above example, I converted the PDF file into png image file. But, if you want to convert pdf file into jpg/jpeg, then in place of png, please write jpg/jpeg.
- If you want to convert PDF file into image file in production server or any other server, then you should install the Ghostscript (32/64 bit) for that server otherwise it will show you an error.
- This is just a sample application and you can change or modify anything as per your requirement.
- Convert Pdf File
- Image Filepng
- GhostScript

Convert PDF to PNG using Ghostscript.NET

Introduction
Ghostscript is an interpreter for PostScript and Portable Document Format (PDF) files. It consists of a PostScript interpreter layer, and a graphics library. GhostPDF is an interpreter built on top of Ghostscript that handles PDF files. It relies on extensions to the PostScript language/imaging model.
Ghostscript.NET (written in C#) is the most completed managed wrapper library around the native Ghostscript library (32-bit & 64-bit), an interpreter for the PostScript language, PDF, related software and documentation.
In this article, we will look into converting PDF files to PNG using Ghostscript.NET.
Step by Step Explanation
Step 1: Download the GhostScript(8.64) from here .
Install it.

The installed files will be located at
Step 2: Fire up a console application and from Nuget Package Console issue
Now let's say we have a set of pdf files
We have to convert these files into PNG.
Step 3: The below program will do the conversion
At first we are identified all the pdf files in a given location
Next we are processing each files by using the foreach loop and invoke the PdfToPng function.
Inside the PdfToPng function, initially we are creating instance for GhostscriptRasterizer . This class rasterize PDF, EPS or multi-page PostScript files to any common image format. Next by calling the GetPage function, we are converting the PDF pages to images by passing the printing resolution (DPI) and the pageNumber.
Finally we are saving the images.
The resultant output will be
This article taught us how to convert PDF to PNG using Ghostscript.NET. Hope this will be helpful. Thanks for reading. Zipped file is attached herewith.
About the Author

Latest Articles
- How to copy or move Excel worksheets in C#
- How to convert PDF to Excel and PDF to Word in C#/VB.NET
- How to host ASP.NET Core 3.x MVC application on server
- How to publish .NET Core 3.x MVC application from Visual Studio 2019
- Same action method and different parameters in .NET core
Latest Articles from Rajnilari2015
- Language Detection using Text Analytics API 2.0 Cognitive Service
- Text Recognition using Vision API Cognitive Service
- Object Recognition using Cognitive Service Vision API
- Face Reading through Face API Cognitive Service
- Machine Learning through Predictive Analysis using Multi Linear Regression in R with an example
Comments or Responses
Login to post response

Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
Script to convert PDF to JPEG using Ghostscript library
KubaSzostak/pdf-to-jpg
Name already in use.
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI .
- Open with GitHub Desktop
- Download ZIP
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Script to convert PDF to JPEG using Ghostscript library. Works well even with very big and heavy PDF files which hang up Adobe Acrobat. Of course there is no size limit.
How to use: Drag and drop Your PDF file to pdf-to-jpg.bat
Download https://github.com/kubaszostak/pdf-to-jpg/archive/refs/heads/master.zip
- Tested with Ghostscript 9.14
- Batchfile 100.0%

- Latest Articles
- Top Articles
- Posting/Update Guidelines
- Article Help Forum

- View Unanswered Questions
- View All Questions
- View C# questions
- View Javascript questions
- View C++ questions
- View Python questions
- View Java questions
- CodeProject.AI Server
- All Message Boards...
- Running a Business
- Sales / Marketing
- Collaboration / Beta Testing
- Work Issues
- Design and Architecture
- Artificial Intelligence
- Internet of Things
- ATL / WTL / STL
- Managed C++/CLI
- Objective-C and Swift
- System Admin
- Hosting and Servers
- Linux Programming
- .NET (Core and Framework)
- Visual Basic
- Web Development
- Site Bugs / Suggestions
- Spam and Abuse Watch
- Competitions
- The Insider Newsletter
- The Daily Build Newsletter
- Newsletter archive
- CodeProject Stuff
- Most Valuable Professionals
- The Lounge
- The CodeProject Blog
- Where I Am: Member Photos
- The Insider News
- The Weird & The Wonderful
- What is 'CodeProject'?
- General FAQ
- Ask a Question
- Bugs and Suggestions

How To Convert PDF to Image Using Ghostscript API

- Download source - 325.29 KB

Where to Download the Required Library
You will need at least GhostScript 8.64 (other versions have a problem with Vista). After you have installed the program, just copy the gs32dll.dll from the installation directory (the bin subdirectory) to the directory where you have the EXE of my program.
Requirements
The program REQUIRES the DLL of Ghostscript, it can be retrieved from the Ghostscript website.
Introduction
Often, I found the need to perform a conversion from a PDF to an image format.
Be it TIF, JPG or whatever format (I strongly suggest to convert PDF to PNG and NOT to JPEG since PNG is MUCH smaller and much better (since it has no information losses). Try for yourself and you will see!)
I found many programs and controls that allow me to do it but they are all expensive or incomplete for my needs. Since I know that Ghostscript performs this kind of work pretty well, I looked for a way to automate a simple conversion.
To perform a conversion, I needed to pass several commands to the Ghostscript interpreter. I must convert a Unicode string to a null terminated ANSI string for Ghostscript. The result is stored in a byte array.
The parameters that we will provide the library are the same and in the same order that we should provide from the command line. So in case any modification attempt should fail on this project, be sure that they are working from the command line!
For a comprehensive list of all the parameters and their meanings, I suggest you read: How to use Ghostscript .
How to Interface with the Ghostscript Library
The functions that are needed to call the library must be invoked using P/Invoke:
Now that we have this function, we MUST call them in this order :
- gsapi_new_instance
- gsapi_init_with_args
- gsapi_delete_instance
Pay attention to the last two, it is a common mistake to invert them!
Now how to call it. (In the real code, there are also parameter checks, but I skip them here for simplicity):
How to Call the Library We Just Created
Using this library is pretty simple.
- Create an instance of the class
- Provide the parameters that are passed as properties (this is optional now)
- Call the function: "Convert" with input and output name (optionally even the parameters)
Here there is an example:

Remark About the Library
Ghostscript isn't threadsafe, if you call it more than once, you MUST provide a lock system to be sure you are not calling two instances at the same time.
How to Use This as a Library
Since I have seen a lot of problems regarding how to use this library, I split my project in 2 main projects, one is a DLL ( PDFToImage.dll ) and the other one is the simple GUI of the DLL.
To use it in an ASP page, YOU MUST set the property " ThrowException " to true and now the library will only throw an exception on error and not show any Messagebox (that you could not want on an ASP page for example).
In case your needs are different from mine, I added a way to pass the library directly the parameters you want. In this case, you will only have to provide input, output name and a string with the parameters as usual in the same form and order then you would provide the command line.
If you want to use this library in an ASP.NET page, you MUST copy both PDFToImage.dll and gs32dll.dll in the BIN directory of your solution !
How to Debug Problems
The program displays a nice arguments list that will help you to find why a file doesn't convert! Open a command prompt, enter the directory where you installed Ghostscript and execute the file gs32win.exe with the parameters as expressed in the textbox (you should only add " to enclose the path of the file that are the last 2 arguments).
You will see how the real Ghostscript would react to it, so you will understand why an error occurred!
- 1.0.3 (2008 January): Initial version
- 1.1.0 (2009 March 25): Made it possible to use as DLL and to pass other parameters
- 1.1.1 (2009 March 26): Fixed an International issue, thanks to tchu_2000
- 1.1.2b (2009 March 27): Fixed multiple page output, and cleaned up the International convention
- 1.1.3 (2009 April 4): Fixed duplicated parameter, added new parameters option ( PageSize , Multithreads support, AntiAlaising and so on)
- 1.2 (2009 November 17): Fixed bug in parameter (thanks Barabara), added more font Options (Thanks Davalv), added Mutex to avoid Concurrency issue (Thanks Davalv), added recognition of 64bit problems
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Comments and Discussions
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Unable to Convert Pdf to Png Using Ghostscript.Net
Hello everyone and thanks for the help in advance. I am using GhostScript.Net to convert Pdf files to Png images. This has worked perfectly fine using Visual Studio 2019 on a Windows 10 OS. However, when I moved to VS 2022 I continue to receive an error "System.NullReferenceException" when trying to save the Png, Here is my code:
pdf2PNG.Save(outputPNGPath, ImageFormat.Png); throws the error. I have installed gsdll64.dll, located in C:\Program Files\gs\gs9.56.1\bin. I'm not sure where to go from here Any help would be appreciated.
ASP.NET Core A set of technologies in the .NET Framework for building web applications and XML web services. 3,616 questions Sign in to follow
pdf2PNG.Save(outputPNGPath, ImageFormat.Png);
Before executing the above code, try to set a break point to debug your code and check whether the pdf2PNG is null or not?
Besides, since this issue relates the GhostScript.Net, it is better to as post this question on the GhostScript.Net forum.
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Using Ghostscript to convert multi-page PDF into single JPG?
I know Ghostscript can convert PDFs to JPGs, and in the case of a multi-page PDF, can rip each page to an individual JPG. But is it possible to have it rip them to one JPG, so that the pages are pasted below each other, e.g. the top half of the JPG is page 1, the bottom half is page 2? Or do I have to use another program (and can ImageMagick do this?) to combine the JPG pages into one image?
- imagemagick
- ghostscript
2 Answers 2
Yes, you'll have to convert each PDF page into a single JPG file (Ghostscript can do that).
Then stitch together the resulting JPG files using another program ( ImageMagick or GraphicsMagic can do that using their montage sub-commands).
I'm not aware of any software which can do that in one go.
PDF-to-JPG conversion (with Ghostscript): You'll want to make sure that you get the best possible result. So make sure you tweak the commandline options so they work for you. I 'd start with this:
This will create JPGs called pdffile-001.jpeg , pdffile-002.jpg etc. The parameter *-dJPEGQ=95" sets "JPEG Quality" to 95%. It uses a resolution of "600x600 dpi". You may need to additionally control the pagesize of the resulting JPGs in case your Ghostscript's default doesn't fit your needs:
multiple-to-single-JPG-stitching with montage (ImageMagick or GraphicsMagick): The montage command (used in this example is ImageMagick) allows you to control the tiling pattern. If you use e.g. -tile 4x3 you'd get this imposition layout:
You could use this command to stitch together 12 individual JPGs into one:
Of course, montage has many dozen of additional parameters which allow you to determine background, spacing, offsets, decoration, labels, rotation, cropping, caption etc. for the input and the resulting JPG.
EDIT: (I had wanted to give this hint already in my original answer, but forgot.) montage by default will use tile sizes of 120x120 pixels. If you want to keep the original page sizes for each tile, you have to add -geometry to the commandline. Assuming you had A4 (=595x852 pt) pages in your PDF, and you want to keep this, but also add a spacing of 11pt to the horizontal and 22 pt to the vertical direction of the tiling (plus 4pt strong gray border/frame lines around each tile), do this:
EDIT 2: (Missed still another important hint.) If you do not want to lose the good image quality during the stitching/montage process, which your PDF-to-JPG conversion had created, then also add the -quality 100 parameter to your commandline like this:
- thank you for your answer. I don't see geometry param in ImageMagick 6.9.9. Also, the image quality of combined image is still crappy, I literally can't read a word from it. – Geek Mar 2, 2018 at 7:24
Since ImageMagick has support for GhostScript built in, you can do the whole thing in one go:
which will take every page and create one long jpeg of them end-to-end.
- 1 But this will NOT give you high quality JPG, because it will use Ghostscript with its default settings (and these are quite shi..y for JPG output). Doing it in 2 steps (and checking your JPG pages first) gives you optimal control, and it also gives you rather good JPG output). – Kurt Pfeifle Jul 27, 2010 at 22:15
- You can change the Ghostscript settings by using ImageMagick's -density setting for the PDF and get results that are as good. Don't knock IM if you're not aware of how to use its options. – erjiang Jul 30, 2010 at 16:49
- 1 k.: Hey, I didn't knock ImageMagick. And I know how to use its options, even with applying ICC color profiles... But you cannot pass all Ghostscript options to montage. My comment referred to your suggested command, which did not mention -density . – Kurt Pfeifle Aug 12, 2010 at 2:39
- Incidentally, I read elsewhere on SO that ImageMagick internally converts from PDF to PS and then PS to PNG when you invoke it this way, so that's another reason not to do it this way (two conversions=>lower quality and slower). – Ibrahim Aug 13, 2012 at 0:39
You must log in to answer this question.
Not the answer you're looking for browse other questions tagged linux pdf imagemagick ghostscript ..
- The Overflow Blog
- Is AI enough to increase your productivity?
- Featured on Meta
- What should be next for community events?
- Practical effects of the October 2023 layoff
Hot Network Questions
- Can you use the Message cantrip to grant Bardic Inspiration?
- How are custom organs controlled by the brain?
- Earth re-entry from orbit by a sequence of upper-atmosphere dips to reduce kinetic energy?
- Drawing planar mechanisms in tikz
- Do recommendation letters need to be strictly from professors at universities?
- What determines the CRL expiration date and validity in PKI?
- What would be the right way to split the profits of the sale of a co-owner property?
- Importance of copper balance when dealing with small components (0402, 0201)
- Besides the Literary Digest poll of 1936, what are some famous examples of biased samples that led to erroneous conclusions?
- Who is this decorated WWI Italian Army General?
- How to explain to 17 year olds why = can become equivalent into an <, and vice versa?
- Comparator doesn't compare inputs close to VCC
- Do universities check if the PDF of Letter of Recommendation has been edited?
- Is it possible to replace/regear the front cog? My easiest gear is too easy and I want to try for a higher resistance
- Is it a Valid Crossword Grid?
- What does Newton's Theorem XXXIII in his book "Principia" mean?
- On the topic of worry in his Sermon on the Mount, why did Jesus not address the fundamental human need for shelter?
- What does a space mean in a resistor value on a schematic?
- What are 'The cobweb clues of Rosamond'?
- Why might a flight have the same departure airport as its destination?
- One day, his son developed or encountered a serious stomachache?
- When Friday asks Robinson "Why God no kill the devil", why can't Robinson find a proper answer?
- Which real world computers are the workstations shown at the Daily Planet in the DCAU show Superman: The Animated Series based on?
- Why is it sufficient to shore up a ceiling on 1 side of load bearing wall?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

You are using an outdated browser. Please upgrade your browser to improve your experience.
Convert a PDF into a series of images using C# and GhostScript
Blog articles and information on c# and .net development topics.
This content has moved - please find it at https://devblog.cyotek.com.
Although these pages remain accessible, some content may not display correctly in future as the new blog evolves.
Visit https://devblog.cyotek.com .
An application I was recently working on received PDF files from a webservice which it then needed to store in a database. I wanted the ability to display previews of these documents within the application. While there are a number of solutions for creating PDF files from C#, options for viewing a PDF within your application is much more limited, unless you purchase expensive commercial products, or use COM interop to embed Acrobat Reader into your application.
This article describes an alternate solution, in which the pages in a PDF are converted into images using GhostScript, from where you can then display them in your application.

In order to avoid huge walls of text, this article has been split into two parts, the first dealing with the actual conversion of a PDF, and the second demonstrates how to extend the ImageBox control to display the images.
Caveat emptor
Before we start, some quick points.
- The method I'm about to demonstrate converts each page of the PDF into an image. This means that it is very suitable for viewing, but interactive elements such as forms, hyperlinks and even good old text selection are not available.
- GhostScript has a number of licenses associated with it but I can't find any information of the pricing of commercial licenses.
- The GhostScript API Integration library used by this project isn't complete and I'm not going to go into the bells and whistles of how it works in this pair of articles - once I've completed the outstanding functionality I'll create a new article for it.
Getting Started
You can download the two libraries used in this article from the links below, these are:
- Cyotek.GhostScript - core library providing GhostScript integration support
- Cyotek.GhostScript.PdfConversion - support library for converting a PDF document into images
Please note that the native GhostScript DLL is not included in these downloads, you will need to obtain that from the GhostScript project page
Using the GhostScriptAPI class
As mentioned above, the core GhostScript library isn't complete yet, so I'll just give a description of the basic functionality required by the conversion library.
The GhostScriptAPI class handles all communication with GhostScript. When you create an instance of the class, it automatically calls gsapi_new_instance in the native GhostScript DLL. When the class is disposed, it will automatically release any handles and calls the native gsapi_exit and gsapi_delete_instance methods.
In order to actually call GhostScript, you call the Execute method, passing in either a string array of all the arguments to pass to GhostScript, or a typed dictionary of commands and values. The GhostScriptCommand enum contains most of the commands supported by GhostScript, which may be a preferable approach rather than trying to remember the parameter names themselves.
Defining conversion settings
The Pdf2ImageSettings class allows you to customize various properties of the output image. The following properties are available:
- AntiAliasMode - specifies the antialiasing level between Low, Medium and High. This internally will set the dTextAlphaBits and dGraphicsAlphaBits GhostScript switches to appropriate values.
- Dpi - dots per inch. Internally sets the r switch. This property is not used if a paper size is set.
- GridFitMode - controls the text readability mode. Internally sets the dGridFitTT switch.
- ImageFormat - specifies the output image format. Internally sets the sDEVICE switch.
- PaperSize - specifies a paper size from one of the standard sizes supported by GhostScript.
- TrimMode - specifies how the image should be sized. Your milage may vary if you try and use the paper size option. Internally sets either the dFIXEDMEDIA and sPAPERSIZE or the dUseCropBox or the dUseTrimBox switches.
Typical settings could look like this:
Converting the PDF
To convert a PDF file into a series of images, use the Pdf2Image class. The following properties and methods are offered:
- ConvertPdfPageToImage - converts a given page in the PDF into an image which is saved to disk
- GetImage - converts a page in the PDF into an image and returns the image
- GetImages - converts a range of pages into the PDF into images and returns an image array
- PageCount - returns the number of pages in the source PDF
- PdfFilename - returns or sets the filename of the PDF document to convert
- PdfPassword - returns or sets the password of the PDF document to convert
- Settings - returns or sets the settings object described above
A typical example to convert the first image in a PDF document:
The inner workings
Most of the code in the class is taken up with the GetConversionArguments method. This method looks at the various properties of the conversion such as output format, quality, etc, and returns the appropriate commands to pass to GhostScript:
As you can see from the method above, the commands are being returned as a strongly typed dictionary - the GhostScriptAPI class will convert these into the correct GhostScript commands, but the enum is much easier to work with from your code! The following is an example of the typical GhostScript commands to convert a single page in a PDF document:
The next step is to call GhostScript and convert the PDF which is done using the ConvertPdfPageToImage method:
As you can see, this is a very simple call - create an instance of the GhostScriptAPI class and then pass in the list of parameters to execute. The GhostScriptAPI class takes care of everything else.
Once the file is saved to disk, you can then load it into a Bitmap or Image object for use in your application. Don't forget to delete the file when you are finished with it!
Alternatively, the GetImage method will convert the file and return the bitmap image for you, automatically deleting the temporary file. This saves you from having to worry about providing and deleting the output file, but it does mean you are responsible for disposing of the returned bitmap.
You could also convert a range of pages at once using the GetImages method:
In conclusion
The above methods provide a simple way of providing basic PDF viewing in your applications. In the next part ] of this series, we describe how to extend the ImageBox component to support conversion and navigation.
Update History
- 2011-09-04 - First published
- 2012-07-10 - Added follow up article links
- 2020-11-21 - Updated formatting
About The Author
The founder of Cyotek, Richard enjoys creating new blog content for the site. Much more though, he likes to develop programs, and can often found writing reams of code. A long term gamer, he has aspirations in one day creating an epic video game. Until that time, he is mostly content with adding new bugs to WebCopy and the other Cyotek products.
Leave a Comment
While we appreciate comments from our users, please follow our posting guidelines . Have you tried the Cyotek Forums for support from Cyotek and the community?
Styling with Markdown is supported
DotNetShoutout
# 04 September 2011 Reply
[b]Convert a PDF into a series of images using C# and GhostScript[/b] Thank you for submitting this cool story - Trackback from DotNetShoutout
DotNetKicks.com
[b]Convert a PDF into a series of images using C# and GhostScript[/b] You've been kicked (a good thing) - Trackback from DotNetKicks.com
# 07 September 2011 Reply
Thank you for this. Please change for support of other languages/codepages, i.e. german Umlaute. Thanks
Richard Moss
Thanks for the comment - could you clarify what were having a problem with so I can look into it further?
Regards; Richard Moss
# 29 September 2011 Reply
Thank you very much. You made my day dude.
# 01 November 2011 Reply
I used your library into sharepoint 2010 workflow on server on 64 bit and I get this error:
Unable to load DLL 'gsdll32.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)?
Why? On the server I installed ghostscript x64 and x86...
While I haven't tested this in SharePoint, or indeed on a server full stop, the most likely cause is gsdll32.dll isn't in your path - either copy it to the folder where your assemblies are deployed, or into a folder which is part of your path, such as \Windows\SysWOW64
Hope this helps; Richard Moss
chandrasekhar
# 31 March 2012 Reply
Hi, I am getting the following error when i load a pdf file into Picturebox "Failed to process GhostScript command." Please help me ...
This error is thrown when Ghostscript cannot perform the action was requested of it. There could be any number of causes, with such limited information I have no way of knowing. Check the the exception object for the Ghostscript result code and the arguments provided.
# 04 April 2012 Reply
Hi How to convert pdf to bmp images in c# . Any examples for converting of pdf to bmp images? Please help me
That's exactly what this article does; converts a PDF into a series of images. To save them into bitmaps, call the Save method of one of the images passing in the ImageFormat.Bmp format.
# 05 April 2012 Reply
Hi. I am getting this error when i try to convert pdf2image(.GetImage()). The Error is "Unable to find an entry point named 'gsapi_new_instance' in DLL 'gsdll32.dll'.". Note : Web Application bin dir have gsdll32.dll and i am not installed ghostscript.exe. How can i get it?
# 06 April 2012 Reply
As I've already noted to another commenter, I haven't tested this on a server environment or in a web application and so I can't assist on deployment issues. The error would indicate that while a DLL is present and loaded, it doesn't actually contain the function that is being requested of it. That would most likely indicate the wrong version of Ghostscript being loaded or perhaps a custom build that doesn't export the function. Or it could be an error in the C# function declaration. Sorry for not being specific, but there's no single cause.
# 01 February 2013 Reply
I had the same issue. I fixed it by installing an older version (8.54). As far as deployment is concerned, you can copy the folder gs\gs8.54\lib independently and set an environment variable "GS_LIB" with the value pointing to the lib folder.
# 10 May 2012 Reply
Is this dll will work against IIS 7.5 and 64 bit OS/Windows 7?
It should work if your application is 32bit as it's calling the 32bit version of Ghostscript (I haven't looked to see if there's a 64bit version of the library - if there is just replace the calls). As long as the correct DLL's are in your path, then it should work fine. But as I've noted multiple times above, I haven't tested this in a server environment at this point in time so I can't say for definite.
# 14 May 2012 Reply
You can solve this issue with following steps(If you are using Windows 7(64 bit) OS and IIS7 or above manager ) Pdf2Image should work with this settings
1)Visual Studio 2008 Project Properties : Go Build->Configuration Manager... Change 'AnyCPU' to x86 Click OK
2) IIS7 or above manager: Application Pool and select “Advanced Settings…” Change the “Enable 32-bit Applications” to True Click OK
Thanks for the information, hopefully this will help others!
IIS6 can also be set to run in 32bit mode, although it's a little more complicated than 7.
# 22 May 2012 Reply
Thank you so much! It works!
Raymond Lai
# 29 May 2012 Reply
Hi Richard, I got sever errors when I try to compile your 2 projects in VS2005. 'Cyotek.GhostScript.GhostScriptException.Arguments.get' must declare a body because it is not marked abstract or extern' d:\Cyotek.GhostScript\GhostScriptException.cs Ln:74 Col:33 yotek.GhostScript
# 03 June 2012 Reply
This is because the sample is using auto generated properties. Essentially, the C# 3+ compiler will let you just declare a property and it will take care of the backing field and body.
In the example you quoted, line 74 is this:
public string[] Arguments { get; protected set; }
In order to make it compile, you'll need to "expand" this, for example:
As far as I know, there's no way of making auto generated properties work in that version of Visual Studio, sorry.
S. Vikneshwar
# 04 July 2012 Reply
Can i get the same code for asp.net
# 05 July 2012 Reply
Can the same thing be done with asp.net. I tried but couldnt? Can you post any updates and let notify me with that. In case if it can be done can you mail it to my id?? Im in real need of it. My mail id is [email protected]
Thanks and regards. S. Vikneshwar
# 10 July 2012 Reply
For a sample project which works in ASP.NET, please see the following article: http://cyotek.com/blog/displaying-the-contents-of-a-pdf-file-in-an-asp-net-application-using-ghostscript
# 05 August 2012 Reply
Hi, The GhostScriptAPI class looks like only support English file name, when I used some asian characters file names such as Japanese, Chinese as parameters to call it, and it returned the error message "Failed to process GhostScript command." Could you give me some suggestion? Thank you.
# 21 August 2012 Reply
According to this comment (http://sourceforge.net/projects/ghostscript/forums/forum/5451/topic/3303450) Ghostscript is an ANSI application and so doesn't support Unicode. That post is from 2009, not sure if anything has changed since then, but unfortunately it nothing has changed I don't think you could do anything about it unless you compiled the Ghostscript source code yourself and made whatever changes were required for Unicode support.
Sathishkumar
Hi All, I have one requirement like open the existing PDF document and edit - basically add some image on the particular place and save them in PDF file. 1) Is it possible to edit the pdf after conversion into image in your image editor then finally generate the again the image into pdf? 2) Is there any library where i can load the existing pdf and edit them and finally save into the pdf document?
Please let me know your suggestion for above requirement apart from doubt also
Thanks and Regards, Sathish
I'm not aware of any libraries that support extended editing of a PDF file, although there's quite a few that would let you create them. Open source ones include PDFSharp and iTextSharp. I've also used cete's Dynamic PDF extensively (this is a commercial product) and while it would allow you create PDF files it has a disappointingly limiting API and is overall a poor product. We are currently evaluating TallPDF which already seems to be an order of magnitude better than cete's offering, although I personally haven't used it yet. However, there's lots and lots of libraries out there!
Sorry I can't be of more help. I've done lots of work generating PDF's, but not editing them :)
# 01 November 2012 Reply
Hi I am using your library to build a console application but the library always throws a GhostScriptException. I have checked the output and found the arguments are supplied correctly. The output file was indeed generated to the designated directory but the result variable held a value of -100 and an exception was thrown.
I am using Windows 7 (64-bit), the 32-bit version of gsdll32.dll and Visual Studio 2010. I have also set the platform target to x86 as suggested above
# 05 November 2012 Reply
This appears to be a generic code for which there could be any number of causes, afraid I can't really help you here. I did find this post (http://stackoverflow.com/questions/4340407/what-is-causing-ghostscript-to-return-an-error-of-100) which may help?
Where do you place the gsdll32.dll for a web application? in the bin folder? or make a custom folder like lib? I tried this and then adding network service and IIS read/write permissions to the folder but I get a Unable to load DLL 'gsdll32.dll': error.
Did you check my article on my experiences of testing using ASP.net (http://cyotek.com/blog/displaying-the-contents-of-a-pdf-file-in-an-asp-net-application-using-ghostscript)?
It needs to be in the bin folder (or system32 worked as well as I recall), but the important thing is that you have IIS set to run your app as 32bit if you are using the 32bit dll. From your comment, it sounds like either it's not in the path, or it's running in 64bit - take a peek at the article and see if this helps you.
# 27 November 2012 Reply
Hello! I've encountered an issue wherein the Ghostscript fails when trying to load a PDF stored on a network share. It returns a generic -100 error code. Have you any ideas on how to solve this? Am I correct in that DLLImport loads Ghostscript as a separate process, away from ASP.NET process? I'm concerned that permissions are preventing Ghostscript from loading the file. Alternatively, can ahe PDF be accessed from a Stream object of some sort?
# 04 December 2012 Reply
Hello! Is there any possibility to convert pdf obtained from Stream(not from file)? Thank you!
As GhostScript is an unmanaged third party library I would expect that no, you can't use streams. I'd expect you'd need to save your stream to a temporary file and call GS with that. At the same time however, I have only tested GS with files, it's possible it has additional support for other inputs - you'd have to check it's documentation.
# 03 January 2013 Reply
I'm trying to convert a PDF to a PNG with a fixed size in pixels. My problem is that (no matter what I do) the images are always generated with the size 612 x 792 pixels (the default papersize = letter)? I set the TrimMode to PaperSize and I've tried A4, A3 and A0. My code:
var converter = new Pdf2Image(Document.FullName, new Pdf2ImageSettings { ImageFormat = Cyotek.GhostScript.ImageFormat.Png24, GridFitMode = GridFitMode.Topological, TrimMode = PdfTrimMode.PaperSize, PaperSize = PaperSize.A0 });
# 28 February 2013 Reply
Thanks for this great project! How can I modify the code (or part of it) to increase the speed of the PDF to image convertion? I need to convert some very big PDF files and/or with lots of pages.
# 06 May 2013 Reply
Great work! And with some code changes for multi page pdf, the speed is 10 time faster. Thanks!
Great work!And with some code changes for multi page pdf, the speed is 10 time faster.Thanks!
# 20 January 2015 Reply
Hi, Dan my problem is regarding your smartness i need to process more no of pages but it makes performance issue i.e it going very slow when processing more number of pages please tell me how to solve this problem
# 29 May 2013 Reply
I have an error in the "PdfImageBoxSample" project...
Error: Failed to process GhostScript command.
# 30 August 2013 Reply
Doest it supports for Parallel programming? poor performance in processing large file, though its free, worth to implement where performance is not a matter.
Does it support for all the versions of PDF?
The source code I have provided doesn't explicitly include this and I don't generally include such language features in my samples as I want them to be a bit more accessible and also the use of such code has its own overheads and so shouldn't just be thrown in without thought. While I haven't tested it, I don't see any reason why, for example, the GetImages method couldn't use Parallel.For . But a lot of the code on this site is concept code or example code to demonstrate techniques, in which case obfuscating them with obscure language constructs is not my goal.
In regards to the PDF version I don't know - you'd need to consult the GhostScript documentation for that.
# 01 October 2013 Reply
I use Ghostscript in my asp.net mvc application. Wich is placed on the server. Ghostscript works but not all PDF files for some of the files I get the message Failed to Process .. Ghostscript command. "For others it is all good. I use the following settings Pdf2ImageSettings see = new Pdf2ImageSettings { Dpi = 100; ImageFormat = ImageFormat.Jpeg, PaperSize = PaperSize.Foolscap }; Has anyone had this problem
# 17 April 2014 Reply
Great work!
Only one issue: the GetPdfPageCount() method does not work with all pdf's - for example encrypted documents or pdf with document level attachments. I used iTextSharp instead:
Thanks for the comments! As I recall (I haven't touched this code for a great while now), I took that particular code from elsewhere - I have no knowledge of the PDF format myself so wasn't aware of encryption or otherwise. Thanks for pointing this out though! I do use iTextSharp in other projects though, I'll make sure to use that instead should I revisit this code down the line.
Thanks again; Richard Moss
# 25 April 2014 Reply
Is it possible for you to write a sample code for beginners like a c# code that uses your libraries. I used package manager to Install-Package GhostScriptSharp but most of the classes show error under their names. I can clearly see GhostscriptSharp added to reference. What do I need to do make those errors go away. These types are not recognized e.g GhostScriptCommand, GhostScriptAPI, AntiAliasMode etc. I have added both projects provided to my solution too. please help. Thanks.
Sorry, I'm afraid I can't really help - that isn't one of our packages and I'm not able to provide support for other peoples packages. I have seen this sort of thing before, typically when a .NET 4.0 reference is added to a .NET 3.5 project - perhaps try re-targeting your project to the latest version of .NET and see if that resolves your issue.
# 07 May 2014 Reply
Hey Richard, Thanks a lot for this brilliant project, I've been looking everywhere for some way to convert a PDF to images, one would think it should be pretty simple, but other than expend $500+ on some complex component I was unable to find anything until I found your blog. Anyways, I've been getting an awful -7 error code on the NativeMethods.gsapi_init_with_args call. I've tried several different PDFs and settings combinations, but no joy. Any thoughts or pointers to a possible source for the issue would be greatly appreciated. The latest settings I've been trying are this: AntiAliasMode = AntiAliasMode.None; Dpi = 100; GridFitMode = GridFitMode.None; ImageFormat = CyotekImageFormat.Jpeg; TrimMode = PdfTrimMode.PaperSize;
Again, thanks and keep up the good work man
hi it very nice and so good it perform well on single request at a time and 2 request with small file size but it through an exception as "Failed to process GhostScript command." when processing 2 request with each file have 992kb file size how can solve this problem help me.
# 16 July 2015 Reply
Dear Richard,
This is such a great piece of software, exactly what i was after, if anybody else is running this on a windows 7 64 bit machine you have to put the gsdll32.dll into the c:/windows/sysWoW64 folder to get it to work..
Just a quick question. I am using this to create icons about 100 px width of the first page of the PDF file. The images generated are quite large, .pngs about 1.4MB filesize each. Is there a way to reduce the size of the images created?
I saw there was a setting convertor.Settings.PaperSize - but was unsure how to use this or if this was right. The images shrink down but it would be good if they could be smaller when generated.
many thanks
# 25 July 2015 Reply
It's been a long time since I looked a GhostScript so I can't say for sure if this is possible or not. You could try and calculate a paper size yourself to see if that helps using a combination of the dDEVICEWIDTHPOINTS , dDEVICEHEIGHTPOINTS and dFIXEDMEDIA GhostScript commands. You might find more info in the GhostScript docs for these switches
It might be easier just to take the output GhostScript gives you and then do your own post processing on the image to make them 100x100px and reduce the file size.
# 03 August 2015 Reply
Thanks for this API worked well until this morning. I was able to take a PDF and crop its image using a rectangle as parameter. Everything worked well! But this morning i'm stuck with this error "Failed to process ghostscript command" (this is one of your defined exception), but when i look at the execution result, i have the -100 code error. But every argument is ok, i didn't change anything since friday when it worked... I'm a bit lost, do you have any explanation about the -100 error code?
If you need any other piece of information, feel free to ask.
Thank you so much again for this API that worked well until this morning...
# 10 August 2015 Reply
I'm sorry, but I have no idea - -100 is a GhostScript result code and their documentation on this is ... well, rubbish - " Fatal Error ". I'm sure you knew that already...
If none of the arguments have changed, then perhaps it's the source file - did you try with a different PDF (one that worked previously?). Do you verify the arguments (for example, does that rectangle you mention fit within the bounds of the PDF you are using?)
ROHIT MAHESHWARI
Hi Richard, Thanx for nice article. Could you please tell me how to use the same if pdf is password protected.
There's a PdfPassword property on the Pdf2Image class that you could use. (I don't recall if I tested it or not as I don't generally work with password protected PDF's)
A simple search of the source for "password" would have given you the answer immediately, instead of me having to answer the same question in two different places :)
Jonathan Kim
# 26 October 2015 Reply
It works well on Windows7(32bit), but is not works on WIndows10(64bit)... How can I worked? Please help me...ASAP i worked already 4days...(i used setting options default. am i wrong???)
result = NativeMethods.gsapi_init_with_args(_ghostScriptInstance, args.Length, _argumentPointersHandle.AddrOfPinnedObject());
result = -100
# 14 December 2015 Reply
Hey , please can you make a youtube video for using this in an asp.net application. Because i am having a hard time including your libraries and using them. I know it is a great solution so please can you make a Sample on asp.net from scratch and record it (while making it) and share. Please also mail me when done.
# 15 December 2015 Reply
Sorry, I won't be doing video tutorials. I don't like them, they have (in my view) no advantage over a nicely written piece of text but do have plenty of disadvantages. I have already provided a full working sample ASP.net project in another post, and on top of that I have not used GhostScript since writing these articles.
# 29 February 2016 Reply
Currently I am using GhostScript dll in one of my services to convert pdf to images. GhostScriptAPI Execute method is called to convert pages of pdf into images. I am facing an issue when trying to convert multiple pdf files simultaneously using thread, but GhostScriptAPI cannot able to process in parallel. Can you please let me know any way so, I can use GhostScriptAPI dll in parallel.
using (GhostScriptAPI api = new GhostScriptAPI()) { api.Execute(this.GetConversionArguments(this.pdfFileName, outputFileName, pageNumber, this.PdfPassword, this.Settings)); } Issue occurs when two threads pdf's are processed at same time.
# 01 March 2016 Reply
I had a quick glance at the GhostScriptAPI class to refresh my memory, it has been some time since I looked at it. As far as I can see, it is self contained so should work in parallel. If it doesn't, then it is most likely because the native Ghostscript DLL doesn't support this. And in fact a 30 second check of the documentation finds
At this stage, Ghostscript supports only one instance.
You could try creating a single instance of the GhostScriptAPI class and then using that in your parallel loop, as I'm assuming right now you're creating one instance per thread. However, I suspect this won't work either the arguments are bound to that single instance ID. You might be better off asking the authors of Ghostscript themselves about parallel support.
Sorry I can't be of more help.
# 21 March 2016 Reply
Hi fi getting following error
"Page number is out of bounds Parameter name: pageNumber"
This is my c# code
please help me Thanks in advance
# 24 May 2016 Reply
Hi Sir My name is jaid ahmed i am using PdfToImage dll but there is problem using PdfToImage to gsdll32.dll for 64 bot os, i want PdfToImage to gsdll64.dll. because in metafile of PDFconverter there is mention gsdll32.dll so i want i want PdfToImage to gsdll64.dll. can you help me please.
# 25 May 2016 Reply
As Ghostscript is a traditional Win32 DLL, in order to use it from .NET you have to use something called platform invoke . If you check the source code for this article, in the NativeMethods.cs file are a bunch of declarations decorated with the DllImport attribute - these say which DLL to use, in this case gsdll32.dll . Assuming that the 32bit and 64bit versions are identical (I have no idea myself), then simply replacing all those occurrences with the 64bit DLL name will be enough. You would also need to ensure that your client application is set to run in 64bit mode, otherwise it probably won't work.
If you need more help with p/invoke, you can refer to the MSDN article I linked at the start of this comment.
Govinda Rajbhar
# 16 November 2016 Reply
Every thing working great but want to increase the speed of the PDF to images convertion? Is there any way to achieve fast performance?
Thanks for the question. While there is possible some optimisation work that can be done to the managed assembly I wrote, the native GhostScript API is doing pretty much all the work and there's nothing I can do to influence that. There may be additional GhostScript parameters that can be used to produce a faster image at the expense of quality, but I don't know - you're best off looking at the GhostScript documentation and seeing what sort of options if offers.
steven frierdich
# 12 May 2021 Reply
any change you updating this code for .net core 3.1 using ghostsriptnetcore
This content may be used free of charge, but as with all free content there are costs involved to develop and maintain.
If this site or its services have saved you time, please consider a donation to help with running costs and timely updates.
Popular Tags
View all tags
- April 2023 (1)
- January 2023 (1)
- All of 2022 (2)
- All of 2021 (2)
- All of 2020 (15)
- All of 2019 (15)
- All of 2018 (9)
- All of 2017 (25)
- All of 2016 (12)
- All of 2015 (17)
- All of 2014 (13)
- All of 2013 (17)
- All of 2012 (13)
- All of 2011 (9)
- All of 2010 (18)
- All of 2009 (1)
Open Source
- ImageBox Control
- ColorPicker Controls Suite
- Dithering Techniques
- CircularBuffer Library
- BMFont Parsing Library
- NBT Library
- TabList Control
- Add Projects Visual Studio Extension
- Simple Screenshot Capture
- MantisSharp Library
- FontDialog Replacement
- ScannerTest
- Registry Comparer Utility
- HTTP Crawler Test Website
- CyotekDownDetector
- ScriptingHostDemo
- SourceSafe to SVN Migration
- Skyline Generator
- ColorEcho Utility
- InternetGetCookieExDemo

IMAGES
VIDEO
COMMENTS
Sometimes the need arises to change a photo or image file saved in the .jpg format to the PDF digital document format. With the right software, this conversion can be made quickly and easily.
In today’s digital age, the ability to convert files from one format to another has become increasingly important. One such conversion that is commonly needed is converting JPG images to PDF format.
In today’s digital age, converting JPG images into PDF format has become a common practice. Whether you need to send important documents or simply want to preserve the quality of your images, converting them into PDF offers numerous benefit...
Batch convert PDF files to image format such as PNG and JPEG easily using Ghostscript.
I'm wondering is there any way to pass arguments through convert to GhostScript or am I stuck with calling GhostScript directly? image · pdf
TLDR; Run the following Ghostscript command to convert a pdf file to a series of png files. PDF files frequently contain data (text, images…
Pdf2Image (1).zip. Ghostscript is an interpreter for the PostScript language and for PDF.
GetPage(xDpi, yDpi, pageNumber);. Finally we are saving the images. pdf2PNG.Save(outputPNGPath
Script to convert PDF to JPEG using Ghostscript library. Works well even with very big and heavy PDF files which hang up Adobe Acrobat. Of course there is no
How to use Ghostscript library to create an image (or images) from a PDF file.
I am using GhostScript.Net to convert Pdf files to Png images. This ... save the png's pdf2PNG.Save(outputPNGPath, ImageFormat.Png); }.
I have a large set PDF documents, many of which will be multiple pages. I am using Ghostscript [GS] to generate a JPG thumbnail image for each
Or do I have to use another program (and can ImageMagick do this?) to combine the JPG pages into one image? linux · pdf · imagemagick
The following properties and methods are offered: ConvertPdfPageToImage - converts a given page in the PDF into an image which is saved to disk