Download and convert image to PDF

This article shows how to download an image on a web page as a PDF document. The image (JPG, PNG or any other raster format) to PDF conversion is done on the fly. Download a free trial of PDFKit.NET to try the image to PDF converter to convert JPG (or any other raster format) to PDF and more.

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

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.

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
        <img src="../image.png" />
        <br />
        @Html.ActionLink("Click here!", "Convert")
    </div>
</body>
</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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TallComponents.PDF;
using TallComponents.PDF.Shapes;
using System.Web.Mvc;
using System.IO;

namespace ImageToPDFWeb.Controllers
{
    public class PDFController : Controller
    {
        public ActionResult Index()
        {
            //show the index page to the client
            return View();
        }

        public FileStreamResult Convert()
        {
            //Create a new PDF document and add the image as an overlay to a page
            Document document = new Document();
            ImageShape image = new ImageShape(
              Server.MapPath(@"..\image.png"));
            Page page = new Page(image.Width, image.Height);
            page.Overlay.Add(image);
            document.Pages.Add(page);

            //since we don't write to disk, write the pdf to a memory stream and return it as a pdf
            MemoryStream ms = new MemoryStream();
            document.Write(ms);
            ms.Flush();
            ms.Position = 0;
            return File(ms, "application/pdf");
        }
    }
}
Download PDFKit.NET 5.0
We will send you a download link
Why do we ask your email address?
We send tips that speed up your evaluation
We let you know about bug fixes
You can always unsubscribe with one click
We never share your address with a 3rd party
Thank you for your download

We have sent an email with a download link.