简体   繁体   中英

how to add a table to a page with header and footer using itext 7

i need to add a table in a specific position and be repeated in all pdf pages without interference with header and footer this is my code

PdfEventHandler handler = new PdfEventHandler(header, x,y);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
Table table = new Table(getcolumnsWidth(pdfColumns, tableWidth));
String line = br.readLine();
process(table, line, true);
while ((line = br.readLine()) != null) {
    process(table, line, false);
}
br.close();
document.add(table);

with

public class PdfEventHandler implements IEventHandler {

    private String header;
    private int x,y;

    public PdfEventHandler(String header,int x , int y) {
     this.header =header;
     this.x = x; this.y =y;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
        Rectangle area = page.getPageSize();
        int pageHeight = (int) area.getHeight();
        Canvas canvas = new Canvas(pdfCanvas, pdfDoc, area);

        canvas.showTextAligned(header, x, y, TextAlignment.CENTER);
    }
}

this is the result pdf file在此处输入图片说明

That's very unclear what you try to achieve, so I've made several assumptions.

First: you create your pdf from scratch (there is no source file). Second: you want to place a table on each page (onto specific area) and the table should not interfere with the other content.

So how to place a table (or another element) on each page? One can use an event handler for it. Please look at the next example: https://github.com/itext/i7js-examples/blob/develop/src/test/java/com/itextpdf/samples/sandbox/events/TableFooter.java There a table is added as a footer once a new page is created.

As for you code I believe that you should have used the showTextAligned which requires a page number: http://itextsupport.com/apidocs/itext7/latest/com/itextpdf/layout/RootElement.html#showTextAligned-com.itextpdf.layout.element.Paragraph-float-float-int-com.itextpdf.layout.property.TextAlignment-com.itextpdf.layout.property.VerticalAlignment-float-

使用 table.setRelativePosition(0, 0, 0, 0) 将表格内容放在 pdf 上重复的标题之后

   for (int i = 0; i < 2; i++) {
     table.addCell("title 1");
    table.addCell("title 2");
    //header row and footer
    }
    table.setHeaderRows(2);  //two header rows ... 
    table.setFooterRows(1); // Of which one is a footer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM