iText样式将HTML解析为PDF

Cec*_*oCQ 4 html java pdf itext

我有iText的问题.

我已经关注此链接:如何将html页面导出为pdf格式?

我的片段:

    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();
Run Code Online (Sandbox Code Playgroud)

工作正常.

但是不考虑将标签样式转换为h3和div.

在此输入图像描述

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

我怎么解决这个问题?

oll*_*llo 6

iText不是最好的Html Parser,但你可以使用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();
Run Code Online (Sandbox Code Playgroud)

但是: FS只支持有效的 Html/Xhtml/xml,所以请确保它是真的.