【问题标题】:iText style parsing HTML to PDFiText 样式将 HTML 解析为 PDF
【发布时间】:2012-11-28 18:43:16
【问题描述】:

iText 有问题。

我点击了这个链接:How to export html page to pdf format?

我的sn-p:

    String str = "<html><head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title></title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></head></html>";
    String fileNameWithPath = "/Users/cecco/Desktop/pdf2.pdf";


    com.itextpdf.text.Document document =
            new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4);
    FileOutputStream fos = new FileOutputStream(fileNameWithPath);
    com.itextpdf.text.pdf.PdfWriter pdfWriter =
            com.itextpdf.text.pdf.PdfWriter.getInstance(document, fos);

    document.open();

    document.addAuthor("Myself");
    document.addSubject("My Subject");
    document.addCreationDate();
    document.addTitle("My Title");

    com.itextpdf.text.html.simpleparser.HTMLWorker htmlWorker =
            new com.itextpdf.text.html.simpleparser.HTMLWorker(document);
    htmlWorker.parse(new StringReader(str.toString()));

    document.close();
    fos.close();

并且工作正常。

但不考虑 h3 和 div 中的标记样式。

但如果我将我的 html 复制到 http://htmledit.squarefree.com/ 中,一切都是正确的。

我该如何解决这个问题?

【问题讨论】:

    标签: java html pdf itext


    【解决方案1】:

    iText 不是最好的 Html 解析器,但您可以为此使用 Flying-Saucer。 Flying-Saucer 建立在 iText 之上,但具有强大的 Xml / (X)Html 解析器。简短:如果你想要 html -> Pdf,飞碟是完美的。

    以下是从字符串生成 pdf 的方法:

    /*
     * Note: i filled something in the title-tag and fixed the head tag (the whole body-tag was in the head)
     */
    String str = "<html><head></head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title>t</title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></html>";
    
    OutputStream os = new FileOutputStream(new File("example.pdf"));
    
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(str);
    renderer.layout();
    renderer.createPDF(os);
    
    os.close();
    

    但是: FS 只支持 valid Html / Xhtml / xml,所以就这样吧。

    【讨论】:

    • 更改为飞碟并在此答案中使用它解决了我所有的 html 到 pdf 解析问题。正如 ollo 指出的那样,您应该首先将字符串“整理”为真正有效的 HTML。为此,我使用 Jsoup 解析 html。
    猜你喜欢
    • 2020-09-04
    相关资源
    最近更新 更多