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() );
        }
    }
}