Search in sources :

Example 1 with ListItem

use of pdftk.com.lowagie.text.ListItem in project staplr by pridiltal.

the class PdfDocument method add.

/**
 * Adds a <CODE>PdfPTable</CODE> to the document.
 * @param ptable the <CODE>PdfPTable</CODE> to be added to the document.
 * @throws DocumentException on error
 */
/* ssteward: dropped in 1.44
    void addPTable(PdfPTable ptable) throws DocumentException {
        ColumnText ct = new ColumnText(writer.getDirectContent());
        if (currentHeight > 0) {
            Paragraph p = new Paragraph();
            p.setLeading(0);
            ct.addElement(p);
        }
        ct.addElement(ptable);
        boolean he = ptable.isHeadersInEvent();
        ptable.setHeadersInEvent(true);
        int loop = 0;
        while (true) {
            ct.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight);
            int status = ct.go();
            if ((status & ColumnText.NO_MORE_TEXT) != 0) {
                text.moveText(0, ct.getYLine() - indentTop() + currentHeight);
                currentHeight = indentTop() - ct.getYLine();
                break;
            }
            if (indentTop() - currentHeight == ct.getYLine())
                ++loop;
            else
                loop = 0;
            if (loop == 3) {
                add(new Paragraph("ERROR: Infinite table loop"));
                break;
            }
            newPage();
        }
        ptable.setHeadersInEvent(he);
    }
    */
/**
 * Gets a PdfTable object
 * (contributed by dperezcar@fcc.es)
 * @param table a high level table object
 * @param supportRowAdditions
 * @return returns a PdfTable object
 * @see PdfWriter#getPdfTable(Table)
 */
/* ssteward: dropped in 1.44
	PdfTable getPdfTable(Table table, boolean supportRowAdditions) {
        return new PdfTable(table, indentLeft(), indentRight(), indentTop() - currentHeight, supportRowAdditions);
	}
    */
/**
 * @see PdfWriter#breakTableIfDoesntFit(PdfTable)
 * (contributed by dperezcar@fcc.es)
 * @param table				Table to add
 * @return true if the table will be broken
 * @throws DocumentException
 */
/* ssteward: dropped in 1.44
	boolean breakTableIfDoesntFit(PdfTable table) throws DocumentException {
		table.updateRowAdditions();
		// Do we have any full page available?
		if (!table.hasToFitPageTable() && table.bottom() <= indentBottom) {
			// Then output that page
			add(table, true);
			return true;
		}
		return false;
	}
    */
/**
 * Adds a new table to
 * @param table				Table to add.  Rendered rows will be deleted after processing.
 * @param onlyFirstPage		Render only the first full page
 * @throws DocumentException
 */
