使用iText

时间:2017-08-22 09:03:38

标签: java html itext

我有3个htmls,标题,正文和页脚。我使用XMLWorker为图像转换html和Base64ImageProvider。 但我不能在我的标题中使用该提供程序。如何转换标题html来显示图像? 我需要帮助。 我的代码:

public class PdfUtils {
public static void createPdf(String header, String body, String footer) throws IOException, DocumentException {
        String dir = "C:/";
        String outputFile = "letter.pdf";

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dir + outputFile));
        document.open();
        writer.setPageEvent(new PDFHeaderFooter(header, footer));

        CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        htmlContext.setImageProvider(new Base64ImageProvider());

        // Pipelines
        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(new ByteArrayInputStream(body.getBytes()));

        // step 5
        document.close();
    }
}

public class PDFHeaderFooter extends PdfPageEventHelper {
    protected ElementList header;
    protected ElementList footer;

    public PDFHeaderFooter(String headerHtml, String footerHtml) throws IOException {
        header = XMLWorkerHelper.parseToElementList(headerHtml, null);
        footer = XMLWorkerHelper.parseToElementList(footerHtml, null);
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            PdfContentByte canvas = writer.getDirectContent();
            ColumnText ct = new ColumnText(canvas);
            ct.setSimpleColumn(36, 832, 559, 810);
            for (Element e : header) {
                ct.addElement(e);
            }
            ct.go();
            ct.setSimpleColumn(36, 10, 559, 32);
            for (Element e : footer) {
                ct.addElement(e);
            }
            ct.go();
        }
        catch (DocumentException de) {
            throw new ExceptionConverter(de);
        }
    }
}

谢谢!

0 个答案:

没有答案