Tuesday, October 21, 2014

Java Code to convert Html to PDF Using wkhtmltopdf

Basic thing to do:
     Need to install all the basic stuffs for java and download wkhtmltopdf from below link
     Link : http://code.google.com/p/wkhtmltopdf/downloads/detail?name=wkhtmltopdf-0.9.9-installer.exe&
Source Code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Java_pdf {
   public static void main(String[] args) throws IOException {
        try
        {
            String htmlFilePath = "D:/html2pdf/a.html";
            String pdfFilePath = "D:/html2pdf/test.pdf";
            ProcessBuilder pb = new ProcessBuilder("C:/Program Files/wkhtmltopdf/wkhtmltopdf.exe", htmlFilePath, pdfFilePath);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
          
            String line = inStreamReader.readLine();
          
                    while(line != null)
                    {
                        System.out.println(line);
                        line = inStreamReader.readLine();
                    }
        }
        catch(Exception e)
        {
            System.out.println("coming-->"+e.getMessage() );
        }
    }
}

6 comments:

  1. Thanks for sharing code...it really help

    ReplyDelete
  2. Thanks man your save my project :)

    ReplyDelete
  3. unable to convert pie charts and headers by using above code. Can you suggest how to convert cucumber features.html?

    ReplyDelete
    Replies
    1. try with the wkhtmltopdf latest version API.

      Delete