Search in sources :

Example 21 with Element

use of com.lowagie.text.Element in project itext2 by albfernandez.

the class PdfDocument method add.

/**
 * 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).getName(), ((Meta) element).getContent());
                break;
            case Element.TITLE:
                info.addTitle(((Meta) element).getContent());
                break;
            case Element.SUBJECT:
                info.addSubject(((Meta) element).getContent());
                break;
            case Element.KEYWORDS:
                info.addKeywords(((Meta) element).getContent());
                break;
            case Element.AUTHOR:
                info.addAuthor(((Meta) element).getContent());
                break;
            case Element.CREATOR:
                info.addCreator(((Meta) element).getContent());
                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;
            // content (text)
            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, anchorAction);
                    // we try to add the chunk to the line, until we succeed
                    {
                        PdfChunk overflow;
                        while ((overflow = line.add(chunk)) != null) {
                            carriageReturn();
                            chunk = overflow;
                            chunk.trimFirstSpace();
                        }
                    }
                    pageEmpty = false;
                    if (chunk.isAttribute(Chunk.NEWPAGE)) {
                        newPage();
                    }
                    break;
                }
            case Element.ANCHOR:
                {
                    leadingCount++;
                    Anchor anchor = (Anchor) element;
                    String url = anchor.getReference();
                    leading = anchor.getLeading();
                    if (url != null) {
                        anchorAction = new PdfAction(url);
                    }
                    // we process the element
                    element.process(this);
                    anchorAction = null;
                    leadingCount--;
                    break;
                }
            case Element.ANNOTATION:
                {
                    if (line == null) {
                        carriageReturn();
                    }
                    Annotation annot = (Annotation) element;
                    Rectangle rect = new Rectangle(0, 0);
                    if (line != null)
                        rect = new Rectangle(annot.llx(indentRight() - line.widthLeft()), annot.lly(indentTop() - currentHeight), annot.urx(indentRight() - line.widthLeft() + 20), annot.ury(indentTop() - currentHeight - 20));
                    PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, rect);
                    annotationsImp.addPlainAnnotation(an);
                    pageEmpty = false;
                    break;
                }
            case Element.PHRASE:
                {
                    leadingCount++;
                    // we cast the element to a phrase and set the leading of the document
                    leading = ((Phrase) element).getLeading();
                    // we process the element
                    element.process(this);
                    leadingCount--;
                    break;
                }
            case Element.PARAGRAPH:
                {
                    leadingCount++;
                    // we cast the element to a paragraph
                    Paragraph paragraph = (Paragraph) element;
                    addSpacing(paragraph.getSpacingBefore(), leading, paragraph.getFont());
                    // we adjust the parameters of the document
                    alignment = paragraph.getAlignment();
                    leading = paragraph.getTotalLeading();
                    carriageReturn();
                    // we don't want to make orphans/widows
                    if (currentHeight + line.height() + leading > indentTop() - indentBottom()) {
                        newPage();
                    }
                    indentation.indentLeft += paragraph.getIndentationLeft();
                    indentation.indentRight += paragraph.getIndentationRight();
                    carriageReturn();
                    PdfPageEvent pageEvent = writer.getPageEvent();
                    if (pageEvent != null && !isSectionTitle)
                        pageEvent.onParagraph(writer, this, indentTop() - currentHeight);
                    // if a paragraph has to be kept together, we wrap it in a table object
                    if (paragraph.getKeepTogether()) {
                        carriageReturn();
                        PdfPTable table = new PdfPTable(1);
                        table.setWidthPercentage(100f);
                        PdfPCell cell = new PdfPCell();
                        cell.setBorder(Table.NO_BORDER);
                        cell.setPadding(0);
                        Iterator iterator = paragraph.iterator();
                        while (iterator.hasNext()) {
                            Object o = iterator.next();
                            if (o instanceof Element) {
                                cell.addElement((Element) o);
                            }
                        }
                        table.addCell(cell);
                        indentation.indentLeft -= paragraph.getIndentationLeft();
                        indentation.indentRight -= paragraph.getIndentationRight();
                        this.add(table);
                        indentation.indentLeft += paragraph.getIndentationLeft();
                        indentation.indentRight += paragraph.getIndentationRight();
                    } else {
                        line.setExtraIndent(paragraph.getFirstLineIndent());
                        element.process(this);
                        carriageReturn();
                        addSpacing(paragraph.getSpacingAfter(), paragraph.getTotalLeading(), paragraph.getFont());
                    }
                    if (pageEvent != null && !isSectionTitle)
                        pageEvent.onParagraphEnd(writer, this, indentTop() - currentHeight);
                    alignment = Element.ALIGN_LEFT;
                    indentation.indentLeft -= paragraph.getIndentationLeft();
                    indentation.indentRight -= paragraph.getIndentationRight();
                    carriageReturn();
                    leadingCount--;
                    break;
                }
            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;
                    PdfPageEvent pageEvent = writer.getPageEvent();
                    boolean hasTitle = section.isNotAddedYet() && section.getTitle() != null;
                    // if the section is a chapter, we begin a new page
                    if (section.isTriggerNewPage()) {
                        newPage();
                    }
                    if (hasTitle) {
                        float fith = indentTop() - currentHeight;
                        int rotation = pageSize.getRotation();
                        if (rotation == 90 || rotation == 180)
                            fith = pageSize.getHeight() - fith;
                        PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith);
                        while (currentOutline.level() >= section.getDepth()) {
                            currentOutline = currentOutline.parent();
                        }
                        PdfOutline outline = new PdfOutline(currentOutline, destination, section.getBookmarkTitle(), section.isBookmarkOpen());
                        currentOutline = outline;
                    }
                    // some values are set
                    carriageReturn();
                    indentation.sectionIndentLeft += section.getIndentationLeft();
                    indentation.sectionIndentRight += section.getIndentationRight();
                    if (section.isNotAddedYet() && pageEvent != null)
                        if (element.type() == Element.CHAPTER)
                            pageEvent.onChapter(writer, this, indentTop() - currentHeight, section.getTitle());
                        else
                            pageEvent.onSection(writer, this, indentTop() - currentHeight, section.getDepth(), section.getTitle());
                    // the title of the section (if any has to be printed)
                    if (hasTitle) {
                        isSectionTitle = true;
                        add(section.getTitle());
                        isSectionTitle = false;
                    }
                    indentation.sectionIndentLeft += section.getIndentation();
                    // we process the section
                    element.process(this);
                    flushLines();
                    // some parameters are set back to normal again
                    indentation.sectionIndentLeft -= (section.getIndentationLeft() + section.getIndentation());
                    indentation.sectionIndentRight -= section.getIndentationRight();
                    if (section.isComplete() && 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;
                    if (list.isAlignindent()) {
                        list.normalizeIndentation();
                    }
                    // we adjust the document
                    indentation.listIndentLeft += list.getIndentationLeft();
                    indentation.indentRight += list.getIndentationRight();
                    // we process the items in the list
                    element.process(this);
                    // some parameters are set back to normal again
                    indentation.listIndentLeft -= list.getIndentationLeft();
                    indentation.indentRight -= list.getIndentationRight();
                    carriageReturn();
                    break;
                }
            case Element.LISTITEM:
                {
                    leadingCount++;
                    // we cast the element to a ListItem
                    ListItem listItem = (ListItem) element;
                    addSpacing(listItem.getSpacingBefore(), leading, listItem.getFont());
                    // we adjust the document
                    alignment = listItem.getAlignment();
                    indentation.listIndentLeft += listItem.getIndentationLeft();
                    indentation.indentRight += listItem.getIndentationRight();
                    leading = listItem.getTotalLeading();
                    carriageReturn();
                    // we prepare the current line to be able to show us the listsymbol
                    line.setListItem(listItem);
                    // we process the item
                    element.process(this);
                    addSpacing(listItem.getSpacingAfter(), listItem.getTotalLeading(), listItem.getFont());
                    // 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();
                    indentation.listIndentLeft -= listItem.getIndentationLeft();
                    indentation.indentRight -= listItem.getIndentationRight();
                    leadingCount--;
                    break;
                }
            case Element.RECTANGLE:
                {
                    Rectangle rectangle = (Rectangle) element;
                    graphics.rectangle(rectangle);
                    pageEmpty = false;
                    break;
                }
            case Element.PTABLE:
                {
                    PdfPTable ptable = (PdfPTable) element;
                    if (ptable.size() <= ptable.getHeaderRows())
                        // nothing to do
                        break;
                    // before every table, we add a new line and flush all lines
                    ensureNewLine();
                    flushLines();
                    addPTable(ptable);
                    pageEmpty = false;
                    newLine();
                    break;
                }
            case Element.MULTI_COLUMN_TEXT:
                {
                    ensureNewLine();
                    flushLines();
                    MultiColumnText multiText = (MultiColumnText) element;
                    float height = multiText.write(writer.getDirectContent(), this, indentTop() - currentHeight);
                    currentHeight += height;
                    text.moveText(0, -1f * height);
                    pageEmpty = false;
                    break;
                }
            case Element.TABLE:
                {
                    if (element instanceof SimpleTable) {
                        PdfPTable ptable = ((SimpleTable) element).createPdfPTable();
                        if (ptable.size() <= ptable.getHeaderRows())
                            // nothing to do
                            break;
                        // 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())
                                // nothing to do
                                break;
                            // 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;
                            addPdfTable((Table) element);
                        }
                    } else {
                        return false;
                    }
                    break;
                }
            case Element.JPEG:
            case Element.JPEG2000:
            case Element.JBIG2:
            case Element.IMGRAW:
            case Element.IMGTEMPLATE:
                {
                    // carriageReturn(); suggestion by Marc Campforts
                    add((Image) element);
                    break;
                }
            case Element.YMARK:
                {
                    DrawInterface zh = (DrawInterface) element;
                    zh.draw(graphics, indentLeft(), indentBottom(), indentRight(), indentTop(), indentTop() - currentHeight - (leadingCount > 0 ? leading : 0));
                    pageEmpty = false;
                    break;
                }
            case Element.MARKED:
                {
                    MarkedObject mo;
                    if (element instanceof MarkedSection) {
                        mo = ((MarkedSection) element).getTitle();
                        if (mo != null) {
                            mo.process(this);
                        }
                    }
                    mo = (MarkedObject) element;
                    mo.process(this);
                    break;
                }
            default:
                return false;
        }
        lastElementType = element.type();
        return true;
    } catch (Exception e) {
        throw new DocumentException(e);
    }
}
Also used : Element(com.lowagie.text.Element) Rectangle(com.lowagie.text.Rectangle) Image(com.lowagie.text.Image) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(com.lowagie.text.List) Table(com.lowagie.text.Table) SimpleTable(com.lowagie.text.SimpleTable) BadElementException(com.lowagie.text.BadElementException) MarkedSection(com.lowagie.text.MarkedSection) SimpleTable(com.lowagie.text.SimpleTable) DrawInterface(com.lowagie.text.pdf.draw.DrawInterface) Phrase(com.lowagie.text.Phrase) Chunk(com.lowagie.text.Chunk) MarkedSection(com.lowagie.text.MarkedSection) Section(com.lowagie.text.Section) Annotation(com.lowagie.text.Annotation) BadElementException(com.lowagie.text.BadElementException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) Paragraph(com.lowagie.text.Paragraph) Anchor(com.lowagie.text.Anchor) MarkedObject(com.lowagie.text.MarkedObject) ListItem(com.lowagie.text.ListItem) MarkedObject(com.lowagie.text.MarkedObject)

Example 22 with Element

use of com.lowagie.text.Element in project itext2 by albfernandez.

the class SAXiTextHandler method handleEndingTags.

/**
 * This method deals with the starting tags.
 *
 * @param name
 *            the name of the tag
 */
