iText 7的Header Footer中的HTML支持

时间:2016-12-12 09:51:05

标签: itext itext7

对于iText 5,以下链接可用于html支持:

http://developers.itextpdf.com/examples/page-events/page-events-headers-and-footers#1331-htmlheaderfooter.java

对于iText 7,库已经改变。有人知道如何为iText 7完成它吗?

目前使用的代码:

protected class TableFooterEventHandler implements IEventHandler {
    protected ElementList header;
    protected ElementList footer;

    public TableFooterEventHandler() throws IOException {
        header = XMLWorkerHelper.parseToElementList(HEADER, null);
        footer = XMLWorkerHelper.parseToElementList(FOOTER, null);

    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        Document document = new Document(pdfDoc).setTextAlignment(TextAlignment.JUSTIFIED);
        PdfPage page = docEvent.getPage();
        Rectangle[] columns = {
                new Rectangle(36, 36, 254, 770),
                new Rectangle(305, 36, 254, 770)};
        document.setRenderer(new ColumnDocumentRenderer(document, columns));
        for(Element e : header)
            document.add(new Paragraph(header).setFont(title ? bold : normal));
        PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
        new Canvas(canvas, pdfDoc, new Rectangle(36, 20, page.getPageSize().getWidth() - 72, 50)).add(header);
    }
}

public static void main(String[] args) throws Exception{
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new HtmlHeaderFooter().createPdf(DEST);
}

public void createPdf(String filename) throws Exception{

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
    Document doc = new Document(pdfDoc, PageSize.A4);
    doc.setMargins(36, 36, 72, 36);

    pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, (new TableFooterEventHandler()));

    for (int i = 0; i < 150; i++) {
        doc.add(new Paragraph("Hello World!"));
    }
    doc.add(new AreaBreak());
    doc.add(new Paragraph("Hello World!"));
    doc.add(new AreaBreak());
    doc.add(new Paragraph("Hello World!"));

    doc.close();
}

在行中:

for(Element e : header)

元素已被弃用。与iText 7相对应的是什么?

1 个答案:

答案 0 :(得分:1)

我很高兴地通知pdfHTML的{​​{1}}插件已经发布了! 要将HTML代码段转换为元素列表,请使用iText7HtmlConverter.convertToElements替代iText7

未设置其他XMLWorkerHelper.parseToElementList时的简单示例:

ConverterProperties

之后,您可以以您喜欢的任何方式使用这些元素,例如将它们添加到您想要在代码中执行的List<IElement> headerElements = HtmlConverter.convertToElements(html);

Canvas