IText can't keep rows together, second row spans multiple pages but won't stick with first row.

Posted by J2SE31 on Stack Overflow See other posts from Stack Overflow or by J2SE31
Published on 2010-06-02T15:35:09Z Indexed on 2010/06/02 18:04 UTC
Read the original article Hit count: 470

Filed under:
|
|
|
|

I am having trouble keeping my first and second rows of my main PDFPTable together using IText. My first row consists of a PDFPTable with some basic search criteria. My second row consists of a PdfPTable that contains all of the tabulated results. Everytime the tabulated results becomes too big and spans multiple pages, it is kicked to the second page automatically rather than showing up directly below the search criteria and then paging to the next page. How can I avoid this problem? I have tried using setSplitRows(false), but I simply get a blank document (see commented lines 117 and 170). How can I keep my tabulated data (second row) up on the first page? An example of my code is shown below (you should be able to just copy/paste).

public class TestHelper{
    private TestEventHelper helper;

    public TestHelper(){
        super();
        helper  = new TestEventHelper();
    }



    public TestEventHelper getHelper() {
        return helper;
    }



    public void setHelper(TestEventHelper helper) {
        this.helper = helper;
    }



    public static void main(String[] args){
        TestHelper test = new TestHelper();
        TestEventHelper helper = test.getHelper();

        FileOutputStream file = null;
        Document document = null;
        PdfWriter writer = null;
        try {
            file = new FileOutputStream(new File("C://Documents and Settings//All Users//Desktop//pdffile2.pdf"));
            document = new Document(PageSize.A4.rotate(), 36, 36, 36, 36);

            writer = PdfWriter.getInstance(document, file);
//          writer.setPageEvent(templateHelper);
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
            writer.setUserunit(1f);
            document.open();

            List<Element> pages = null;
            try {
                pages = helper.createTemplate();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Iterator<Element> iterator = pages.iterator();
            while (iterator.hasNext()) {
                Element element = iterator.next();
                if (element instanceof Phrase) {
                    document.newPage();
                } else {
                    document.add(element);
                }
            }

        } catch (Exception de) {
            de.printStackTrace();
//          log.debug("Exception " + de + " " + de.getMessage());
        } finally {
            if (document != null) {
                document.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
        System.out.println("Done!");
    }


private class TestEventHelper extends PdfPageEventHelper{

    // The PdfTemplate that contains the total number of pages.
    protected PdfTemplate total;
    protected BaseFont helv;

    private static final float SMALL_MARGIN = 20f;
    private static final float MARGIN = 36f;
    private final Font font = new Font(Font.HELVETICA, 12, Font.BOLD);
    private final Font font2 = new Font(Font.HELVETICA, 10, Font.BOLD);
    private final Font smallFont = new Font(Font.HELVETICA, 10, Font.NORMAL);

    private String[] datatableHeaderFields = new String[]{"Header1", "Header2", "Header3", "Header4", "Header5", "Header6", "Header7", "Header8", "Header9"};
    public TestEventHelper(){
        super();
    }

    public List<Element> createTemplate() throws Exception {
        List<Element> elementList = new ArrayList<Element>();
        float[] tableWidths = new float[]{1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.25f, 1.25f, 1.25f, 1.25f};
//      logger.debug("entering create reports template...");

        PdfPTable splitTable = new PdfPTable(1);
        splitTable.setSplitRows(false);
        splitTable.setWidthPercentage(100f);

        PdfPTable pageTable = new PdfPTable(1);
        pageTable.setKeepTogether(true);
        pageTable.setWidthPercentage(100f);

        PdfPTable searchTable = generateSearchFields();
        if(searchTable != null){
            searchTable.setSpacingAfter(25f);
        }

        PdfPTable outlineTable = new PdfPTable(1);
        outlineTable.setKeepTogether(true);
        outlineTable.setWidthPercentage(100f);

        PdfPTable datatable = new PdfPTable(datatableHeaderFields.length);
        datatable.setKeepTogether(false);
        datatable.setWidths(tableWidths);


        generateDatatableHeader(datatable);

        for(int i = 0; i < 100; i++){
            addCell(datatable, String.valueOf(i), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+1), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+2), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+3), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+4), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+5), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+6), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+7), 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, smallFont, true);
            addCell(datatable, String.valueOf(i+8), 1, Rectangle.NO_BORDER, Element.ALIGN_RIGHT, smallFont, true);
        }

        PdfPCell dataCell = new PdfPCell(datatable);
        dataCell.setBorder(Rectangle.BOX);
        outlineTable.addCell(dataCell);

        PdfPCell searchCell = new PdfPCell(searchTable);
        searchCell.setVerticalAlignment(Element.ALIGN_TOP);

        PdfPCell outlineCell = new PdfPCell(outlineTable);
        outlineCell.setVerticalAlignment(Element.ALIGN_TOP);

        addCell(pageTable, searchCell, 1, Rectangle.NO_BORDER, Element.ALIGN_LEFT, null, null);
        addCell(pageTable, outlineCell, 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, null, null);

        PdfPCell pageCell = new PdfPCell(pageTable);
        pageCell.setVerticalAlignment(Element.ALIGN_TOP);
        addCell(splitTable, pageCell, 1, Rectangle.NO_BORDER, Element.ALIGN_CENTER, null, null);

        elementList.add(pageTable);
