Quantcast
Channel: Tech Spear » java
Viewing all articles
Browse latest Browse all 8

Program to convert HTML file into a pdf file- Java 6

$
0
0

The following code is to convert a html file into a pdf file. This code will work according to your wish :)

 

//HtmlToPdf.java

/* Java code to convert html page to a pdf
* Import all the basic packages needed
*/
package html.to.pdf;
//import basic packages to work with text
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.codec.Base64;
//import the needed stream and buffered readers
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;
// An array list import
import java.util.ArrayList;
//Class declaration
public class HtmlToPdf {
//main class
public static void main(String a[]) throws Exception {
//instance of Document
Document pdfDoc = new Document();
// Buffered reader to read the test.html file
Reader htmlReader = new BufferedReader(new InputStreamReader(new FileInputStream(“/home/devil/test.html”))); //change the name accordingly
ByteArrayOutputStream byteAOS = new ByteArrayOutputStream();
// get Instance
PdfWriter.getInstance(pdfDoc, byteAOS);
// Open document
pdfDoc.open();
//Instance for stylesheet
StyleSheet stylez = new StyleSheet();
//load a basic font. can also do other functions
stylez.loadTagStyle(“body”, “font”, “Times New Roman”);
//HTML worker in simpleParser
ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, stylez);
//Add to the document
for (int i = 0; i < arrayElementList.size(); ++i) {
Element e = (Element) arrayElementList.get(i);
pdfDoc.add(e);
}
//close the document after adding
pdfDoc.close();
byte[] byt = byteAOS.toByteArray();
//encode the bytes
String pdfBase64 = Base64.encodeBytes(byt);
File pdfFile = new File(“Worked.pdf”); //target name. change accordingly
FileOutputStream out = new FileOutputStream(pdfFile);
out.write(byt);
out.close();
}
}


Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images