如何使用 iText 和飞碟在 java 中将 html 页面的 url 转换为 pdf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4014149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert url of html page to pdf in java using iText & flying saucer?
提问by Vinothkumar Arputharaj
I've just downloaded xhtmlrenderer and iText jar files. I can make pdf files by using these jars.
我刚刚下载了 xhtmlrenderer 和 iText jar 文件。我可以使用这些 jars 制作 pdf 文件。
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在“inputFile”的位置给出一个有效的 URL(比如“ ”),我需要创建 pdf 。飞碟和iText可以吗?
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();
}
}
回答by Edd
Yes... this probably won't work as the page being requested isn't xhtml but this should do the trick:
是的...这可能不起作用,因为请求的页面不是 xhtml 但这应该可以解决问题:
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
当未找到您请求的文件时,会发生流关闭错误。'samples' 文件夹必须存在于您工作区的项目中或您运行应用程序的任何位置