//      elementList.add(splitTable);

        return elementList;
    }

    public void onOpenDocument(PdfWriter writer, Document document) {
        total = writer.getDirectContent().createTemplate(100, 100);
        total.setBoundingBox(new Rectangle(-20, -20, 100, 100));
        try {
            helv = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }

    public void onEndPage(PdfWriter writer, Document document) {
        //TODO
    }

    public void onCloseDocument(PdfWriter writer, Document document) {
        total.beginText();
        total.setFontAndSize(helv, 10);
        total.setTextMatrix(0, 0);
        total.showText(String.valueOf(writer.getPageNumber() - 1));
        total.endText();
    }

    private PdfPTable generateSearchFields(){
        PdfPTable searchTable = new PdfPTable(2);

        for(int i = 0; i < 6; i++){
            addCell(searchTable, "Search Key" +i, 1, Rectangle.NO_BORDER, Element.ALIGN_RIGHT, font2, MARGIN, true);
            addCell(searchTable, "Search Value +i", 1, Rectangle.NO_BORDER, Element.ALIGN_LEFT, smallFont, null, true);
        }
        return searchTable;
    }

    private void generateDatatableHeader(PdfPTable datatable) {
        if (datatableHeaderFields != null && datatableHeaderFields.length != 0) {
            for (int i = 0; i < datatableHeaderFields.length; i++) {
                addCell(datatable, datatableHeaderFields[i], 1, Rectangle.BOX, Element.ALIGN_CENTER, font2);
            }
        }
    }

    private PdfPCell addCell(PdfPTable table, String cellContent, int colspan, int cellBorder, int horizontalAlignment, Font font) {
        return addCell(table, cellContent, colspan, cellBorder, horizontalAlignment, font, null, null);
    }

    private PdfPCell addCell(PdfPTable table, String cellContent, int colspan, int cellBorder, int horizontalAlignment, Font font, Boolean noWrap) {
        return addCell(table, cellContent, colspan, cellBorder, horizontalAlignment, font, null, noWrap);
    }

    private PdfPCell addCell(PdfPTable table, String cellContent, Integer colspan, Integer cellBorder, Integer horizontalAlignment, Font font, Float paddingLeft, Boolean noWrap) {
        PdfPCell cell = new PdfPCell(new Phrase(cellContent, font));
        return addCell(table, cell, colspan, cellBorder, horizontalAlignment, paddingLeft, noWrap);
    }

    private PdfPCell addCell(PdfPTable table, PdfPCell cell, int colspan, int cellBorder, int horizontalAlignment, Float paddingLeft, Boolean noWrap) {
        cell.setColspan(colspan);
        cell.setBorder(cellBorder);
        cell.setHorizontalAlignment(horizontalAlignment);
        if(paddingLeft != null){
            cell.setPaddingLeft(paddingLeft);
        }
        if(noWrap != null){
            cell.setNoWrap(noWrap);
        }
        table.addCell(cell);
        return cell;
    }

}
}

© Stack Overflow or respective owner

Related posts about java

Related posts about pdf