corner.orm.tapestry.pdf.components.AbstractPdfTableDisplay.java Source code

Java tutorial

Introduction

Here is the source code for corner.orm.tapestry.pdf.components.AbstractPdfTableDisplay.java

Source

// Copyright 2007 the original author or authors.
// site: http://www.bjmaxinfo.com
// file: $Id: AbstractPdfTableDisplay.java 3919 2008-01-16 04:36:52Z xf $
// created at:2007-07-31
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package corner.orm.tapestry.pdf.components;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.InjectObject;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfFormField;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPCellEvent;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.TextField;

import corner.orm.tapestry.pdf.PdfSystemException;
import corner.orm.tapestry.pdf.PdfUtils;
import corner.orm.tapestry.pdf.PdfWriterDelegate;

/**
 * pdf
 * 
 * @author <a href="mailto:jun.tsai@bjmaxinfo.com">Jun Tsai</a>
 * @author <a href=mailto:Ghostbb@bjmaxinfo.com>Ghostbb</a>
 * @version $Revision: 3919 $
 * @since 2.3.7
 */
public abstract class AbstractPdfTableDisplay extends AbstractColumnText {
    /**
     * ??List?.
     */
    public static final String CURRENT_CYCLE_SEQ_ATTRIBUTE_NAME = "pdf-current-overflow-table-seq";

    /**
     * ?source
     */
    public static final String CURRENT_SOURCE = "pdf-current-source";

    /**
     * table
     */
    public static final String OV_TABLE_MODE = "pdf-ov-table-model";

    /**
     * 
     * 
     * @return 
     */
    protected abstract IPdfTableModel<Object> getDisplayTableModel();

    /**
     * @see corner.orm.tapestry.pdf.components.AbstractColumnText#renderColumnText(com.lowagie.text.pdf.ColumnText, corner.orm.tapestry.pdf.PdfWriterDelegate, com.lowagie.text.Document)
     */
    @Override
    protected void renderColumnText(ColumnText ct, PdfWriterDelegate writer, Document doc) {
        // ???
        Integer currentCycleSeqObj = getRecord(CURRENT_CYCLE_SEQ_ATTRIBUTE_NAME, Integer.class);
        int currentSeq = 0;
        if (currentCycleSeqObj != null) {
            currentSeq = (Integer) currentCycleSeqObj;
        }

        // ??
        List sourceObj = getRecord(CURRENT_SOURCE, List.class);

        List source = sourceObj;
        if (sourceObj == null) {
            source = getDefaultSource();
        }

        // 
        Integer currentTemplateSourceStepObj = getRecord(getStepAttributeName(), Integer.class);

        int currentTemplateSourceStep = findCycleStep(currentTemplateSourceStepObj, writer, source);

        if (currentTemplateSourceStep == 0) {
            return;
        }

        /**
         * source?
         * 
         * :true :false
         */
        boolean isEndOfSource = source.size() <= (currentSeq + currentTemplateSourceStep);

        // System.out.println("current seq "+currentSeq+"
        // step:"+currentTemplateSourceStep);
        // ??
        addStepTableData(writer, source, ct, currentSeq, currentTemplateSourceStep, isEndOfSource);

        if (isEndOfSource) { // source?
            return;
        }
        // ??
        record(CURRENT_CYCLE_SEQ_ATTRIBUTE_NAME, currentSeq + currentTemplateSourceStep);
        record(getStepAttributeName(), currentTemplateSourceStep);
        record(CURRENT_SOURCE, source);

        doRenderOverflowContent(writer, currentCycleSeqObj == null);

        // ?
        if (currentCycleSeqObj == null) {// currentCycleSeqObj???
            rollback(CURRENT_CYCLE_SEQ_ATTRIBUTE_NAME, currentCycleSeqObj);
        }
        rollback(getStepAttributeName(), currentTemplateSourceStepObj);
        rollback(CURRENT_SOURCE, sourceObj);
    }

    protected String getStepAttributeName() {
        throw new UnsupportedOperationException();
    }

    protected List getDefaultSource() {
        throw new UnsupportedOperationException();
    }

    protected void doRenderOverflowContent(IMarkupWriter writer, boolean isFirstPage) {
        throw new UnsupportedOperationException();
    }

