gpt4 book ai didi

java - 有什么方法可以将 HTML 转换为 PDF 吗?

转载 作者:行者123 更新时间:2023-12-01 18:14:43 25 4
gpt4 key购买 nike

我尝试了一切,但找不到任何解决方案。我使用 iText、flying-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.

最佳答案

我使用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);

htmlxhtml by org.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

关于java - 有什么方法可以将 HTML 转换为 PDF 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com