Downloadable PDF functionalities are part of different websites. PDF or excel downloads have large number of ways to do. Excel is easy, but PDF usually have issues of CSS and many more.
I have done a lot more research on this and found the usage of CutyCapt.exe more convenient to capture a webpage as PDF or Image.
What is CutyCapt
CutyCapt is a small cross-platform command-line utility to capture WebKit's rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP. See IECapt for a similar tool based on Internet Explorer.
Requirements
- The process of PDF creation is done using an executable file called CutyCapt.exe. Download the exe and add it to the solution.
- If we are working with ASP.NET project, the exe can be called in a redirection page. This page will be blank with the following code on page load.
Implementation
- Create a file name and path: To make the filename unique I would prefer a GUID. (It is the choice of the developer according to the requirement and logic). The file Url is then added to a string.
- string filename = Guid.NewGuid() + ".pdf";
-
- string url = “http:
- Location of executable: The location of the CutyCapt.exe is assigned to a string.
//location of Executable
string cutycaptLocation = "D:\\CutyCapt";
- Command creation: For creating the command in ASP.NET, we use the ProcessStartInfo object.
Different parameters are assigned to the object as properties like the following:
a. CreateNoWindow.
b. WorkingDirectory.
c. FileName .
d. Arguments.
- link of the page which needs to be converted to PDF.
- the destination folder
e. UseShellExecute .
-
- System.Diagnostics.ProcessStartInfo pi = new System.Diagnostics.ProcessStartInfo();
- pi.CreateNoWindow = false;
- pi.WorkingDirectory = cutycaptLocation;
- pi.FileName = cutycaptLocation + "\\CutyCapt.exe";
- pi.Arguments = "--url=" + link + " --out-format=pdf -out=" + System.IO.Path.GetFullPath(Server.MapPath("~/CutyCapt")) + "\\" + filename;
- pi.UseShellExecute = false;
- Process execution: Process object in ASP.Net is used to execute the process, for the info created.
- try {
-
-
- using(System.Diagnostics.Process exeProcess = System.Diagnostics.Process.Start(pi)) {
- exeProcess.WaitForExit();
- }
- }
- catch (Exception ex)
- {
- Response.Write(ex.Message);
- }
- Redirect to PDF: Once the PDF is created the browser is redirected to the PDF link loading the PDF created.
The PDF file for the specified page is ready to be saved to the system. This is the easiest way to create a PDF in my experience.
Please feel free to put in your comments on this.