How to convert url of html page to pdf in java using iText & flying saucer?
How to convert url of html page to pdf in java using iText & flying saucer?
I've just downloaded xhtmlrenderer and iText jar files. I can make pdf files by using these jars.
What I exactly want is:
I need to create pdf if I give one valid URL (say "https://xhtmlrenderer.dev.java.net/news.html") in the place of "inputFile". Is it possible with flying saucer and iText?
https://xhtmlrenderer.dev.java.net/news.html
If yes, please guide me to achieve this.
Also, when I'm trying to run the below code, I'm getting error: stream closed
import java.io.*;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextRenderer;
public class FirstDoc {
public static void main(String args)
throws IOException, DocumentException {
String inputFile = "samples/sql.html";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "firstdoc.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
com.lowagie
com.itextpdf
1 Answer
1
Yes... this probably won't work as the page being requested isn't xhtml but this should do the trick:
import java.io.*;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextRenderer;
public class FirstDoc {
public static void main(String args)
throws IOException, DocumentException {
String url= "http://xhtmlrenderer.java.net/news.html";
String outputFile = "firstdoc.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
The stream closed error occurs when the file you're requesting isn't found. The 'samples' folder must exist in the project in your workspace or wherever it is that you're running your application from
My HTML contains '&' in between text. How to handle that
– Harshavardhan Konakanchi
Jul 3 '13 at 11:00
I'd suggest you create a new question
– Edd
Jul 3 '13 at 11:16
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Your code contains
com.lowagie. That is an ancient version of iText. Please usecom.itextpdfiText.– Amedee Van Gasse
Apr 10 '16 at 6:55