iText7 Java将图像添加为标题

时间:2018-09-03 11:07:41

标签: itext7 html2pdf

我是iText7的新手,使用Java示例,我能够将HTML转换为PDF / A-1A,并添加页眉文本和页脚文本。addEventHandler可以使用页眉文本和页脚文本,并且也是css编写的,就像这样:

@page {
    @bottom-right {
        content: "Page " counter(page) " of " counter(pages);
        font-family: FreeSans;
    }
}

但是标题,我想要一个图像,例如徽标。这是我的Header类:

public class Header implements IEventHandler {
    String header;
    public Header(String header) {
        this.header = header;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        canvas.setFontSize(18f);
        try {
            PdfFont pdfFont = PdfFontFactory.createFont("src/main/resources/fonts/noto/NotoSans-Regular.ttf", PdfEncodings.IDENTITY_H);
            canvas.setFont(pdfFont);
        } catch(Exception ex) {
            ex.printStackTrace();
        }

        String DOG = "src/main/resources/html/img/logo.png";
        try {
            Image img = new Image(ImageDataFactory.create(DOG));

            Paragraph paragraph = new Paragraph().add(img);

            canvas.showTextAligned(paragraph, 0, 0, TextAlignment.CENTER);
        } catch(Exception ex) {
            ex.printStackTrace();
        } 
    }
}

但是图像看不到,或者覆盖了很大的主要内容。如何调整图像属性,例如宽度,高度和位置?

0 个答案:

没有答案