/* ssteward: dropped in 1.44	
    private void add(PdfTable table, boolean onlyFirstPage) throws DocumentException {
        // before every table, we flush all lines
        flushLines();

		// initialisation of parameters
		float pagetop = indentTop();
		float oldHeight = currentHeight;
		float cellDisplacement;
		PdfCell cell;
		PdfContentByte cellGraphics = new PdfContentByte(writer);
		boolean tableHasToFit =
			table.hasToFitPageTable() ? (table.bottom() < indentBottom() && table.height() < (top() - bottom())) : false;
		if (pageEmpty)
			tableHasToFit = false;
		boolean cellsHaveToFit = table.hasToFitPageCells();
                    
		// drawing the table
		ArrayList cells = table.getCells();
		ArrayList headercells = table.getHeaderCells();
		// Check if we have removed header cells in a previous call
		if (headercells.size() > 0 && (cells.size() == 0 || cells.get(0) != headercells.get(0))) {
			ArrayList allCells = new ArrayList(cells.size()+headercells.size());
			allCells.addAll(headercells);
			allCells.addAll(cells);
			cells = allCells;
		}
		while (!cells.isEmpty()) {
			// initialisation of some extra parameters;
			float lostTableBottom = 0;
                        
			// loop over the cells
			boolean cellsShown = false;
			int currentGroupNumber = 0;
			boolean headerChecked = false;
			for (ListIterator iterator = cells.listIterator(); iterator.hasNext() && !tableHasToFit;) {
				cell = (PdfCell) iterator.next();
				boolean atLeastOneFits = false;
				if( cellsHaveToFit ) {
					if( !cell.isHeader() ) {
						if (cell.getGroupNumber() != currentGroupNumber) {
							boolean cellsFit = true;
							currentGroupNumber = cell.getGroupNumber();
							cellsHaveToFit = table.hasToFitPageCells();
							int cellCount = 0;
							while (cell.getGroupNumber() == currentGroupNumber && cellsFit && iterator.hasNext()) {
								if (cell.bottom() < indentBottom()) {
									cellsFit = false;
								}
								else {
									atLeastOneFits |= true;
								}
								cell = (PdfCell) iterator.next();
								cellCount++;
							}
							if (!atLeastOneFits) {
								cellsHaveToFit = false;
							}
							if (!cellsFit) {
								break;
							}
							for (int i = cellCount; i >= 0; i--) {
								cell = (PdfCell) iterator.previous();
							}
						}
					}
					else {
						if( !headerChecked ) {
							headerChecked = true;
							boolean cellsFit = true;
							int cellCount = 0;
							float firstTop = cell.top();
							while (cell.isHeader() && cellsFit && iterator.hasNext()) {
								if (firstTop - cell.bottom(0) > indentTop() - currentHeight - indentBottom()) {
									cellsFit = false;
								}
								cell = (PdfCell) iterator.next();
								cellCount++;
							}
							currentGroupNumber = cell.getGroupNumber();
							while (cell.getGroupNumber() == currentGroupNumber && cellsFit && iterator.hasNext()) {
								if (firstTop - cell.bottom(0) > indentTop() - currentHeight - indentBottom() - 10.0) {
									cellsFit = false;
								}
								cell = (PdfCell) iterator.next();
								cellCount++;
							}
							for (int i = cellCount; i >= 0; i--) {
								cell = (PdfCell) iterator.previous();
							}
							if (!cellsFit) {
								while( cell.isHeader() ) {
									iterator.remove();
									cell = (PdfCell) iterator.next();
								}
								break;
							}
						}
					}
				}
				lines = cell.getLines(pagetop, indentBottom());
				// if there are lines to add, add them
				if (lines != null && lines.size() > 0) {
					// we paint the borders of the cells
					cellsShown = true;
					cellGraphics.rectangle(cell.rectangle(pagetop, indentBottom()));
					lostTableBottom = Math.max(cell.bottom(), indentBottom());
                                
					// we write the text
					float cellTop = cell.top(pagetop - oldHeight);
					text.moveText(0, cellTop);
					cellDisplacement = flushLines() - cellTop;
					text.moveText(0, cellDisplacement);
					if (oldHeight + cellDisplacement > currentHeight) {
						currentHeight = oldHeight + cellDisplacement;
					}
				}
				ArrayList images = cell.getImages(pagetop, indentBottom());
				for (Iterator i = images.iterator(); i.hasNext();) {
					cellsShown = true;
					Image image = (Image) i.next();
					graphics.addImage(image);
				}
				// if a cell is allready added completely, remove it
				if (cell.mayBeRemoved()) {
					iterator.remove();
				}
			}
			tableHasToFit = false;
			// we paint the graphics of the table after looping through all the cells
			if (cellsShown) {
				Rectangle tablerec = new Rectangle(table);
				tablerec.setBorder(table.border());
				tablerec.setBorderWidth(table.borderWidth());
				tablerec.setBorderColor(table.borderColor());
				tablerec.setBackgroundColor(table.backgroundColor());
				tablerec.setGrayFill(table.grayFill());
				PdfContentByte under = writer.getDirectContentUnder();
				under.rectangle(tablerec.rectangle(top(), indentBottom()));
				under.add(cellGraphics);
				// bugfix by Gerald Fehringer: now again add the border for the table
				// since it might have been covered by cell backgrounds
				tablerec.setGrayFill(0);
				tablerec.setBackgroundColor(null);
				under.rectangle(tablerec.rectangle(top(), indentBottom()));
				// end bugfix
			}
			cellGraphics = new PdfContentByte(null);
			// if the table continues on the next page
			if (!cells.isEmpty()) {
				graphics.setLineWidth(table.borderWidth());
				if (cellsShown && (table.border() & Rectangle.BOTTOM) == Rectangle.BOTTOM) {
					// Draw the bottom line
                                
					// the color is set to the color of the element
					Color tColor = table.borderColor();
					if (tColor != null) {
						graphics.setColorStroke(tColor);
					}
					graphics.moveTo(table.left(), Math.max(table.bottom(), indentBottom()));
					graphics.lineTo(table.right(), Math.max(table.bottom(), indentBottom()));
					graphics.stroke();
					if (tColor != null) {
						graphics.resetRGBColorStroke();
					}
				}
                            
				// old page
				pageEmpty = false;
				float difference = lostTableBottom;
                            
				// new page
				newPage();
				// G.F.: if something added in page event i.e. currentHeight > 0
				float heightCorrection = 0;
				boolean somethingAdded = false;
				if (currentHeight > 0) {
					heightCorrection = 6;
					currentHeight += heightCorrection;
					somethingAdded = true;
					newLine();
					flushLines();
					indentTop = currentHeight - leading;
					currentHeight = 0;
				}
				else {
					flushLines();
				}
                            
				// this part repeats the table headers (if any)
				int size = headercells.size();
				if (size > 0) {
					// this is the top of the headersection
					cell = (PdfCell) headercells.get(0);
					float oldTop = cell.top(0);
					// loop over all the cells of the table header
					for (int i = 0; i < size; i++) {
						cell = (PdfCell) headercells.get(i);
						// calculation of the new cellpositions
						cell.setTop(indentTop() - oldTop + cell.top(0));
						cell.setBottom(indentTop() - oldTop + cell.bottom(0));
						pagetop = cell.bottom();
						// we paint the borders of the cell
						cellGraphics.rectangle(cell.rectangle(indentTop(), indentBottom()));
						// we write the text of the cell
						ArrayList images = cell.getImages(indentTop(), indentBottom());
						for (Iterator im = images.iterator(); im.hasNext();) {
							cellsShown = true;
							Image image = (Image) im.next();
							graphics.addImage(image);
						}
						lines = cell.getLines(indentTop(), indentBottom());
						float cellTop = cell.top(indentTop());
						text.moveText(0, cellTop-heightCorrection);
						cellDisplacement = flushLines() - cellTop+heightCorrection;
						text.moveText(0, cellDisplacement);
					}           
					currentHeight = indentTop() - pagetop + table.cellspacing();
					text.moveText(0, pagetop - indentTop() - currentHeight);
				}
				else {
					if (somethingAdded) {
						pagetop = indentTop();
						text.moveText(0, -table.cellspacing());
					}
				}
				oldHeight = currentHeight - heightCorrection;
                            
				// calculating the new positions of the table and the cells
				size = Math.min(cells.size(), table.columns());
				int i = 0;
				while (i < size) {
					cell = (PdfCell) cells.get(i);
					if (cell.top(-table.cellspacing()) > lostTableBottom) {
						float newBottom = pagetop - difference + cell.bottom();
						float neededHeight = cell.remainingHeight();
						if (newBottom > pagetop - neededHeight) {
							difference += newBottom - (pagetop - neededHeight);
						}
					}
					i++;
				}
				size = cells.size();
				table.setTop(indentTop());
				table.setBottom(pagetop - difference + table.bottom(table.cellspacing()));
				for (i = 0; i < size; i++) {
					cell = (PdfCell) cells.get(i);
					float newBottom = pagetop - difference + cell.bottom();
					float newTop = pagetop - difference + cell.top(-table.cellspacing());
					if (newTop > indentTop() - currentHeight) {
						newTop = indentTop() - currentHeight;
					}
					//float newBottom = newTop - cell.height();
					cell.setTop(newTop );
					cell.setBottom(newBottom );
				}
				if (onlyFirstPage) {
					break;
				}
			}
		}
                    
        float tableHeight = table.top() - table.bottom();
        currentHeight = oldHeight + tableHeight;
        text.moveText(0, -tableHeight );
        pageEmpty = false;
    }
    */
/**
 * Signals that an <CODE>Element</CODE> was added to the <CODE>Document</CODE>.
 *
 * @param element the element to add
 * @return <CODE>true</CODE> if the element was added, <CODE>false</CODE> if not.
 * @throws DocumentException when a document isn't open yet, or has been closed
 */
public boolean add(Element element) throws DocumentException {
    if (writer != null && writer.isPaused()) {
        return false;
    }
    try {
        switch(element.type()) {
            // Information (headers)
            case Element.HEADER:
                info.addkey(((Meta) element).name(), ((Meta) element).content());
                break;
            case Element.TITLE:
                info.addTitle(((Meta) element).content());
                break;
            case Element.SUBJECT:
                info.addSubject(((Meta) element).content());
                break;
            case Element.KEYWORDS:
                info.addKeywords(((Meta) element).content());
                break;
            case Element.AUTHOR:
                info.addAuthor(((Meta) element).content());
                break;
            case Element.CREATOR:
                info.addCreator(((Meta) element).content());
                break;
            case Element.PRODUCER:
                // you can not change the name of the producer
                info.addProducer();
                break;
            case Element.CREATIONDATE:
                // you can not set the creation date, only reset it
                info.addCreationDate();
                break;
            case Element.CHUNK:
                {
                    // if there isn't a current line available, we make one
                    if (line == null) {
                        carriageReturn();
                    }
                    // we cast the element to a chunk
                    PdfChunk chunk = new PdfChunk((Chunk) element, currentAction);
                    // we try to add the chunk to the line, until we succeed
                    {
                        PdfChunk overflow;
                        while ((overflow = line.add(chunk)) != null) {
                            carriageReturn();
                            chunk = overflow;
                        }
                    }
                    pageEmpty = false;
                    if (chunk.isAttribute(Chunk.NEWPAGE)) {
                        newPage();
                    }
                    break;
                }
            case Element.ANCHOR:
                {
                    Anchor anchor = (Anchor) element;
                    String url = anchor.reference();
                    leading = anchor.leading();
                    if (url != null) {
                        currentAction = new PdfAction(url);
                    }
                    // we process the element
                    element.process(this);
                    currentAction = null;
                    break;
                }
            case Element.ANNOTATION:
                {
                    if (line == null) {
                        carriageReturn();
                    }
                    Annotation annot = (Annotation) element;
                    PdfAnnotation an = convertAnnotation(writer, annot);
                    annotations.add(an);
                    pageEmpty = false;
                    break;
                }
            case Element.PHRASE:
                {
                    // we cast the element to a phrase and set the leading of the document
                    leading = ((Phrase) element).leading();
                    // we process the element
                    element.process(this);
                    break;
                }
            case Element.PARAGRAPH:
                {
                    // we cast the element to a paragraph
                    Paragraph paragraph = (Paragraph) element;
                    float spacingBefore = paragraph.spacingBefore();
                    if (spacingBefore != 0) {
                        leading = spacingBefore;
                        carriageReturn();
                        if (!pageEmpty) {
                            /*
                             * Don't add spacing before a paragraph if it's the first
                             * on the page
                             */
                            Chunk space = new Chunk(" ");
                            space.process(this);
                            carriageReturn();
                        }
                    }
                    // we adjust the parameters of the document
                    alignment = paragraph.alignment();
                    leading = paragraph.leading();
                    carriageReturn();
                    // we don't want to make orphans/widows
                    if (currentHeight + line.height() + leading > indentTop() - indentBottom()) {
                        newPage();
                    }
                    // Begin added: Bonf (Marc Schneider) 2003-07-29
                    // carriageReturn();
                    // End added: Bonf (Marc Schneider) 2003-07-29
                    indentLeft += paragraph.indentationLeft();
                    indentRight += paragraph.indentationRight();
                    // Begin removed: Bonf (Marc Schneider) 2003-07-29
                    carriageReturn();
                    // End removed: Bonf (Marc Schneider) 2003-07-29
                    // add by Jin-Hsia Yang
                    paraIndent += paragraph.indentationLeft();
                    // end add by Jin-Hsia Yang
                    PdfPageEvent pageEvent = writer.getPageEvent();
                    if (pageEvent != null && isParagraph)
                        pageEvent.onParagraph(writer, this, indentTop() - currentHeight);
                    /* ssteward: dropped in 1.44
                    // if a paragraph has to be kept together, we wrap it in a table object
                    if (paragraph.getKeepTogether()) {
                        Table table = new Table(1, 1);
                        table.setOffset(0f);
                        table.setBorder(Table.NO_BORDER);
                        table.setWidth(100f);
                        table.setTableFitsPage(true);
                        Cell cell = new Cell(paragraph);
                        cell.setBorder(Table.NO_BORDER);
                        //patch by Matt Benson 11/01/2002 - 14:32:00
                        cell.setHorizontalAlignment(paragraph.alignment());
                        //end patch by Matt Benson
                        table.addCell(cell);
                        this.add(table);
                        break;
                    }
                    else
		    */
                    // we process the paragraph
                    element.process(this);
                    // add by Jin-Hsia Yang and blowagie
                    paraIndent -= paragraph.indentationLeft();
                    // end add by Jin-Hsia Yang and blowagie
                    // Begin removed: Bonf (Marc Schneider) 2003-07-29
                    // carriageReturn();
                    // End removed: Bonf (Marc Schneider) 2003-07-29
                    float spacingAfter = paragraph.spacingAfter();
                    if (spacingAfter != 0) {
                        leading = spacingAfter;
                        carriageReturn();
                        if (currentHeight + line.height() + leading < indentTop() - indentBottom()) {
                            /*
                             * Only add spacing after a paragraph if the extra
                             * spacing fits on the page.
                             */
                            Chunk space = new Chunk(" ");
                            space.process(this);
                            carriageReturn();
                        }
                        // restore original leading
                        leading = paragraph.leading();
                    }
                    if (pageEvent != null && isParagraph)
                        pageEvent.onParagraphEnd(writer, this, indentTop() - currentHeight);
                    alignment = Element.ALIGN_LEFT;
                    indentLeft -= paragraph.indentationLeft();
                    indentRight -= paragraph.indentationRight();
                    // Begin added: Bonf (Marc Schneider) 2003-07-29
                    carriageReturn();
                    break;
                }
            /* ssteward: dropped in 1.44
                case Element.SECTION:
                case Element.CHAPTER: {
                    // Chapters and Sections only differ in their constructor
                    // so we cast both to a Section
                    Section section = (Section) element;
                    
                    boolean hasTitle = section.title() != null;
                    
                    // if the section is a chapter, we begin a new page
                    if (section.isChapter()) {
                        newPage();
                    }
                    // otherwise, we begin a new line
                    else {
                        newLine();
                    }

                    if (hasTitle) {
                    float fith = indentTop() - currentHeight;
                    int rotation = pageSize.getRotation();
                    if (rotation == 90 || rotation == 180)
                        fith = pageSize.height() - fith;
                    PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith);
                    while (currentOutline.level() >= section.depth()) {
                        currentOutline = currentOutline.parent();
                    }
                    PdfOutline outline = new PdfOutline(currentOutline, destination, section.getBookmarkTitle(), section.isBookmarkOpen());
                    currentOutline = outline;
                    }
                    
                    // some values are set
                    carriageReturn();
                    indentLeft += section.indentationLeft();
                    indentRight += section.indentationRight();
                    
                    PdfPageEvent pageEvent = writer.getPageEvent();
                    if (pageEvent != null)
                        if (element.type() == Element.CHAPTER)
                            pageEvent.onChapter(writer, this, indentTop() - currentHeight, section.title());
                        else
                            pageEvent.onSection(writer, this, indentTop() - currentHeight, section.depth(), section.title());
                    
                    // the title of the section (if any has to be printed)
                    if (hasTitle) {
                        isParagraph = false;
                        add(section.title());
                        isParagraph = true;
                    }
                    indentLeft += section.indentation();
                    // we process the section
                    element.process(this);
                    // some parameters are set back to normal again
                    indentLeft -= section.indentationLeft() + section.indentation();
                    indentRight -= section.indentationRight();
                    
                    if (pageEvent != null)
                        if (element.type() == Element.CHAPTER)
                            pageEvent.onChapterEnd(writer, this, indentTop() - currentHeight);
                        else
                            pageEvent.onSectionEnd(writer, this, indentTop() - currentHeight);
                    
                    break;
                }
*/
            case Element.LIST:
                {
                    // we cast the element to a List
                    List list = (List) element;
                    // we adjust the document
                    listIndentLeft += list.indentationLeft();
                    indentRight += list.indentationRight();
                    // we process the items in the list
                    element.process(this);
                    // some parameters are set back to normal again
                    listIndentLeft -= list.indentationLeft();
                    indentRight -= list.indentationRight();
                    break;
                }
            case Element.LISTITEM:
                {
                    // we cast the element to a ListItem
                    ListItem listItem = (ListItem) element;
                    float spacingBefore = listItem.spacingBefore();
                    if (spacingBefore != 0) {
                        leading = spacingBefore;
                        carriageReturn();
                        if (!pageEmpty) {
                            /*
                             * Don't add spacing before a paragraph if it's the first
                             * on the page
                             */
                            Chunk space = new Chunk(" ");
                            space.process(this);
                            carriageReturn();
                        }
                    }
                    // we adjust the document
                    alignment = listItem.alignment();
                    listIndentLeft += listItem.indentationLeft();
                    indentRight += listItem.indentationRight();
                    leading = listItem.leading();
                    carriageReturn();
                    // we prepare the current line to be able to show us the listsymbol
                    line.setListItem(listItem);
                    // we process the item
                    element.process(this);
                    float spacingAfter = listItem.spacingAfter();
                    if (spacingAfter != 0) {
                        leading = spacingAfter;
                        carriageReturn();
                        if (currentHeight + line.height() + leading < indentTop() - indentBottom()) {
                            /*
                             * Only add spacing after a paragraph if the extra
                             * spacing fits on the page.
                             */
                            Chunk space = new Chunk(" ");
                            space.process(this);
                            carriageReturn();
                        }
                        // restore original leading
                        leading = listItem.leading();
                    }
                    // if the last line is justified, it should be aligned to the left
                    // if (line.hasToBeJustified()) {
                    // line.resetAlignment();
                    // }
                    // some parameters are set back to normal again
                    carriageReturn();
                    listIndentLeft -= listItem.indentationLeft();
                    indentRight -= listItem.indentationRight();
                    break;
                }
            case Element.RECTANGLE:
                {
                    Rectangle rectangle = (Rectangle) element;
                    graphics.rectangle(rectangle);
                    pageEmpty = false;
                    break;
                }
            /*
	                    
					PdfTable table;
                    if (element instanceof PdfTable) {
                    	// Already pre-rendered
                    	table = (PdfTable)element;
						table.updateRowAdditions();
                    } else if (element instanceof SimpleTable) {
                    	PdfPTable ptable = ((SimpleTable)element).createPdfPTable();
                    	if (ptable.size() <= ptable.getHeaderRows())
                    		break; //nothing to do
            		
                    	// before every table, we add a new line and flush all lines
                    	ensureNewLine();
                    	flushLines();
                    	addPTable(ptable);                    
                    	pageEmpty = false;
                    	break;
                    } else if (element instanceof Table) {

                    	try {
                    		PdfPTable ptable = ((Table)element).createPdfPTable();
                    		if (ptable.size() <= ptable.getHeaderRows())
                                break; //nothing to do
                    		
                            // before every table, we add a new line and flush all lines
                            ensureNewLine();
                            flushLines();
                            addPTable(ptable);                    
                            pageEmpty = false;
                            break;
                    	}
                    	catch(BadElementException bee) {
                    		// constructing the PdfTable
                            // Before the table, add a blank line using offset or default leading
                            float offset = ((Table)element).getOffset();
                            if (Float.isNaN(offset))
                                offset = leading;
                            carriageReturn();
                            lines.add(new PdfLine(indentLeft(), indentRight(), alignment, offset));
                            currentHeight += offset;
    	                    table = getPdfTable((Table)element, false);
                    	}
					} else {
						return false;
					}
                    add(table, false);
                    break;
                }
                case Element.JPEG:
                case Element.IMGRAW:
                case Element.IMGTEMPLATE: {
                    //carriageReturn(); suggestion by Marc Campforts
                    add((Image) element);
                    break;
                }
                case Element.GRAPHIC: {
                    Graphic graphic = (Graphic) element;
                    graphic.processAttributes(indentLeft(), indentBottom(), indentRight(), indentTop(), indentTop() - currentHeight);
                    graphics.add(graphic);
                    pageEmpty = false;
                    break;
                }
    */
            default:
                return false;
        }
        lastElementType = element.type();
        return true;
    } catch (Exception e) {
        throw new DocumentException(e);
    }
}
Also used : Rectangle(pdftk.com.lowagie.text.Rectangle) Phrase(pdftk.com.lowagie.text.Phrase) Chunk(pdftk.com.lowagie.text.Chunk) Annotation(pdftk.com.lowagie.text.Annotation) IOException(java.io.IOException) DocumentException(pdftk.com.lowagie.text.DocumentException) Paragraph(pdftk.com.lowagie.text.Paragraph) Anchor(pdftk.com.lowagie.text.Anchor) DocumentException(pdftk.com.lowagie.text.DocumentException) List(pdftk.com.lowagie.text.List) ArrayList(java.util.ArrayList) ListItem(pdftk.com.lowagie.text.ListItem)

