代码之家  ›  专栏  ›  技术社区  ›  Vinothkumar Arputharaj

如何使用iText&flying discer在java中将html页面的url转换为pdf?

  •  5
  • Vinothkumar Arputharaj  · 技术社区  · 14 年前

    我刚刚下载了xhtmlender和iText jar文件。我可以用这些罐子制作pdf文件。

    我真正想要的是: 我需要创建pdf,如果我给一个有效的网址(说“ https://xhtmlrenderer.dev.java.net/news.html )替换为“inputFile”。飞碟和iText有可能吗?

    另外,当我试图运行下面的代码时,我得到了一个错误:streamclosed

    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();
        }
    }
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   Edd    14 年前

    对。。。这可能不起作用,因为请求的页面不是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();
    }
    }