    /**
     * ??.
     * 
     * @param writer
     *            pdf writer ?
     * @param source
     *            ?Source
     * @return ??. true,????
     */
    protected boolean nextIsLastPage(PdfWriterDelegate writer, List source) {
        // ???
        Integer currentCycleSeqObj = getRecord(CURRENT_CYCLE_SEQ_ATTRIBUTE_NAME, Integer.class);
        int currentSeq = 0;
        if (currentCycleSeqObj != null) {
            currentSeq = (Integer) currentCycleSeqObj;
        }

        Integer currentTemplateSourceStepObj = getRecord(getStepAttributeName(), Integer.class);

        int currentTemplateSourceStep = findCycleStep(currentTemplateSourceStepObj, writer, source);

        // System.out.println("------------current seq "+currentSeq+"
        // step:"+currentTemplateSourceStep);
        return (currentSeq + currentTemplateSourceStep) >= source.size();

    }

    /**
     * TextField.
     * 
     * @author <a href="mailto:jun.tsai@bjmaxinfo.com">Jun Tsai</a>
     * @version $Revision: 3919 $
     * @since 0.7.5
     */
    private class CreateTextFieldCellEvent implements PdfPCellEvent {

        /** the writer with the acroform */
        private PdfWriter writer;

        /** the current fieldname */
        private String fieldname = "NoName";

        private String value;

        public CreateTextFieldCellEvent(PdfWriter writer, String string) {
            this.writer = writer;
            this.value = string;

        }

