Generating PDF and Image of HTML(JSP) page using WebKit(wk)

WebKit is the engine of Apples Safari

There are two exe’s wkhtmltopdf.exe & wkhtmltoimage for generating PDF and IMG.
We need to install EXE from WKHTMLtoPDF

Example

GeneratePDF.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taher.javahunter;

import java.io.File;
import java.io.IOException;

/**
 *
 * @author Taher_JAVAHUNTER
 */
public class GeneratePDF {

    String logUserId = "0";
    public String path = "c:/PDF";

    public void genrateCmd(String reqURL, String reqQuery, String folderName, String id) {
        try {
            File destFoldereGP = new File("c:/eGP");
            if (destFoldereGP.exists() == false) {
                destFoldereGP.mkdirs();
            }

            File destFolderPDF = new File("c:/PDF/");
            if (destFolderPDF.exists() == false) {
                destFolderPDF.mkdirs();
            }

            File destFolder = new File("c:/PDF/" + folderName);
            if (destFolder.exists() == false) {
                destFolder.mkdirs();
            }

            File destFolder2 = new File("c:/PDF/" + folderName + "/" + id);
            if (destFolder2.exists() == false) {
                destFolder2.mkdirs();
            }
//For Image change 'wkhtmltopdf.exe' to 'wkhtmltoimage.exe' and '.pdf' to '.jpeg'
            Process p = Runtime.getRuntime().exec("wkhtmltopdf.exe " + reqURL + "?" + reqQuery + " c:/PDF/" + folderName + "/" + id + "/" + folderName + ".pdf");

        } catch (IOException e1) {
            System.out.println("Exception::" + e1);
        } catch (Exception e) {
            System.out.println("Exception::" + e);
        }
    }
}

index.jsp

<%-- 
    Document   : index
    Created on : May 16, 2011, 10:39:58 AM
    Author     : Taher_JavaHunter
--%>

<%@page import="taher.javahunter.GeneratePDF"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
                    if ("Generate PDF".equals(request.getParameter("OK"))) {
                        String reqURL = request.getRequestURL().toString();
                        String reqQuery = "btn=false";
                        String folderName = "JavaHunter";
                        GeneratePDF obj = new GeneratePDF();
                        obj.genrateCmd(reqURL, reqQuery, folderName, "786");                        
                    }
        %>
        <form id="frmPDF" action="" name="frmPDF" method="post">
            <table width="100%" border="2" style='background-color:#f2dbdb;color: #943634; line-height:20px;border:1px solid #943634;font-family: arial, verdana; font-size: 13px;'>
                <tr>
                    <th style="background-color: #943634;color: #F2DBDB;">First Name</th>
                    <th style="background-color: #943634;color: #F2DBDB;">Last Name</th>
                    <th style="background-color: #943634;color: #F2DBDB;">Salary</th>
                    <th style="background-color: #943634;color: #F2DBDB;">Place</th>
                </tr>
                <% for (int i = 1; i <= 10; i++) {%>
                <tr>
                    <td align="center">Taher</td>
                    <td align="center">TINWALA</td>
                    <td align="center">1000<%=i%></td>
                    <td align="center">Ahmedabad-<%=i%></td>
                </tr>
                <% }%>
            </table>
                <%if(!"false".equals(request.getParameter("btn"))){%>
                <div align="center">
                    <br/>
                    <input type="submit" id="OK" name="OK" value="Generate PDF"/>
                </div>
               <%}%>
        </form>
    </body>
</html>

Generated PDF image
WKHTMLTOPDF

Advertisements
This entry was posted in Generate PDF, JSP. Bookmark the permalink.

12 Responses to Generating PDF and Image of HTML(JSP) page using WebKit(wk)

  1. kapil says:

    we have a website when the customer might want a pdf of some google map or some XML data or html URL. Could you suggest the most efficient to create PDFs by simply transforming html/xml/jsps into PDF? Pl justify against Apache FOP, or PD4ML?

    Would this have any memory issues in terms of processes not being used/closed etc? What is the maximum PDF size a wkhtmltoPDF utility can handle? what is the maximum page coverage it can process in one hit? Does it matter if concurrently multiple users call the same utility from different webserver sessions? would it start a new thread/process for each http session? wpuld this have any mal effect on overall website performance and scalability and memory consumption? Pl advice soem references on websites where this is actively used with higher data etc? Does it have any limitation on the type of XML/CSS it can render as PDF?

    Pl advice on the bottleneck if any? Was curious, about the PDF icon click suggestion that you had above? Something that is always there on any apache website. On Apache FOP for example one can click on the PDF icon to generate the displayed set of web pages as PDF. IS wkhtmltoPDF used in that process?

  2. kapil says:

    01:20:32,996 INFO [STDOUT] Exception::java.io.IOException: Cannot run program “wkhtmltopdf.exe”: CreateProcess error=2, The system cannot find the file specified
    I mightbe doing something silly here, any idea?

  3. EDUARDO JORGE DOS SANTOS CORDEIRO says:

    The best solution found. Congratulations!

  4. Chitra says:

    could we create the pdf of hindi database of postgres in jsp or servlet

  5. Hello Taher Sir. I’m using your code in the following manner…

    JSP Page

    First Name
    Last Name
    Salary
    Place

    <% for (int i = 1; i

    Kushal
    Agarwal
    1000
    Hyderabad-

    My issue is. I need to assign “SPECIFIC FILE NAME” to each and every print I take. How can this be possible ?

    Like pass a string from a different page to this print page and save it as pdf.

    Eg. Passed “Voucher_25-01-2017_BANK ” to this print page and the file should be named as ” Voucher_25-01-2017_BANK.pdf “…

  6. Vijay says:

    Hi Sir,
    If I click on download button, it is saving in local directory.
    Assume there are two systems one is client & other is server.
    If client clicks on download button, it is saved in server system but user was not able
    to see the pdf file.How to resolve this?

    • tahertinwala says:

      It will be saved on server on dedicated path provided by you. If you want client side to get downloaded you need to read byte array from server and write in servlet outputstream to get it as a download. You can get example code from internet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s