Skip to main content

Generate PDF, screenshot of a webpage in c# using phantomjs

In this post i will explain how to capture screenshot and how to create PDF of a webpage using Phantomjs.

I searched a lot for html to pdf converter and found some of the solution but they were not rendering webpage currectly and even not supporting css and styling, eventually i found two best solution which supports latest css, styling and render webpage as it is in browsers, first of them is Phantomjs and second is Pechkin.

Here i going to use Phontomjs and in my next article i will explain how to generate PDF from webpage through Pechkin.

Here is little bit about Phontomjs -

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG, this is a command line utility it is always try to start command prompt process to work.

You can find more about phantomjs and how to install it in your project from this link http://phantomjs.org/

Creating PDF of a webpage using phantomjs -

protected void btnPdf_Click(object sender, EventArgs e)
{
  string serverPath = Server.MapPath("~/Phantomjs/");
  string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";

  new Thread(new ParameterizedThreadStart(x =>
  {
    ExecuteCommand(string.Format("cd {0} & phantomjs rasterize.js {1} {2} \"A4\"", serverPath, txtUrl.Text, filename));
  })).Start();

  var filePath = Path.Combine(Server.MapPath("~/Phantomjs/"), filename);

  var stream = new MemoryStream();
  byte[] bytes = DoWhile(filePath);

  Response.ContentType = "application/pdf";
  Response.AddHeader("content-disposition", "attachment;filename=Image.pdf");
  Response.OutputStream.Write(bytes, 0, bytes.Length);

}

Capture screenshot of a webpage using phontomjs -

protected void btnScreenShot_Click(object sender, EventArgs e)
{
 string serverPath = Server.MapPath("~/Phantomjs/");
 string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".png";

 ExecuteCommand(string.Format("cd {0} & phantomjs phantomimage.js {1} {2}", serverPath, txtUrl.Text, filename));

 var filePath = Path.Combine(Server.MapPath("~/Phantomjs/"), filename);

 var stream = new MemoryStream();
 byte[] bytes = DoWhile(filePath);

 Response.AddHeader("content-disposition", "attachment;filename=HtmlToImage.png");
 Response.OutputStream.Write(bytes, 0, bytes.Length);
}

Helper Method -


private void ExecuteCommand(string Command)
{
 try
 {
  ProcessStartInfo ProcessInfo;
  Process Process;

  ProcessInfo = new ProcessStartInfo("cmd.exe""/K " + Command);
  ProcessInfo.CreateNoWindow = true;
  ProcessInfo.UseShellExecute = false;

  Process = Process.Start(ProcessInfo);
 }
 catch { }
}


private byte[] DoWhile(string filePath)
{
 byte[] bytes = new byte[0];
 bool fail = true;

 while (fail)
 {
  try
  {
   using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
   {
       bytes = new byte[file.Length];
       file.Read(bytes, 0, (int)file.Length);
   }

   fail = false;
  }
  catch
  {
    Thread.Sleep(1000);
  }
 }

 System.IO.File.Delete(filePath);
 return bytes;
}

Html Part -


<asp:TextBox runat="server" ID="txtUrl" Text="http://www.dotnetbull.com"></asp:TextBox>

<asp:Button runat="server" ID="btnPdf" Text="Generate PDF" onclick="btnPdf_Click" />
<asp:Button runat="server" ID="btnImage" Text="Capture Image" onclick="btnScreenShot_Click"/>

Download Sample Code Click Here



Popular posts from this blog

Uploading large file in chunks in Asp.net Mvc c# from Javascript ajax

Often we have a requirement to upload files in Asp.net, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.

How to handle click event of linkbutton inside gridview

Recently I have posted how to sort only current page of gridview, Scrollble gridview with fixed header through javascript, File upload control inside gridview during postback and now i am going to explain how to handle click event of linkbutton or any button type control inside gridview.

We can handle click event of any button type control inside gridview by two way first is through event bubbling and second one is directly (in this type of event handling we need to access current girdviewrow container)

What is NameSpace in .Net

This a basic question which allways asked in the interview that what is the namespace ,do you know about namespace,can you tell me some words about namespace.

how $document.ready() is different from window.onload()

we often use window.onload() in javascript and $document.ready() in jquery and assume that both are same just jquery library wrap up javascript window.onload() and introduce $document.ready() but no there is much difference between them below is the explanation -

Merging multiple PDFs using iTextSharp in asp.net c#

In this article i will show you how to merge multiple pdfs into one using ITextSharp below is the two approach one is to pass your input files path, output file path (will be created if not exist) and another is pass direct input stream, output stream and it will write the merge files into output stream.