简体   繁体   English

如何使用iText和飞碟将html页面的网址转换为PDF格式的pdf?

[英]How to convert url of html page to pdf in java using iText & flying saucer?

I've just downloaded xhtmlrenderer and iText jar files. 我刚刚下载了xhtmlrenderer和iText jar文件。 I can make pdf files by using these 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". 我真正想要的是:如果我在“inputFile”的位置提供一个有效的URL(比如“ https://xhtmlrenderer.dev.java.net/news.html ”),我需要创建pdf。 Is it possible with flying saucer and iText? 飞碟和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();
    }
}

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'文件夹必须存在于工作区中的项目中,或者您正在运行应用程序的任何位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM