有没有办法将HTML转换为PDF?

时间:2015-05-22 05:17:37

标签: java pdf-generation

我尝试了所有方法,但无法找到任何解决方案。我使用iText,fly-saucer将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.

1 个答案:

答案 0 :(得分:4)

我使用ITextRenderer。我只支持xhtmlpdf。这就是为什么您最初需要将html转换为xhtml的原因。

xhtmlpdf

    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);
html

{p> xhtmlorg.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