Wednesday, 27 November 2013

Convert Webpage into PDF Using Java and PhantomJs

Download the demo folder from here : Download Me
Place it in your D:/ drive root.
Now Run Test.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;


public class Test {
public static void main(String[] args) {
 try {
  
  //Set URL INFO
  String URL = "http://www.google.com";
  String FILE_NAME = "google_pdf";
  
  StringBuffer buffer = new StringBuffer("var page = require('webpage').create();");
  buffer.append("page.open('"+URL+"', function () {");
  buffer.append("page.render('temp_file/temp_"+FILE_NAME+".pdf');");
  buffer.append("phantom.exit();");
  buffer.append("});");
  
  //Delete Content From JS File
  File writer = new File("D://demo/demo.js");
  writer.delete();

  BufferedWriter bw = new BufferedWriter(new FileWriter("D://demo/demo.js", true));
  bw.write(buffer.toString());
     bw.close();
     
     System.out.println("PDF URL: D:/demo/temp_file/temp_"+FILE_NAME+".pdf");
     
     // Execute command
  String command = "cmd /c start D:/demo/my.bat";
  
     Process child = Runtime.getRuntime().exec(command);

     // Get output stream to write from it
     OutputStream out = child.getOutputStream();

     out.write("cd C:/ /r/n".getBytes());
     out.flush();
     out.write("dir /r/n".getBytes());
     out.close();
 } catch (IOException e) {
 }
}
}

Put these code in your my.bat inside demo folder.
cd\
D:
cd demo
phantomjs demo.js

exit

1 comments:

  1. Very Nice and Informative Post. Thank admin for sharing such an amazing post.

    --->>Easiest way to Convert Webpage to PDF

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...