【问题标题】:Is there is any way to convert HTML to PDF? [closed]有什么方法可以将 HTML 转换为 PDF 吗? [关闭]
【发布时间】:2015-08-04 00:18:42
【问题描述】:

我尝试了所有方法,但找不到任何解决方案。我使用 iText,飞碟将 HTML 转换为 PDF,但不能这样做。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;


public class Pdf {
    public static void main(String[] args) throws DocumentException, IOException {
         String File_To_Convert = "WebContent/index.html";
         String url = new File(File_To_Convert).toURI().toURL().toString();
         System.out.println(""+url);
         String HTML_TO_PDF = "ConvertedFile.pdf";
         OutputStream os = new FileOutputStream(HTML_TO_PDF); 


         ITextRenderer renderer = new ITextRenderer();
         renderer.setDocument(url);      
         renderer.layout();
         renderer.createPDF(os);       
         os.close();
    }
}

运行这段代码时出错:

 Flying Saucer: No configuration files found in classpath using URL: resources/conf/xhtmlrenderer.conf, resorting to hard-coded fallback properties.

【问题讨论】:

  • 请展示您尝试过的内容..
  • public class Pdf { public static void main(String[] args) throws DocumentException, IOException { String File_To_Convert = "WebContent/index.html"; String url = new File(File_To_Convert).toURI().toURL().toString(); System.out.println(""+url); String HTML_TO_PDF = "ConvertedFile.pdf"; OutputStream os = new FileOutputStream(HTML_TO_PDF); ITextRenderer 渲染器 = 新 ITextRenderer(); renderer.setDocument(url);渲染器.layout(); renderer.createPDF(os); os.close(); } }
  • 警告:飞碟:使用 URL:resources/conf/xhtmlrenderer.conf 在类路径中找不到配置文件,采用硬编码的后备属性。
  • @user2681809 您可以将此添加到您的问题中。您的代码将更具可读性

标签: java pdf-generation


【解决方案1】:

我使用ITextRenderer。我只支持xhtml 到pdf。这就是为什么您首先需要将html 转换为xhtml。

xhtml 到 pdf

    String path_xhtml = "C:\example.xhtml";
    String path_pdf = "C:\example.pdf";
    String url = new File(path_xhtml).toURI().toURL().toString();
    OutputStream os = new FileOutputStream(path_pdf);
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(url);
    renderer.layout();
    renderer.createPDF(os);

htmlxhtmlorg.w3c.tidy.Tidy

     FileInputStream fis = new FileInputStream("C:\example.html");
     FileOutputStream fos = new FileOutputStream("C:\example.xhtml");   
     Tidy tidy = new Tidy();
     tidy.setXHTML(true);
     Document d = tidy.parseDOM(fis, fos);

更新

html 文件中的图片

html 文件中可能有图像。上面的代码不足以渲染图像。 请参考 Using Flying Saucer to Render Images to PDF In Memory

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    相关资源
    最近更新 更多