Search in sources :

Example 1 with DocumentException

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

the class PdfDocument method ensureNewLine.

/**
 * Ensures that a new line has been started.
 */
private void ensureNewLine() {
    try {
        if ((lastElementType == Element.PHRASE) || (lastElementType == Element.CHUNK)) {
            newLine();
            flushLines();
        }
    } catch (DocumentException ex) {
        throw new ExceptionConverter(ex);
    }
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter) DocumentException(pdftk.com.lowagie.text.DocumentException)

Example 2 with DocumentException

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

the class PdfDocument method open.

// methods to open and close a document
/**
 * Opens the document.
 * <P>
 * You have to open the document before you can begin to add content
 * to the body of the document.
 */
public void open() {
    if (!open) {
        super.open();
        writer.open();
        rootOutline = new PdfOutline(writer);
        currentOutline = rootOutline;
    }
    try {
        initPage();
    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    }
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter) DocumentException(pdftk.com.lowagie.text.DocumentException)

Example 3 with DocumentException

use of pdftk.com.lowagie.text.DocumentException 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 4 with DocumentException

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

the class PdfCopyFieldsImp method closeIt.

protected void closeIt() throws DocumentException, IOException {
    for (int k = 0; k < readers.size(); ++k) {
        ((PdfReader) readers.get(k)).removeFields();
    }
    for (int r = 0; r < readers.size(); ++r) {
        PdfReader reader = (PdfReader) readers.get(r);
        for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
            pageRefs.add(getNewReference(reader.getPageOrigRef(page)));
            pageDics.add(reader.getPageN(page));
        }
    }
    mergeFields();
    createAcroForms();
    for (int r = 0; r < readers.size(); ++r) {
        PdfReader reader = (PdfReader) readers.get(r);
        for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
            PdfDictionary dic = reader.getPageN(page);
            PdfIndirectReference pageRef = getNewReference(reader.getPageOrigRef(page));
            PdfIndirectReference parent = getRoot().addPageRef(pageRef);
            dic.put(PdfName.PARENT, parent);
            propagate(dic, pageRef, false);
        }
    }
    for (Iterator it = readers2intrefs.keySet().iterator(); it.hasNext(); ) {
        PdfReader reader = (PdfReader) it.next();
        try {
            file = reader.getSafeFile();
            file.reOpen();
            IntHashtable t = (IntHashtable) readers2intrefs.get(reader);
            int[] keys = t.toOrderedKeys();
            for (int k = 0; k < keys.length; ++k) {
                PRIndirectReference ref = new PRIndirectReference(reader, keys[k]);
                addToBody(PdfReader.getPdfObjectRelease(ref), t.get(keys[k]));
            }
        } finally {
            try {
                file.close();
                reader.close();
            } catch (Exception e) {
            // empty on purpose
            }
        }
    }
    getPdfDocument().close();
}
Also used : Iterator(java.util.Iterator) IOException(java.io.IOException) DocumentException(pdftk.com.lowagie.text.DocumentException)

Example 5 with DocumentException

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

the class ColumnText method showTextAligned.

/**
 * Shows a line of text. Only the first line is written.
 * @param canvas where the text is to be written to
 * @param alignment the alignment. It is not influenced by the run direction
 * @param phrase the <CODE>Phrase</CODE> with the text
 * @param x the x reference position
 * @param y the y reference position
 * @param rotation the rotation to be applied in degrees counterclockwise
 * @param runDirection the run direction
 * @param arabicOptions the options for the arabic shaping
 */
public static void showTextAligned(PdfContentByte canvas, int alignment, Phrase phrase, float x, float y, float rotation, int runDirection, int arabicOptions) {
    if (alignment != Element.ALIGN_LEFT && alignment != Element.ALIGN_CENTER && alignment != Element.ALIGN_RIGHT)
        alignment = Element.ALIGN_LEFT;
    canvas.saveState();
    ColumnText ct = new ColumnText(canvas);
    if (rotation == 0) {
        if (alignment == Element.ALIGN_LEFT)
            ct.setSimpleColumn(phrase, x, y - 1, 20000 + x, y + 2, 2, alignment);
        else if (alignment == Element.ALIGN_RIGHT)
            ct.setSimpleColumn(phrase, x - 20000, y - 1, x, y + 2, 2, alignment);
        else
            ct.setSimpleColumn(phrase, x - 20000, y - 1, x + 20000, y + 2, 2, alignment);
    } else {
        double alpha = rotation * Math.PI / 180.0;
        float cos = (float) Math.cos(alpha);
        float sin = (float) Math.sin(alpha);
        canvas.concatCTM(cos, sin, -sin, cos, x, y);
        if (alignment == Element.ALIGN_LEFT)
            ct.setSimpleColumn(phrase, 0, -1, 20000, 2, 2, alignment);
        else if (alignment == Element.ALIGN_RIGHT)
            ct.setSimpleColumn(phrase, -20000, -1, 0, 2, 2, alignment);
        else
            ct.setSimpleColumn(phrase, -20000, -1, 20000, 2, 2, alignment);
    }
    if (runDirection == PdfWriter.RUN_DIRECTION_RTL) {
        if (alignment == Element.ALIGN_LEFT)
            alignment = Element.ALIGN_RIGHT;
        else if (alignment == Element.ALIGN_RIGHT)
            alignment = Element.ALIGN_LEFT;
    }
    ct.setAlignment(alignment);
    ct.setArabicOptions(arabicOptions);
    ct.setRunDirection(runDirection);
    try {
        ct.go();
    } catch (DocumentException e) {
        throw new ExceptionConverter(e);
    }
    canvas.restoreState();
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter) DocumentException(pdftk.com.lowagie.text.DocumentException)

Aggregations

DocumentException (pdftk.com.lowagie.text.DocumentException)33 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 ExceptionConverter (pdftk.com.lowagie.text.ExceptionConverter)5 Iterator (java.util.Iterator)4 Rectangle (pdftk.com.lowagie.text.Rectangle)3 EOFException (java.io.EOFException)2 ListItem (pdftk.com.lowagie.text.ListItem)2 Paragraph (pdftk.com.lowagie.text.Paragraph)2 Phrase (pdftk.com.lowagie.text.Phrase)2 Color (java.awt.Color)1 RandomAccessFile (java.io.RandomAccessFile)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Stack (java.util.Stack)1 StringTokenizer (java.util.StringTokenizer)1 Anchor (pdftk.com.lowagie.text.Anchor)1 Annotation (pdftk.com.lowagie.text.Annotation)1 Chunk (pdftk.com.lowagie.text.Chunk)1