Download and convert image to PDF

Generate PDF, Images, Shapes
9/27/2010

This article shows how to download an image on a web page as a PDF document. The image to PDF conversion is done on the fly.

pageshot.PNG

ASPX page

The aspx page is extremely simple. Basically it consists of an img element and a ActionLink element as shown in the following code snippet.

1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head runat="server"> 4 <title>Index</title> 5 </head> 6 <body> 7 <div> 8 <img src="../image.png" /> 9 <br /> 10 @Html.ActionLink("Click here!", "Convert") 11 </div> 12 </body> 13 </html>

Code-behind file

The code-behind file consists of just the OnClick handler. It creates a document, adds a page that has the same size as the image, adds an image shape to the page and then streams the PDF document to the client.

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using TallComponents.PDF; 6 using TallComponents.PDF.Shapes; 7 using System.Web.Mvc; 8 using System.IO; 9 10 namespace ImageToPDFWeb.Controllers 11 { 12 public class PDFController : Controller 13 { 14 public ActionResult Index() 15 { 16 //show the index page to the client 17 return View(); 18 } 19 20 public FileStreamResult Convert() 21 { 22 //Create a new PDF document and add the image as an overlay to a page 23 Document document = new Document(); 24 ImageShape image = new ImageShape( 25 Server.MapPath(@"..\image.png")); 26 Page page = new Page(image.Width, image.Height); 27 page.Overlay.Add(image); 28 document.Pages.Add(page); 29 30 //since we don't write to disk, write the pdf to a memory stream and return it as a pdf 31 MemoryStream ms = new MemoryStream(); 32 document.Write(ms); 33 ms.Flush(); 34 ms.Position = 0; 35 return File(ms, "application/pdf"); 36 } 37 } 38 }