public void handleEndingTags(String name) {
    if (ElementTags.IGNORE.equals(name)) {
        ignore = false;
        return;
    }
    if (ignore)
        return;
    // tags that don't have any content
    if (isNewpage(name) || ElementTags.ANNOTATION.equals(name) || ElementTags.IMAGE.equals(name) || isNewline(name)) {
        return;
    }
    try {
        // titles of sections and chapters
        if (ElementTags.TITLE.equals(name)) {
            Paragraph current = (Paragraph) stack.pop();
            if (currentChunk != null) {
                current.add(currentChunk);
                currentChunk = null;
            }
            Section previous = (Section) stack.pop();
            previous.setTitle(current);
            stack.push(previous);
            return;
        }
        // all other endtags
        if (currentChunk != null) {
            TextElementArray current;
            try {
                current = (TextElementArray) stack.pop();
            } catch (EmptyStackException ese) {
                current = new Paragraph();
            }
            current.add(currentChunk);
            stack.push(current);
            currentChunk = null;
        }
        // chunks
        if (ElementTags.CHUNK.equals(name)) {
            return;
        }
        // phrases, anchors, lists, tables
        if (ElementTags.PHRASE.equals(name) || ElementTags.ANCHOR.equals(name) || ElementTags.LIST.equals(name) || ElementTags.PARAGRAPH.equals(name)) {
            Element current = (Element) stack.pop();
            try {
                TextElementArray previous = (TextElementArray) stack.pop();
                previous.add(current);
                stack.push(previous);
            } catch (EmptyStackException ese) {
                document.add(current);
            }
            return;
        }
        // listitems
        if (ElementTags.LISTITEM.equals(name)) {
            ListItem listItem = (ListItem) stack.pop();
            List list = (List) stack.pop();
            list.add(listItem);
            stack.push(list);
        }
        // tables
        if (ElementTags.TABLE.equals(name)) {
            Table table = (Table) stack.pop();
            try {
                TextElementArray previous = (TextElementArray) stack.pop();
                previous.add(table);
                stack.push(previous);
            } catch (EmptyStackException ese) {
                document.add(table);
            }
            return;
        }
        // rows
        if (ElementTags.ROW.equals(name)) {
            ArrayList cells = new ArrayList();
            int columns = 0;
            Table table;
            Cell cell;
            while (true) {
                Element element = (Element) stack.pop();
                if (element.type() == Element.CELL) {
                    cell = (Cell) element;
                    columns += cell.getColspan();
                    cells.add(cell);
                } else {
                    table = (Table) element;
                    break;
                }
            }
            if (table.getColumns() < columns) {
                table.addColumns(columns - table.getColumns());
            }
            Collections.reverse(cells);
            String width;
            float[] cellWidths = new float[columns];
            boolean[] cellNulls = new boolean[columns];
            for (int i = 0; i < columns; i++) {
                cellWidths[i] = 0;
                cellNulls[i] = true;
            }
            float total = 0;
            int j = 0;
            for (Iterator i = cells.iterator(); i.hasNext(); ) {
                cell = (Cell) i.next();
                width = cell.getWidthAsString();
                if (cell.getWidth() == 0) {
                    if (cell.getColspan() == 1 && cellWidths[j] == 0) {
                        try {
                            cellWidths[j] = 100f / columns;
                            total += cellWidths[j];
                        } catch (Exception e) {
                        // empty on purpose
                        }
                    } else if (cell.getColspan() == 1) {
                        cellNulls[j] = false;
                    }
                } else if (cell.getColspan() == 1 && width.endsWith("%")) {
                    try {
                        cellWidths[j] = Float.parseFloat(width.substring(0, width.length() - 1) + "f");
                        total += cellWidths[j];
                    } catch (Exception e) {
                    // empty on purpose
                    }
                }
                j += cell.getColspan();
                table.addCell(cell);
            }
            float[] widths = table.getProportionalWidths();
            if (widths.length == columns) {
                float left = 0.0f;
                for (int i = 0; i < columns; i++) {
                    if (cellNulls[i] && widths[i] != 0) {
                        left += widths[i];
                        cellWidths[i] = widths[i];
                    }
                }
                if (100.0 >= total) {
                    for (int i = 0; i < widths.length; i++) {
                        if (cellWidths[i] == 0 && widths[i] != 0) {
                            cellWidths[i] = (widths[i] / left) * (100.0f - total);
                        }
                    }
                }
                table.setWidths(cellWidths);
            }
            stack.push(table);
        }
        // cells
        if (ElementTags.CELL.equals(name)) {
            return;
        }
        // sections
        if (ElementTags.SECTION.equals(name)) {
            stack.pop();
            return;
        }
        // chapters
        if (ElementTags.CHAPTER.equals(name)) {
            document.add((Element) stack.pop());
            return;
        }
        // the documentroot
        if (isDocumentRoot(name)) {
            try {
                while (true) {
                    Element element = (Element) stack.pop();
                    try {
                        TextElementArray previous = (TextElementArray) stack.pop();
                        previous.add(element);
                        stack.push(previous);
                    } catch (EmptyStackException es) {
                        document.add(element);
                    }
                }
            } catch (EmptyStackException ese) {
            // empty on purpose
            }
            if (controlOpenClose)
                document.close();
            return;
        }
    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    }
}
Also used : Table(com.lowagie.text.Table) Element(com.lowagie.text.Element) ArrayList(java.util.ArrayList) Section(com.lowagie.text.Section) BadElementException(com.lowagie.text.BadElementException) EmptyStackException(java.util.EmptyStackException) DocumentException(com.lowagie.text.DocumentException) Paragraph(com.lowagie.text.Paragraph) EmptyStackException(java.util.EmptyStackException) ExceptionConverter(com.lowagie.text.ExceptionConverter) TextElementArray(com.lowagie.text.TextElementArray) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(com.lowagie.text.List) ListItem(com.lowagie.text.ListItem) Cell(com.lowagie.text.Cell)

Example 23 with Element

use of com.lowagie.text.Element in project itext2 by albfernandez.

the class SAXiTextHandler method handleStartingTags.

/**
 * This method deals with the starting tags.
 *
 * @param name
 *            the name of the tag
 * @param attributes
 *            the list of attributes
 */
public void handleStartingTags(String name, Properties attributes) {
    // System.err.println("Start: " + name);
    if (ignore || ElementTags.IGNORE.equals(name)) {
        ignore = true;
        return;
    }
    // maybe there is some meaningful data that wasn't between tags
    if (currentChunk != null) {
        TextElementArray current;
        try {
            current = (TextElementArray) stack.pop();
        } catch (EmptyStackException ese) {
            if (bf == null) {
                current = new Paragraph("", new Font());
            } else {
                current = new Paragraph("", new Font(this.bf));
            }
        }
        current.add(currentChunk);
        stack.push(current);
        currentChunk = null;
    }
    // chunks
    if (ElementTags.CHUNK.equals(name)) {
        currentChunk = ElementFactory.getChunk(attributes);
        if (bf != null) {
            currentChunk.setFont(new Font(this.bf));
        }
        return;
    }
    // symbols
    if (ElementTags.ENTITY.equals(name)) {
        Font f = new Font();
        if (currentChunk != null) {
            handleEndingTags(ElementTags.CHUNK);
            f = currentChunk.getFont();
        }
        currentChunk = EntitiesToSymbol.get(attributes.getProperty(ElementTags.ID), f);
        return;
    }
    // phrases
    if (ElementTags.PHRASE.equals(name)) {
        stack.push(ElementFactory.getPhrase(attributes));
        return;
    }
    // anchors
    if (ElementTags.ANCHOR.equals(name)) {
        stack.push(ElementFactory.getAnchor(attributes));
        return;
    }
    // paragraphs and titles
    if (ElementTags.PARAGRAPH.equals(name) || ElementTags.TITLE.equals(name)) {
        stack.push(ElementFactory.getParagraph(attributes));
        return;
    }
    // lists
    if (ElementTags.LIST.equals(name)) {
        stack.push(ElementFactory.getList(attributes));
        return;
    }
    // listitems
    if (ElementTags.LISTITEM.equals(name)) {
        stack.push(ElementFactory.getListItem(attributes));
        return;
    }
    // cells
    if (ElementTags.CELL.equals(name)) {
        stack.push(ElementFactory.getCell(attributes));
        return;
    }
    // tables
    if (ElementTags.TABLE.equals(name)) {
        Table table = ElementFactory.getTable(attributes);
        float[] widths = table.getProportionalWidths();
        for (int i = 0; i < widths.length; i++) {
            if (widths[i] == 0) {
                widths[i] = 100.0f / widths.length;
            }
        }
        try {
            table.setWidths(widths);
        } catch (BadElementException bee) {
            // this shouldn't happen
            throw new ExceptionConverter(bee);
        }
        stack.push(table);
        return;
    }
    // sections
    if (ElementTags.SECTION.equals(name)) {
        Element previous = (Element) stack.pop();
        Section section;
        try {
            section = ElementFactory.getSection((Section) previous, attributes);
        } catch (ClassCastException cce) {
            throw new ExceptionConverter(cce);
        }
        stack.push(previous);
        stack.push(section);
        return;
    }
    // chapters
    if (ElementTags.CHAPTER.equals(name)) {
        stack.push(ElementFactory.getChapter(attributes));
        return;
    }
    // images
    if (ElementTags.IMAGE.equals(name)) {
        try {
            Image img = ElementFactory.getImage(attributes);
            try {
                addImage(img);
                return;
            } catch (EmptyStackException ese) {
                // to the document
                try {
                    document.add(img);
                } catch (DocumentException de) {
                    throw new ExceptionConverter(de);
                }
                return;
            }
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
    // annotations
    if (ElementTags.ANNOTATION.equals(name)) {
        Annotation annotation = ElementFactory.getAnnotation(attributes);
        TextElementArray current;
        try {
            try {
                current = (TextElementArray) stack.pop();
                try {
                    current.add(annotation);
                } catch (Exception e) {
                    document.add(annotation);
                }
                stack.push(current);
            } catch (EmptyStackException ese) {
                document.add(annotation);
            }
            return;
        } catch (DocumentException de) {
            throw new ExceptionConverter(de);
        }
    }
    // newlines
    if (isNewline(name)) {
        TextElementArray current;
        try {
            current = (TextElementArray) stack.pop();
            current.add(Chunk.NEWLINE);
            stack.push(current);
        } catch (EmptyStackException ese) {
            if (currentChunk == null) {
                try {
                    document.add(Chunk.NEWLINE);
                } catch (DocumentException de) {
                    throw new ExceptionConverter(de);
                }
            } else {
                currentChunk.append("\n");
            }
        }
        return;
    }
    // newpage
    if (isNewpage(name)) {
        TextElementArray current;
        try {
            current = (TextElementArray) stack.pop();
            Chunk newPage = new Chunk("");
            newPage.setNewPage();
            if (bf != null) {
                newPage.setFont(new Font(this.bf));
            }
            current.add(newPage);
            stack.push(current);
        } catch (EmptyStackException ese) {
            document.newPage();
        }
        return;
    }
    if (ElementTags.HORIZONTALRULE.equals(name)) {
        TextElementArray current;
        LineSeparator hr = new LineSeparator(1.0f, 100.0f, null, Element.ALIGN_CENTER, 0);
        try {
            current = (TextElementArray) stack.pop();
            current.add(hr);
            stack.push(current);
        } catch (EmptyStackException ese) {
            try {
                document.add(hr);
            } catch (DocumentException de) {
                throw new ExceptionConverter(de);
            }
        }
        return;
    }
    // documentroot
    if (isDocumentRoot(name)) {
        String key;
        String value;
        // pagesize and orientation specific code suggested by Samuel Gabriel
        // Updated by Ricardo Coutinho. Only use if set in html!
        Rectangle pageSize = null;
        String orientation = null;
        for (Iterator i = attributes.keySet().iterator(); i.hasNext(); ) {
            key = (String) i.next();
            value = attributes.getProperty(key);
            try {
                // margin specific code suggested by Reza Nasiri
                if (ElementTags.LEFT.equalsIgnoreCase(key))
                    leftMargin = Float.parseFloat(value + "f");
                if (ElementTags.RIGHT.equalsIgnoreCase(key))
                    rightMargin = Float.parseFloat(value + "f");
                if (ElementTags.TOP.equalsIgnoreCase(key))
                    topMargin = Float.parseFloat(value + "f");
                if (ElementTags.BOTTOM.equalsIgnoreCase(key))
                    bottomMargin = Float.parseFloat(value + "f");
            } catch (Exception ex) {
                throw new ExceptionConverter(ex);
            }
            if (ElementTags.PAGE_SIZE.equals(key)) {
                try {
                    String pageSizeName = value;
                    Field pageSizeField = PageSize.class.getField(pageSizeName);
                    pageSize = (Rectangle) pageSizeField.get(null);
                } catch (Exception ex) {
                    throw new ExceptionConverter(ex);
                }
            } else if (ElementTags.ORIENTATION.equals(key)) {
                try {
                    if ("landscape".equals(value)) {
                        orientation = "landscape";
                    }
                } catch (Exception ex) {
                    throw new ExceptionConverter(ex);
                }
            } else {
                try {
                    document.add(new Meta(key, value));
                } catch (DocumentException de) {
                    throw new ExceptionConverter(de);
                }
            }
        }
        if (pageSize != null) {
            if ("landscape".equals(orientation)) {
                pageSize = pageSize.rotate();
            }
            document.setPageSize(pageSize);
        }
        document.setMargins(leftMargin, rightMargin, topMargin, bottomMargin);
        if (controlOpenClose)
            document.open();
    }
}
Also used : Meta(com.lowagie.text.Meta) Table(com.lowagie.text.Table) BadElementException(com.lowagie.text.BadElementException) Element(com.lowagie.text.Element) Rectangle(com.lowagie.text.Rectangle) Image(com.lowagie.text.Image) Chunk(com.lowagie.text.Chunk) Section(com.lowagie.text.Section) LineSeparator(com.lowagie.text.pdf.draw.LineSeparator) BaseFont(com.lowagie.text.pdf.BaseFont) Font(com.lowagie.text.Font) BadElementException(com.lowagie.text.BadElementException) EmptyStackException(java.util.EmptyStackException) DocumentException(com.lowagie.text.DocumentException) Annotation(com.lowagie.text.Annotation) Paragraph(com.lowagie.text.Paragraph) EmptyStackException(java.util.EmptyStackException) ExceptionConverter(com.lowagie.text.ExceptionConverter) Field(java.lang.reflect.Field) TextElementArray(com.lowagie.text.TextElementArray) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator)

Example 24 with Element

use of com.lowagie.text.Element in project itext2 by albfernandez.

the class RtfCell method importCell.

/**
 * Imports the Cell properties into the RtfCell
 *
 * @param cell The PdfPCell to import
 * @since 2.1.3
 */
private void importCell(PdfPCell cell) {
    this.content = new ArrayList();
    if (cell == null) {
        this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, this.parentRow.getParentTable().getBorders());
        return;
    }
    // padding
    this.cellPadding = (int) this.parentRow.getParentTable().getCellPadding();
    this.cellPaddingBottom = cell.getPaddingBottom();
    this.cellPaddingTop = cell.getPaddingTop();
    this.cellPaddingRight = cell.getPaddingRight();
    this.cellPaddingLeft = cell.getPaddingLeft();
    // BORDERS
    this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, cell.getBorder(), cell.getBorderWidth(), cell.getBorderColor());
    // border colors
    this.border = cell.getBorder();
    this.borderColor = cell.getBorderColor();
    this.borderColorBottom = cell.getBorderColorBottom();
    this.borderColorTop = cell.getBorderColorTop();
    this.borderColorLeft = cell.getBorderColorLeft();
    this.borderColorRight = cell.getBorderColorRight();
    // border widths
    this.borderWidth = cell.getBorderWidth();
    this.borderWidthBottom = cell.getBorderWidthBottom();
    this.borderWidthTop = cell.getBorderWidthTop();
    this.borderWidthLeft = cell.getBorderWidthLeft();
    this.borderWidthRight = cell.getBorderWidthRight();
    this.colspan = cell.getColspan();
    // cell.getRowspan();
    this.rowspan = 1;
    // if(cell.getRowspan() > 1) {
    // this.mergeType = MERGE_VERT_PARENT;
    // }
    this.verticalAlignment = cell.getVerticalAlignment();
    if (cell.getBackgroundColor() == null) {
        this.backgroundColor = new RtfColor(this.document, 255, 255, 255);
    } else {
        this.backgroundColor = new RtfColor(this.document, cell.getBackgroundColor());
    }
    // does it have column composite info?
    java.util.List compositeElements = cell.getCompositeElements();
    if (compositeElements != null) {
        Iterator cellIterator = compositeElements.iterator();
        // does it have column info?
        Paragraph container = null;
        while (cellIterator.hasNext()) {
            try {
                Element element = (Element) cellIterator.next();
                // should we wrap it in a paragraph
                if (!(element instanceof Paragraph) && !(element instanceof List)) {
                    if (container != null) {
                        container.add(element);
                    } else {
                        container = new Paragraph();
                        container.setAlignment(cell.getHorizontalAlignment());
                        container.add(element);
                    }
                } else {
                    if (container != null) {
                        RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
                        for (int i = 0; i < rtfElements.length; i++) {
                            rtfElements[i].setInTable(true);
                            this.content.add(rtfElements[i]);
                        }
                        container = null;
                    }
                    // with that of enclosing cell
                    if (element instanceof Paragraph && ((Paragraph) element).getAlignment() == Element.ALIGN_UNDEFINED) {
                        ((Paragraph) element).setAlignment(cell.getHorizontalAlignment());
                    }
                    RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(element);
                    for (int i = 0; i < rtfElements.length; i++) {
                        rtfElements[i].setInTable(true);
                        this.content.add(rtfElements[i]);
                    }
                }
            } catch (DocumentException de) {
                de.printStackTrace();
            }
        }
        if (container != null) {
            try {
                RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
                for (int i = 0; i < rtfElements.length; i++) {
                    rtfElements[i].setInTable(true);
                    this.content.add(rtfElements[i]);
                }
            } catch (DocumentException de) {
                de.printStackTrace();
            }
        }
    }
    // does it have image info?
    Image img = cell.getImage();
    if (img != null) {
        try {
            RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(img);
            for (int i = 0; i < rtfElements.length; i++) {
                rtfElements[i].setInTable(true);
                this.content.add(rtfElements[i]);
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // does it have phrase info?
    Phrase phrase = cell.getPhrase();
    if (phrase != null) {
        try {
            RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(phrase);
            for (int i = 0; i < rtfElements.length; i++) {
                rtfElements[i].setInTable(true);
                this.content.add(rtfElements[i]);
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // does it have table info?
    PdfPTable table = cell.getTable();
    if (table != null) {
        this.add(table);
    // try {
    // RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(table);
    // for (int i = 0; i < rtfElements.length; i++) {
    // rtfElements[i].setInTable(true);
    // this.content.add(rtfElements[i]);
    // }
    // } catch (DocumentException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    }
}
Also used : Element(com.lowagie.text.Element) RtfBasicElement(com.lowagie.text.rtf.RtfBasicElement) RtfExtendedElement(com.lowagie.text.rtf.RtfExtendedElement) ArrayList(java.util.ArrayList) Phrase(com.lowagie.text.Phrase) Image(com.lowagie.text.Image) Paragraph(com.lowagie.text.Paragraph) RtfParagraph(com.lowagie.text.rtf.text.RtfParagraph) PdfPTable(com.lowagie.text.pdf.PdfPTable) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator) RtfColor(com.lowagie.text.rtf.style.RtfColor) ArrayList(java.util.ArrayList) List(com.lowagie.text.List) RtfBasicElement(com.lowagie.text.rtf.RtfBasicElement)

Aggregations

Element (com.lowagie.text.Element)24 DocumentException (com.lowagie.text.DocumentException)13 Paragraph (com.lowagie.text.Paragraph)13 ArrayList (java.util.ArrayList)12 Chunk (com.lowagie.text.Chunk)9 ListItem (com.lowagie.text.ListItem)9 List (com.lowagie.text.List)8 ExceptionConverter (com.lowagie.text.ExceptionConverter)7 Phrase (com.lowagie.text.Phrase)7 TextElementArray (com.lowagie.text.TextElementArray)7 Section (com.lowagie.text.Section)6 IOException (java.io.IOException)6 Iterator (java.util.Iterator)6 BadElementException (com.lowagie.text.BadElementException)5 Table (com.lowagie.text.Table)5 Annotation (com.lowagie.text.Annotation)4 Image (com.lowagie.text.Image)4 EmptyStackException (java.util.EmptyStackException)4 Cell (com.lowagie.text.Cell)3 Font (com.lowagie.text.Font)3