Tuesday 15 April 2014

Displaying Contents of a PDF file in Application using GhostScript

What is GhostScript?

Ghostscript is a package of software that provides an interpreter for the PostScript (TM) language, with the ability to convert PostScript language files to many raster formats, view them on displays, and print them on printers that don't have PostScript language capability built in; An interpreter for Portable Document Format (PDF) files, with the same abilities; The ability to convert PostScript language files to PDF (with some limitations) and vice versa; and A set of C procedures (the Ghostscript library) that implement the graphics and filtering (data compression / decompression / conversion) capabilities that appear as primitive operations in the PostScript language and in PDF.


Features of GhostScript:
  1. Raster image processor (RIP): Raster computer printers—for instance, as an input filter of line printer daemon—or as the RIP engine behind PostScript and PDF viewers.
  2. File Format Converter: PostScript to PDF converter or PDF to raster image (png, tiff, jpeg, etc) converter; this is often combined with a PostScript printer driver in "virtual printer" PDF creators.
  3. General purpose programming environment.

How we can achieve:
  1. You can use http://www.ghostscript.com/download/gsdnld.html link to get ghostscript latest build for development.
  2. Create a new ASP.NET Web Forms Site.
  3. Open up Default.aspx and add some controls similar to the following:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GhostScriptWebTest._Default" %>

<!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 id="Head1" runat="server">
    <title>PDF Conversion Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            <asp:LinkButton runat="server" ID="previousLinkButton" Text="Previous" OnClick="previousLinkButton_Click" />
            <asp:LinkButton runat="server" ID="nextLinkButton" Text="Next" OnClick="nextLinkButton_Click" />
        </p>
        <p>
            <asp:Image runat="server" ID="pdfImage" ImageUrl="~/PdfImage.ashx?fileName=sample.pdf&page=1" />
        </p>
    </div>
    </form>
</body>
</html>


4.  Creating the image handler

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using Cyotek.GhostScript.PdfConversion;

namespace GhostScriptWebTest
{
  public class PdfImage : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      string fileName;
      int pageNumber;
      Pdf2Image convertor;
      Bitmap image;

fileName = context.Server.MapPath("~/" + context.Request.QueryString["fileName"]);
      pageNumber = Convert.ToInt32(context.Request.QueryString["page"]);

      // convert the image
      convertor = new Pdf2Image(fileName);
      image = convertor.GetImage(pageNumber);

      // set the content type
      context.Response.ContentType = "image/png";

      // save the image directly to the response stream
      image.Save(context.Response.OutputStream, ImageFormat.Png);
    }

    public bool IsReusable
    { get { return true; } }
  }
}

5.  Now that we can display our PDF, we'll add some basic navigation. Open up the code behind file forDefault.aspx and fill in the event handlers for the two hyperlink buttons.

using System;
using System.Collections.Specialized;
using System.Web;
using Cyotek.GhostScript.PdfConversion;

namespace GhostScriptWebTest
{
  public partial class _Default : System.Web.UI.Page
  {
    protected void previousLinkButton_Click(object sender, EventArgs e)
    {
      this.IncrementPage(-1);
    }
     protected void nextLinkButton_Click(object sender, EventArgs e)
    {
      this.IncrementPage(1);
    }
   private void IncrementPage(int increment)
    {
      NameValueCollection queryString;
      int pageNumber;
      string pdfFileName;
      Pdf2Image converter;

 queryString = HttpUtility.ParseQueryString(pdfImage.ImageUrl.Substring(pdfImage.ImageUrl.IndexOf("?")));
 pdfFileName = queryString["fileName"];
 pageNumber = Convert.ToInt32(queryString["page"]) + increment;
 converter = new Pdf2Image(this.Server.MapPath("~/" + pdfFileName));

if (pageNumber > 0 && pageNumber <= converter.PageCount)
pdfImage.ImageUrl = string.Format("~/PdfImage.ashx?fileName={0}&page={1}", pdfFileName, pageNumber);
 }
 }
}

About Author:
Nimish Jethwa is budding technology geek, who helps Systems Plus with his creativity and research on technology. He works in systems Plus and actively contributes to technology. He can be contacted at: nimish.j@spluspl.com

1 comment: