我刚刚下载了 xhtmlrenderer 和 iText jar 文件。我可以使用这些 jar 制作 pdf 文件。
我真正想要的是:
如果我在“inputFile”的位置提供一个有效的 URL(比如“https://xhtmlrenderer.dev.java.net/news.html
”),我需要创建 pdf。 Flying Saucer 和 iText 有可能吗?
如果是,请指导我实现这一目标。
此外,当我尝试运行以下代码时,出现错误: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();
}
}
最佳答案
是的...这可能行不通,因为请求的页面不是 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();
}
}
当找不到您请求的文件时,会发生流关闭错误。 'samples' 文件夹必须存在于您工作区的项目中或您从中运行应用程序的任何位置
关于java - 如何使用 iText 和 Flying Saucer 在 java 中将 html 页面的 url 转换为 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4014149/