簡體   English   中英

為 JSOUP 添加 bootstrap css 將 HTML 轉換為 PDF

[英]Adding bootstrap css for JSOUP converting HTML to PDF

我正在嘗試使用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();
}

編輯:我設法使用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();

但是,重要的是不完全支持CSS3CSS2問題。 但使其工作的唯一方法是使用在html文件中定義的內聯css 希望這可以幫助。


舊答案


我有同樣的問題。 我一直在關注這個帖子 如果您查看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 工作,但沒有引導程序。

當我有更好的消息時,我會回來的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM