Wednesday, January 4, 2012

Html to Pdf using Java

The following Java Code is used to convert the HTML content into PDF

import java.io.*;

import java.io.FileOutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
public class pdfCreation {

/**
* @Purpose : Converting html file into PDF.
* External jar file used iText-2.0.8.jar, core-renderer.jar
* xml-apis-xerces-2.9.1.jar
*/
public static void main(String[] args) {
try{
//html file path
String inputFile=”C:\\workspace\\html2Pdf\\src\\pack1\\sample.html”;
//Output pdf file path
String outputFP=”C:\\sample.pdf”;
File inputHTMLFile=new File(inputFile);
if(!inputHTMLFile.exists()){
System.out.println(”Input html File does not exists!”);
System exit(0);
}
String url=inputHTMLFile.toURI().toURL().toString();
OutputStream os=new FileOutputStream(outputFP);
ITextRenderer renderer=new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
System.out.println(”HTML file was converted into PDF”);
}
catch(Exception e){
e.printStackTrace();
}
}
}

2 comments:

  1. your code is very nice but i want to use in xpages

    ReplyDelete
  2. You can convert HTML to PDF format and vice versa with Aspose.PDF for Java API. It also offers many other features which developers can use in their application.

    ReplyDelete