Example 2 with ListItem

use of pdftk.com.lowagie.text.ListItem in project staplr by pridiltal.

the class ColumnText method goComposite.

protected int goComposite(boolean simulate) throws DocumentException {
    if (!rectangularMode)
        throw new DocumentException("Irregular columns are not supported in composite mode.");
    linesWritten = 0;
    descender = 0;
    boolean firstPass = true;
    main_loop: while (true) {
        if (compositeElements.isEmpty())
            return NO_MORE_TEXT;
        Element element = (Element) compositeElements.getFirst();
        if (element.type() == Element.PARAGRAPH) {
            Paragraph para = (Paragraph) element;
            int status = 0;
            for (int keep = 0; keep < 2; ++keep) {
                float lastY = yLine;
                boolean createHere = false;
                if (compositeColumn == null) {
                    compositeColumn = new ColumnText(canvas);
                    compositeColumn.setUseAscender(firstPass ? useAscender : false);
                    compositeColumn.setAlignment(para.alignment());
                    compositeColumn.setIndent(para.indentationLeft() + para.getFirstLineIndent());
                    compositeColumn.setExtraParagraphSpace(para.getExtraParagraphSpace());
                    compositeColumn.setFollowingIndent(para.indentationLeft());
                    compositeColumn.setRightIndent(para.indentationRight());
                    compositeColumn.setLeading(para.leading(), para.getMultipliedLeading());
                    compositeColumn.setRunDirection(runDirection);
                    compositeColumn.setArabicOptions(arabicOptions);
                    compositeColumn.setSpaceCharRatio(spaceCharRatio);
                    compositeColumn.addText(para);
                    if (!firstPass) {
                        yLine -= para.spacingBefore();
                    }
                    createHere = true;
                }
                compositeColumn.leftX = leftX;
                compositeColumn.rightX = rightX;
                compositeColumn.yLine = yLine;
                compositeColumn.rectangularWidth = rectangularWidth;
                compositeColumn.rectangularMode = rectangularMode;
                compositeColumn.minY = minY;
                compositeColumn.maxY = maxY;
                boolean keepCandidate = (para.getKeepTogether() && createHere && !firstPass);
                status = compositeColumn.go(simulate || (keepCandidate && keep == 0));
                if ((status & NO_MORE_TEXT) == 0 && keepCandidate) {
                    compositeColumn = null;
                    yLine = lastY;
                    return NO_MORE_COLUMN;
                }
                if (simulate || !keepCandidate)
                    break;
                if (keep == 0) {
                    compositeColumn = null;
                    yLine = lastY;
                }
            }
            firstPass = false;
            yLine = compositeColumn.yLine;
            linesWritten += compositeColumn.linesWritten;
            descender = compositeColumn.descender;
            if ((status & NO_MORE_TEXT) != 0) {
                compositeColumn = null;
                compositeElements.removeFirst();
                yLine -= para.spacingAfter();
            }
            if ((status & NO_MORE_COLUMN) != 0) {
                return NO_MORE_COLUMN;
            }
        } else if (element.type() == Element.LIST) {
            pdftk.com.lowagie.text.List list = (pdftk.com.lowagie.text.List) element;
            ArrayList items = list.getItems();
            ListItem item = null;
            float listIndentation = list.indentationLeft();
            int count = 0;
            Stack stack = new Stack();
            for (int k = 0; k < items.size(); ++k) {
                Object obj = items.get(k);
                if (obj instanceof ListItem) {
                    if (count == listIdx) {
                        item = (ListItem) obj;
                        break;
                    } else
                        ++count;
                } else if (obj instanceof pdftk.com.lowagie.text.List) {
                    stack.push(new Object[] { list, new Integer(k), new Float(listIndentation) });
                    list = (pdftk.com.lowagie.text.List) obj;
                    items = list.getItems();
                    listIndentation += list.indentationLeft();
                    k = -1;
                    continue;
                }
                if (k == items.size() - 1) {
                    if (!stack.isEmpty()) {
                        Object[] objs = (Object[]) stack.pop();
                        list = (pdftk.com.lowagie.text.List) objs[0];
                        items = list.getItems();
                        k = ((Integer) objs[1]).intValue();
                        listIndentation = ((Float) objs[2]).floatValue();
                    }
                }
            }
            int status = 0;
            for (int keep = 0; keep < 2; ++keep) {
                float lastY = yLine;
                boolean createHere = false;
                if (compositeColumn == null) {
                    if (item == null) {
                        listIdx = 0;
                        compositeElements.removeFirst();
                        continue main_loop;
                    }
                    compositeColumn = new ColumnText(canvas);
                    compositeColumn.setUseAscender(firstPass ? useAscender : false);
                    compositeColumn.setAlignment(item.alignment());
                    compositeColumn.setIndent(item.indentationLeft() + listIndentation + item.getFirstLineIndent());
                    compositeColumn.setExtraParagraphSpace(item.getExtraParagraphSpace());
                    compositeColumn.setFollowingIndent(compositeColumn.getIndent());
                    compositeColumn.setRightIndent(item.indentationRight() + list.indentationRight());
                    compositeColumn.setLeading(item.leading(), item.getMultipliedLeading());
                    compositeColumn.setRunDirection(runDirection);
                    compositeColumn.setArabicOptions(arabicOptions);
                    compositeColumn.setSpaceCharRatio(spaceCharRatio);
                    compositeColumn.addText(item);
                    if (!firstPass) {
                        yLine -= item.spacingBefore();
                    }
                    createHere = true;
                }
                compositeColumn.leftX = leftX;
                compositeColumn.rightX = rightX;
                compositeColumn.yLine = yLine;
                compositeColumn.rectangularWidth = rectangularWidth;
                compositeColumn.rectangularMode = rectangularMode;
                compositeColumn.minY = minY;
                compositeColumn.maxY = maxY;
                boolean keepCandidate = (item.getKeepTogether() && createHere && !firstPass);
                status = compositeColumn.go(simulate || (keepCandidate && keep == 0));
                if ((status & NO_MORE_TEXT) == 0 && keepCandidate) {
                    compositeColumn = null;
                    yLine = lastY;
                    return NO_MORE_COLUMN;
                }
                if (simulate || !keepCandidate)
                    break;
                if (keep == 0) {
                    compositeColumn = null;
                    yLine = lastY;
                }
            }
            firstPass = false;
            yLine = compositeColumn.yLine;
            linesWritten += compositeColumn.linesWritten;
            descender = compositeColumn.descender;
            if (!Float.isNaN(compositeColumn.firstLineY) && !compositeColumn.firstLineYDone) {
                if (!simulate)
                    showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(item.listSymbol()), compositeColumn.leftX + listIndentation, compositeColumn.firstLineY, 0);
                compositeColumn.firstLineYDone = true;
            }
            if ((status & NO_MORE_TEXT) != 0) {
                compositeColumn = null;
                ++listIdx;
                yLine -= item.spacingAfter();
            }
            if ((status & NO_MORE_COLUMN) != 0) {
                return NO_MORE_COLUMN;
            }
        } else
            /* ssteward: dropped in 1.44 
            else if (element.type() == Element.PTABLE) {
                if (yLine < minY || yLine > maxY)
                    return NO_MORE_COLUMN;
                PdfPTable table = (PdfPTable)element;
                if (table.size() <= table.getHeaderRows()) {
                    compositeElements.removeFirst();
                    continue;
                }
                float yTemp = yLine;
                float yLineWrite = yLine;
                if (!firstPass && listIdx == 0) {
                    yTemp -= table.spacingBefore();
                    yLineWrite = yTemp;
                }
                currentLeading = 0;
                if (yTemp < minY || yTemp > maxY)
                    return NO_MORE_COLUMN;
                float x1 = leftX;
                float tableWidth;
                if (table.isLockedWidth())
                    tableWidth = table.getTotalWidth();
                else {
                    tableWidth = rectangularWidth * table.getWidthPercentage() / 100f;
                    table.setTotalWidth(tableWidth);
                }
                int k;
                boolean skipHeader = (!firstPass && table.isSkipFirstHeader() && listIdx <= table.getHeaderRows());
                if (!skipHeader) {
                    yTemp -= table.getHeaderHeight();
                    if (yTemp < minY || yTemp > maxY) {
                        if (firstPass) {
                            compositeElements.removeFirst();
                            continue;
                        }
                        return NO_MORE_COLUMN;
                    }
                }
                if (listIdx < table.getHeaderRows())
                    listIdx = table.getHeaderRows();
                for (k = listIdx; k < table.size(); ++k) {
                    float rowHeight = table.getRowHeight(k);
                    if (yTemp - rowHeight < minY)
                        break;
                    yTemp -= rowHeight;
                }
                if (k < table.size()) {
                    if (table.isSplitRows() && (!table.isSplitLate() || (k == listIdx && firstPass))) {
                        if (!splittedRow) {
                            splittedRow = true;
                            table = new PdfPTable(table);
                            compositeElements.set(0, table);
                            ArrayList rows = table.getRows();
                            for (int i = table.getHeaderRows(); i < listIdx; ++i)
                                rows.set(i, null);
                        }
                        float h = yTemp - minY;
                        PdfPRow newRow = table.getRow(k).splitRow(h);
                        if (newRow == null) {
                            if (k == listIdx)
                                return NO_MORE_COLUMN;
                        }
                        else {
                            yTemp = minY;
                            table.getRows().add(++k, newRow);
                        }
                    }
                    else if (!table.isSplitRows() && k == listIdx && firstPass) {
                        compositeElements.removeFirst();
                        splittedRow = false;
                        continue;
                    }
                    else if (k == listIdx && !firstPass && (!table.isSplitRows() || table.isSplitLate())) {
                            return NO_MORE_COLUMN;
                    }
                }
                firstPass = false;
                if (!simulate) {
                    switch (table.getHorizontalAlignment()) {
                        case Element.ALIGN_LEFT:
                            break;
                        case Element.ALIGN_RIGHT:
                            x1 += rectangularWidth - tableWidth;
                            break;
                        default:
                            x1 += (rectangularWidth - tableWidth) / 2f;
                    }
                    PdfPTable nt = PdfPTable.shallowCopy(table);
                    ArrayList rows = table.getRows();
                    ArrayList sub = nt.getRows();
                    if (!skipHeader) {
                        for (int j = 0; j < table.getHeaderRows(); ++j)
                            sub.add(rows.get(j));
                    }
                    else
                        nt.setHeaderRows(0);
                    for (int j = listIdx; j < k; ++j)
                        sub.add(rows.get(j));
                    float rowHeight = 0;
                    if (table.isExtendLastRow()) {
                        PdfPRow last = (PdfPRow)sub.get(sub.size() - 1);
                        rowHeight = last.getMaxHeights();
                        last.setMaxHeights(yTemp - minY + rowHeight);
                        yTemp = minY;
                    }
                    nt.writeSelectedRows(0, -1, x1, yLineWrite, canvas);
                    if (table.isExtendLastRow()) {
                        PdfPRow last = (PdfPRow)sub.get(sub.size() - 1);
                        last.setMaxHeights(rowHeight);
                    }
                }
                else if (table.isExtendLastRow() && minY > PdfPRow.BOTTOM_LIMIT)
                    yTemp = minY;
                yLine = yTemp;
                if (k >= table.size()) {
                    yLine -= table.spacingAfter();
                    compositeElements.removeFirst();
                    splittedRow = false;
                    listIdx = 0;
                }
                else {
                    if (splittedRow) {
                        ArrayList rows = table.getRows();
                        for (int i = listIdx; i < k; ++i)
                            rows.set(i, null);
                    }
                    listIdx = k;
                    return NO_MORE_COLUMN;
                }
            }
	    */
            /* ssteward: dropped in 1.44
            else if (element.type() == Element.GRAPHIC) {
                if (!simulate) {
                    Graphic gr = (Graphic)element;
                    ByteBuffer bf = gr.getInternalBuffer();
                    ByteBuffer store = null;
                    if (bf.size() > 0) {
                        store = new ByteBuffer();
                        store.append(bf);
                        bf.reset();
                    }
                    gr.processAttributes(leftX, minY, rightX, maxY, yLine);
                    canvas.add(gr);
                    bf.reset();
                    if (store != null) {
                        bf.append(store);
                    }
                }
                compositeElements.removeFirst();
            }
	    */
            compositeElements.removeFirst();
    }
}
Also used : Element(pdftk.com.lowagie.text.Element) ArrayList(java.util.ArrayList) Phrase(pdftk.com.lowagie.text.Phrase) Paragraph(pdftk.com.lowagie.text.Paragraph) Stack(java.util.Stack) DocumentException(pdftk.com.lowagie.text.DocumentException) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) ListItem(pdftk.com.lowagie.text.ListItem)

Aggregations

ArrayList (java.util.ArrayList)2 DocumentException (pdftk.com.lowagie.text.DocumentException)2 ListItem (pdftk.com.lowagie.text.ListItem)2 Paragraph (pdftk.com.lowagie.text.Paragraph)2 Phrase (pdftk.com.lowagie.text.Phrase)2 IOException (java.io.IOException)1 LinkedList (java.util.LinkedList)1 Stack (java.util.Stack)1 Anchor (pdftk.com.lowagie.text.Anchor)1 Annotation (pdftk.com.lowagie.text.Annotation)1 Chunk (pdftk.com.lowagie.text.Chunk)1 Element (pdftk.com.lowagie.text.Element)1 List (pdftk.com.lowagie.text.List)1 Rectangle (pdftk.com.lowagie.text.Rectangle)1