【问题标题】:Adding bootstrap css for JSOUP converting HTML to PDF为 JSOUP 添加引导 css 将 HTML 转换为 PDF
【发布时间】:2020-06-23 15:40:57
【问题描述】:

我正在尝试使用 JSOUPxhtmlrenderer 将 HTML 文件转换为 PDF。

不幸的是,html 中的 CSS 引用链接无法转换。生成的 PDF 没有任何 CSS...

检查后,HTML 文件中添加了一个引导 CSS 链接引用:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

请告诉我如何将此引导 CSS 加载到 JSOUP 以转换为 PDF:

我将 html 转换为 PDF 的代码:

String inputFile = "d:\\contractorder-01.html";
String outputFile = "d:\\generated.pdf";

try {
    String html = new String(Files.readAllBytes(Paths.get(inputFile)));
    final Document document = Jsoup.parse(html);
    document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(document.html());
    renderer.layout();

    try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
        renderer.createPDF(os);
    }

    catch (Exception ex) {
        ex.printStackTrace();
    }

} catch (Exception ex) {
    ex.printStackTrace();
}

【问题讨论】:

    标签: java html pdf jsoup


    【解决方案1】:

    编辑: 我已经成功地使用SpringTemplageEngine 生成了pdf,并传递了值。这允许我使用 Thymeleaf 生成 HTML 内容,您还可以传递 Context(如 ModelMap),其值:

    Context context = new Context();
    context.setVariable("name", value);
    String html = templateEngine.process("application/pdf-agreement", context);
    

    HTMLthymeleaf 文件,但需要声明 pdf 资源,其中类路径为:

    String filename = "filename.pdf";
    FileOutputStream os = new FileOutputStream(filename);
    ITextRenderer renderer = new ITextRenderer();
    
    renderer.setDocumentFromString(html,
                        new ClassPathResource("/pdf-resources/").getURL().toExternalForm());
    renderer.layout();
    renderer.createPDF(os);
    renderer.finishPDF();
    os.close();
    

    但是,重要的是 CSS3 不完全支持,CSS2 没关系。但使其工作的唯一方法是使用在html 文件中定义的内联css。 希望这会有所帮助。


    老答案


    我也有同样的问题。 我一直在关注这个post。 如果您查看PdfService,它是使用本地资源文件夹完成的示例,所有 CSS 和 JS 都在该文件夹中:

     private File renderPdf(String html) throws IOException, DocumentException {
        File file = File.createTempFile("students", ".pdf");
        OutputStream outputStream = new FileOutputStream(file);
        ITextRenderer renderer = new ITextRenderer(20f * 4f / 3f, 20);
        renderer.setDocumentFromString(html, new ClassPathResource(PDF_RESOURCES).getURL().toExternalForm());
        renderer.layout();
        renderer.createPDF(outputStream);
        outputStream.close();
        file.deleteOnExit();
        return file;
    }
    

    PDF_RESOURCES 是一个位于resources 文件夹中的文件夹。 尽管如此,我一直在为某些 CSS 工作而苦苦挣扎,但没有引导程序。

    当我有更好的消息时我会回来的。

    【讨论】:

    • 另外忘记提一下生成的 html 是使用 Thymeleaf 完成的。
    猜你喜欢
    • 1970-01-01
    • 2016-12-06
    • 2015-01-10
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2011-09-02
    相关资源
    最近更新 更多