有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从包含图像和文本的html生成java PDF

我正在寻找一种快速有效的方法,从我的网站创建pdf。pdf将有图像和一些文本,我可以作为html传递。pdf可以是我传递的html的打印格式。类似于CutePDF的功能。可能吗?怎样请分享你的想法


共 (4) 个答案

  1. # 1 楼答案

    试着使用wkhtmltopdf,这适用于大多数情况。你必须安装这个小的exe/rpm。它首先使用webkit引擎在headless browser mode中呈现html,并将网页转换为pdf。安装后,可以通过java/php应用程序调用它。它值得安装

    以下是链接:http://code.google.com/p/wkhtmltopdf/

    PS:我不为wkhtmltopdf工作,我在我的一个项目中尝试了其他几个类似itext的工具,但没有像这个工具那样有效

  2. # 2 楼答案

    真的有可能就在我做这件事的前一周。我用java、servlet和jsp做了同样的事情

    步骤:

    1. 阅读html文件并将其置于字符串中
    2. 使用ITextRenderer将html转换为pdf
    3. 使用setDocumentFromString()设置从字符串呈现文档
    4. 然后使用createPDF()方法创建pdf
      • 您可以将pdf存储在指定的路径或输出流中,我使用了输出流

    示例代码:

    Visit http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
    protected void doProcess(HttpServletRequest request,
            HttpServletResponse response){
        response.setContentType("application/pdf;");
        response.setHeader("Content-Disposition", "attachment; filename=Filenametodownload.pdf");       
        String reportContent = "<html><body><b>This is sample HTML</b></body></html>";
        ServletOutputStream sos =null;
        try {
            sos = response.getOutputStream();
        } catch (IOException e1) {          
            e1.printStackTrace();
        }
        String st = System.getProperty("user.dir");
        // ITextRenderer is only works fine with compailed version of core-renderer.jar 
        //Jar available in http://wo-repository.doit.com.br/content/repositories/thirdparty/org/xhtmlrenderer/core-renderer/R8-final/
        ITextRenderer renderer = new ITextRenderer();   
        //System.out.println(reportContent);
        renderer.setDocumentFromString(reportContent);
        renderer.layout();
        try {
            renderer.createPDF(sos);
        } catch (DocumentException e) {         
            e.printStackTrace();
        }
    
        try {       
            sos.close();
            session.removeAttribute("ReportContent");
        } catch (IOException e) {           
            e.printStackTrace();
        }
    }
    

    注:包括itext。jar和核心渲染器。罐子

    试试你能做的。。。祝你一切顺利

  3. # 3 楼答案

    如果你不想安装WKHTMLTOPDF这样的工具,但仍然需要完整的CSS、HTML和Javascript功能,你可以使用Sprint PDF。这是一个在线API,有很多选项

  4. # 4 楼答案

    如果你想做HTML->;服务器端的PDF转换,前提是您的服务器代码已经是Java或C#/。NET,您可以使用iText中的XMLWorker。这里有一个demo-page和一些documentation(已经过时,但应该很快更新)

    OTOH,如果你想在客户端进行转换,那PDF打印机呢?我个人最喜欢的是PDFCreator。请注意,使用PDF打印机只是一种解决方案,不适合任何浏览网站的用户