Create PDF Document and Convert to Image Programmatically

The Portable Document Format (PDF) is a file format used to present documents in a manner independent of application software, hardware and operating systems. Each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, graphics and other information needed to display it. As a program developer, sometimes we will need to manipulate PDF documents programmatically. When you search the Internet, you will find many products, all of which might be very nice and useful, but I will recommend two products used in my work to you, that are more wonderful, one is ItextSharp, the other one is Spire.PDF.

This article shows how to create a PDF and convert it to an image in a relatively easy method to use the two libraries.

The first step is to create a simple PDF document with ItextSharp.

Namespace to be used:

  1. using iTextSharp.text;   
  2. using iTextSharp.text.pdf;  
Here is the code:
  1. Document document = new Document();  
  2. PdfWriter.GetInstance(document, new FileStream("Sample.pdf", FileMode.Create));  
  3. document.Open();  
  4. document.Add(new Paragraph("Hello World"));  
  5. PdfPTable table = new PdfPTable(3);  
  6. table.SpacingBefore = 30f;  
  7. table.SpacingAfter = 30f;  
  8. PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));  
  9. cell.Colspan = 3;  
  10. cell.HorizontalAlignment = 1;   
  11. table.AddCell(cell);  
  12. table.AddCell("Col 1 Row 1");  
  13. table.AddCell("Col 2 Row 1");  
  14. table.AddCell("Col 3 Row 1");  
  15. table.AddCell("Col 1 Row 2");  
  16. table.AddCell("Col 2 Row 2");  
  17. table.AddCell("Col 3 Row 2");  
  18. document.Add(table);  
  19. Image image = Image.GetInstance("1.PNG");  
  20. document.Add(image);  
  21. document.Close();  

Here is how it looks.

hello word

As you can see, it is easy, you could also set the style of the table, add the image, and so on.

Next is to convert the PDF document generated by ItextSharp to an image with Spire.Pdf.

Step 1

Open the PDF document.

To open a document the Spire.PDF library contains a PdfDocument class, that allows loading PDF documents in many formats, stream, byte, and so on. Here I use the file source path:

  1. PdfDocument pdfdocument = new PdfDocument("Sample.pdf");  

Step 2

Iterate through the PDF document pages and save it as an image.

Now I iterate through the pages the PDF contains, then save it as an image. In the SaveAsImage method, we can set the DPI of the image. Here is the code:

  1. for(int i=0;i< pdfdocument.Pages.Count;i++)  
  2. {  
  3.       System.Drawing.Image image= pdfdocument.SaveAsImage(i, 96, 96);  
  4.       image.Save(string.Format("ImagePage{0}.png", i), System.Drawing.Imaging.ImageFormat.Png);  
  5. }  
Effect screenshot:

Effect screenshot

I hope you enjoy this article.

Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all