        /**
         * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
         *      com.lowagie.text.Rectangle,
         *      com.lowagie.text.pdf.PdfContentByte[])
         */
        public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
            TextField tf = getFieldCreator().createTextField(writer, position, fieldname);
            tf.setFont(PdfUtils.createSongLightBaseFont());
            tf.setOptions(TextField.MULTILINE);
            tf.setText(value);
            try {
                PdfFormField field = tf.getTextField();
                writer.addAnnotation(field);
            } catch (IOException e) {
                throw new PdfSystemException(e);
            } catch (DocumentException e) {
                throw new PdfSystemException(e);
            }
        }
    }

    protected PdfPTable createAllRowsTable(PdfWriter writer, List source) {
        int columnCount = getDisplayTableModel().getColumnCount();

        PdfPTable table = new PdfPTable(columnCount);
        table.setTotalWidth(this.getCurrentColumnTextWidth());
        beginTableHeader(table);
        try {
            table.setWidths(this.getDisplayTableModel().getColumPercentWidths());
        } catch (DocumentException e) {
            throw new PdfSystemException(e);
        }
        for (int i = 0; i < source.size(); i++) {
            createTableRow(writer, table, source.get(i), columnCount, getDisplayTableModel());
        }
        return table;
    }

    /**
     * PdfPTableHeader
     * 
     * @param table
     */
    protected void beginTableHeader(PdfPTable table) {
        // 
        if (this.getDisplayTableModel().getHeaders() != null) {
            Font headerFont = this.getDisplayTableModel().getHeadersFont();
            if (headerFont == null) {//footer
                headerFont = PdfUtils.createHeaderSongLightFont(10);
            }
            for (int i = 0; i < getDisplayTableModel().getColumnCount(); i++) {

                // TODO ??
                PdfPCell cell = new PdfPCell(new Phrase(getDisplayTableModel().getHeaders()[i], headerFont));

                cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);// 
                cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);// 

                table.addCell(cell);
            }
        }

    }

    /**
     * PdfPTableFooter
     * 
     * @param table
     */
    protected void beginTableFooter(PdfPTable table, PdfWriter writer) {
        if (this.getDisplayTableModel().getFooters() != null) {
            List<String> cells = this.getDisplayTableModel().getFooters();
            Font footerFont = this.getDisplayTableModel().getFootersFont();
            if (footerFont == null) {//footer
                footerFont = PdfUtils.createHeaderSongLightFont(10);
            }
            Iterator<String> it = cells.iterator();
            while (it.hasNext()) {
                String key = it.next();
                // TODO ??
                PdfPCell cell = new PdfPCell(new Phrase(key, footerFont));
                cell.setColspan(getDisplayTableModel().getColumnCount());
                cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);// ??
                cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);// 

                table.addCell(cell);
            }
        }
    }

    // ?
    protected void createTableRow(PdfWriter writer, PdfPTable table, Object obj, int columnCount,
            IPdfTableModel model) {
        Font contentFont = model.getContentFont();
        if (contentFont == null) {//model??
            contentFont = PdfUtils.createSongLightFont(10);
        }
        for (int i = 0; i < columnCount; i++) {
            // ??TableRow?.
            PdfPCell cell = new PdfPCell(new Phrase("", contentFont));
            // .
            cell.setCellEvent(
                    new CreateTextFieldCellEvent(writer, getDisplayTableModel().getCurrentColumnValue(obj, i)));
            table.addCell(cell);
        }

    }

    // ???
    protected PdfPTable createPdfTable(PdfWriter pdfWriter, List source, int start, int rows) {
        int columnCount = getDisplayTableModel().getColumnCount();

        PdfPTable table = new PdfPTable(columnCount);
        table.setTotalWidth(this.getCurrentColumnTextWidth());
        beginTableHeader(table);// TableHeader
        try {
            table.setWidths(this.getDisplayTableModel().getColumPercentWidths());
        } catch (DocumentException e) {
            throw new PdfSystemException(e);
        }

        for (int i = start; i < start + rows && i < source.size(); i++) {
            createTableRow(pdfWriter, table, source.get(i), columnCount, getDisplayTableModel());
        }
        return table;
    }

    /**
     * FooterPdfPTable
     * 
     * @param table
     * @return
     */
    protected PdfPTable createPdfFooterTable(PdfWriter pdfWriter, List source, int start, int rows) {
        PdfPTable table = this.createPdfTable(pdfWriter, source, start, rows);
        if (this.getDisplayTableModel().getFooters() != null) {
            this.beginTableFooter(table, pdfWriter);
        }
        return table;
    }

    // ?
    protected int findCurrentTemplateSourceStep(List source, PdfWriterDelegate writer, int rows, ColumnText ct)
            throws DocumentException {
        if (rows >= source.size()) {
            return rows;
        }
        PdfPTable table = createPdfTable(writer.getPdfWriter(), source, 0, rows);
        ct.addElement(table);
        if (ColumnText.hasMoreText(ct.go(true))) {
            ct.setYLine(this.getColumnTextStartHeight());
            return rows - 1;
        }
        // ?
        ct.setYLine(this.getColumnTextStartHeight());
        return findCurrentTemplateSourceStep(source, writer, ++rows, ct);
    }

    // 
    protected void record(String attrName, Object value) {
        getCycle().setAttribute(attrName, value);
    }

    // 
    @SuppressWarnings("unchecked")
    protected <T> T getRecord(String name, Class<T> clazz) {
        return (T) getCycle().getAttribute(name);
    }

    // ?
    protected void rollback(String name, Object oldObj) {
        if (oldObj != null) {
            getCycle().setAttribute(name, oldObj);
        } else {
            getCycle().removeAttribute(name);
        }

    }

    // ColumnText
    // TODO ???ColumnText??.
    protected ColumnText createTempColumnText(PdfWriterDelegate writer) {
        ColumnText tmpCT = new ColumnText(writer.getPdfWriter().getDirectContentUnder());
        String[] p = getRectangle().split(",");
        tmpCT.setSimpleColumn(Float.valueOf(p[0]), Float.valueOf(p[1]), Float.valueOf(p[2]), Float.valueOf(p[3]));
        return tmpCT;
    }

    // ?
    protected int findCycleStep(Integer currentTemplateSourceStepObj, PdfWriterDelegate writer, List source) {
        if (currentTemplateSourceStepObj != null) {
            return (Integer) currentTemplateSourceStepObj;
        } else {

            try {
                // ??
                ColumnText tmpCT = createTempColumnText(writer);
                return findCurrentTemplateSourceStep(source, writer, 1, tmpCT);
            } catch (DocumentException e) {
                throw new PdfSystemException(e);
            }
        }
    }

    // step??pdf
    protected void addStepTableData(PdfWriterDelegate writer, List source, ColumnText ct, int currentSeq,
            int currentTemplateSourceStep, boolean isEndOfSource) {
        try {
            //
            PdfPTable table = isEndOfSource
                    ? createPdfFooterTable(writer.getPdfWriter(), source, currentSeq, currentTemplateSourceStep)
                    : createPdfTable(writer.getPdfWriter(), source, currentSeq, currentTemplateSourceStep);
            ct.addElement(table);
            ct.go(false);
        } catch (DocumentException e) {
            throw new PdfSystemException(e);
        }
    }

    @InjectObject("infrastructure:requestCycle")
    public abstract IRequestCycle getCycle();

}