Search in sources :

Example 11 with Annotation

use of com.lowagie.text.Annotation in project OpenPDF by LibrePDF.

the class SimpleAnnotations method main.

/**
 * Creates documents with some simple annotations.
 *
 * @param args
 *            no arguments needed
 */
public static void main(String[] args) {
    System.out.println("Simple Annotations");
    // step 1: creation of a document-object
    Document document1 = new Document(PageSize.A4, 10, 10, 10, 10);
    Document document2 = new Document(PageSize.A4, 10, 10, 10, 10);
    try {
        // step 2:
        PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream("SimpleAnnotations1.pdf"));
        PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream("SimpleAnnotations2.pdf"));
        // step 3:
        writer2.setPdfVersion(PdfWriter.VERSION_1_5);
        document1.open();
        document2.open();
        // step 4:
        document1.add(new Paragraph("Each square on this page represents an annotation."));
        // document1
        PdfContentByte cb1 = writer1.getDirectContent();
        Annotation a1 = new Annotation("authors", "Maybe it's because I wanted to be an author myself that I wrote iText.", 250f, 700f, 350f, 800f);
        document1.add(a1);
        Annotation a2 = new Annotation(250f, 550f, 350f, 650f, new URL("https://github.com/LibrePDF/OpenPDF"));
        document1.add(a2);
        Annotation a3 = new Annotation(250f, 400f, 350f, 500f, "http://www.lowagie.com/iText");
        document1.add(a3);
        Image image = Image.getInstance("iText.gif");
        image.setAnnotation(a3);
        document1.add(image);
        Annotation a4 = new Annotation(250f, 250f, 350f, 350f, PdfAction.LASTPAGE);
        document1.add(a4);
        // draw rectangles to show where the annotations were added
        cb1.rectangle(250, 700, 100, 100);
        cb1.rectangle(250, 550, 100, 100);
        cb1.rectangle(250, 400, 100, 100);
        cb1.rectangle(250, 250, 100, 100);
        cb1.stroke();
        // more content
        document1.newPage();
        for (int i = 0; i < 5; i++) {
            document1.add(new Paragraph("blahblahblah"));
        }
        document1.add(new Annotation("blahblah", "Adding an annotation without specifying coordinates"));
        for (int i = 0; i < 3; i++) {
            document1.add(new Paragraph("blahblahblah"));
        }
        document1.newPage();
        document1.add(new Chunk("marked chunk").setLocalDestination("mark"));
        // document2
        document2.add(new Paragraph("Each square on this page represents an annotation."));
        PdfContentByte cb2 = writer2.getDirectContent();
        Annotation a5 = new Annotation(100f, 700f, 200f, 800f, "cards.mpg", "video/mpeg", true);
        document2.add(a5);
        Annotation a6 = new Annotation(100f, 550f, 200f, 650f, "SimpleAnnotations1.pdf", "mark");
        document2.add(a6);
        Annotation a7 = new Annotation(100f, 400f, 200f, 500f, "SimpleAnnotations1.pdf", 2);
        document2.add(a7);
        Annotation a8 = new Annotation(100f, 250f, 200f, 350f, "C://windows/notepad.exe", null, null, null);
        document2.add(a8);
        // draw rectangles to show where the annotations were added
        cb2.rectangle(100, 700, 100, 100);
        cb2.rectangle(100, 550, 100, 100);
        cb2.rectangle(100, 400, 100, 100);
        cb2.rectangle(100, 250, 100, 100);
        cb2.stroke();
    } catch (Exception de) {
        de.printStackTrace();
    }
    // step 5: we close the document
    document1.close();
    document2.close();
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) FileOutputStream(java.io.FileOutputStream) PdfContentByte(com.lowagie.text.pdf.PdfContentByte) Document(com.lowagie.text.Document) Image(com.lowagie.text.Image) Chunk(com.lowagie.text.Chunk) Annotation(com.lowagie.text.Annotation) URL(java.net.URL) Paragraph(com.lowagie.text.Paragraph)

Example 12 with Annotation

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

the class PdfContentByte method addImage.

/**
 * Adds an <CODE>Image</CODE> to the page. The positioning of the <CODE>Image</CODE>
 * is done with the transformation matrix. To position an <CODE>image</CODE> at (x,y)
 * use addImage(image, image_width, 0, 0, image_height, x, y). The image can be placed inline.
 * @param image the <CODE>Image</CODE> object
 * @param a an element of the transformation matrix
 * @param b an element of the transformation matrix
 * @param c an element of the transformation matrix
 * @param d an element of the transformation matrix
 * @param e an element of the transformation matrix
 * @param f an element of the transformation matrix
 * @param inlineImage <CODE>true</CODE> to place this image inline, <CODE>false</CODE> otherwise
 * @throws DocumentException on error
 */
public void addImage(Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage) throws DocumentException {
    try {
        if (image.getLayer() != null)
            beginLayer(image.getLayer());
        if (image.isImgTemplate()) {
            writer.addDirectImageSimple(image);
            PdfTemplate template = image.getTemplateData();
            float w = template.getWidth();
            float h = template.getHeight();
            addTemplate(template, a / w, b / w, c / h, d / h, e, f);
        } else {
            content.append("q ");
            content.append(a).append(' ');
            content.append(b).append(' ');
            content.append(c).append(' ');
            content.append(d).append(' ');
            content.append(e).append(' ');
            content.append(f).append(" cm");
            if (inlineImage) {
                content.append("\nBI\n");
                PdfImage pimage = new PdfImage(image, "", null);
                if (image instanceof ImgJBIG2) {
                    byte[] globals = ((ImgJBIG2) image).getGlobalBytes();
                    if (globals != null) {
                        PdfDictionary decodeparms = new PdfDictionary();
                        decodeparms.put(PdfName.JBIG2GLOBALS, writer.getReferenceJBIG2Globals(globals));
                        pimage.put(PdfName.DECODEPARMS, decodeparms);
                    }
                }
                for (Iterator it = pimage.getKeys().iterator(); it.hasNext(); ) {
                    PdfName key = (PdfName) it.next();
                    PdfObject value = pimage.get(key);
                    String s = (String) abrev.get(key);
                    if (s == null)
                        continue;
                    content.append(s);
                    boolean check = true;
                    if (key.equals(PdfName.COLORSPACE) && value.isArray()) {
                        PdfArray ar = (PdfArray) value;
                        if (ar.size() == 4 && PdfName.INDEXED.equals(ar.getAsName(0)) && ar.getPdfObject(1).isName() && ar.getPdfObject(2).isNumber() && ar.getPdfObject(3).isString()) {
                            check = false;
                        }
                    }
                    if (check && key.equals(PdfName.COLORSPACE) && !value.isName()) {
                        PdfName cs = writer.getColorspaceName();
                        PageResources prs = getPageResources();
                        prs.addColor(cs, writer.addToBody(value).getIndirectReference());
                        value = cs;
                    }
                    value.toPdf(null, content);
                    content.append('\n');
                }
                content.append("ID\n");
                pimage.writeContent(content);
                content.append("\nEI\nQ").append_i(separator);
            } else {
                PdfName name;
                PageResources prs = getPageResources();
                Image maskImage = image.getImageMask();
                if (maskImage != null) {
                    name = writer.addDirectImageSimple(maskImage);
                    prs.addXObject(name, writer.getImageReference(name));
                }
                name = writer.addDirectImageSimple(image);
                name = prs.addXObject(name, writer.getImageReference(name));
                content.append(' ').append(name.getBytes()).append(" Do Q").append_i(separator);
            }
        }
        if (image.hasBorders()) {
            saveState();
            float w = image.getWidth();
            float h = image.getHeight();
            concatCTM(a / w, b / w, c / h, d / h, e, f);
            rectangle(image);
            restoreState();
        }
        if (image.getLayer() != null)
            endLayer();
        Annotation annot = image.getAnnotation();
        if (annot == null)
            return;
        float[] r = new float[unitRect.length];
        for (int k = 0; k < unitRect.length; k += 2) {
            r[k] = a * unitRect[k] + c * unitRect[k + 1] + e;
            r[k + 1] = b * unitRect[k] + d * unitRect[k + 1] + f;
        }
        float llx = r[0];
        float lly = r[1];
        float urx = llx;
        float ury = lly;
        for (int k = 2; k < r.length; k += 2) {
            llx = Math.min(llx, r[k]);
            lly = Math.min(lly, r[k + 1]);
            urx = Math.max(urx, r[k]);
            ury = Math.max(ury, r[k + 1]);
        }
        annot = new Annotation(annot);
        annot.setDimensions(llx, lly, urx, ury);
        PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, new Rectangle(llx, lly, urx, ury));
        if (an == null)
            return;
        addAnnotation(an);
    } catch (Exception ee) {
        throw new DocumentException(ee);
    }
}
Also used : Rectangle(com.lowagie.text.Rectangle) ImgJBIG2(com.lowagie.text.ImgJBIG2) Image(com.lowagie.text.Image) Annotation(com.lowagie.text.Annotation) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) IllegalPdfSyntaxException(com.lowagie.text.exceptions.IllegalPdfSyntaxException) DocumentException(com.lowagie.text.DocumentException) Iterator(java.util.Iterator)

Example 13 with Annotation

use of com.lowagie.text.Annotation 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 14 with Annotation

use of com.lowagie.text.Annotation 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 15 with Annotation

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

the class RtfMapper method mapElement.

/**
 * Takes an Element subclass and returns an array of RtfBasicElement
 * subclasses, that contained the mapped RTF equivalent to the Element
 * passed in.
 *
 * @param element The Element to wrap
 * @return An array of RtfBasicElement wrapping the Element
 * @throws DocumentException
 */
public RtfBasicElement[] mapElement(Element element) throws DocumentException {
    ArrayList rtfElements = new ArrayList();
    if (element instanceof RtfBasicElement) {
        RtfBasicElement rtfElement = (RtfBasicElement) element;
        rtfElement.setRtfDocument(this.rtfDoc);
        return new RtfBasicElement[] { rtfElement };
    }
    switch(element.type()) {
        case Element.CHUNK:
            Chunk chunk = (Chunk) element;
            if (chunk.hasAttributes()) {
                if (chunk.getAttributes().containsKey(Chunk.IMAGE)) {
                    rtfElements.add(new RtfImage(rtfDoc, chunk.getImage()));
                } else if (chunk.getAttributes().containsKey(Chunk.NEWPAGE)) {
                    rtfElements.add(new RtfNewPage(rtfDoc));
                } else if (chunk.getAttributes().containsKey(Chunk.TAB)) {
                    Float tabPos = (Float) ((Object[]) chunk.getAttributes().get(Chunk.TAB))[1];
                    RtfTab tab = new RtfTab(tabPos.floatValue(), RtfTab.TAB_LEFT_ALIGN);
                    tab.setRtfDocument(rtfDoc);
                    rtfElements.add(tab);
                    rtfElements.add(new RtfChunk(rtfDoc, new Chunk("\t")));
                } else {
                    rtfElements.add(new RtfChunk(rtfDoc, (Chunk) element));
                }
            } else {
                rtfElements.add(new RtfChunk(rtfDoc, (Chunk) element));
            }
            break;
        case Element.PHRASE:
            rtfElements.add(new RtfPhrase(rtfDoc, (Phrase) element));
            break;
        case Element.PARAGRAPH:
            rtfElements.add(new RtfParagraph(rtfDoc, (Paragraph) element));
            break;
        case Element.ANCHOR:
            rtfElements.add(new RtfAnchor(rtfDoc, (Anchor) element));
            break;
        case Element.ANNOTATION:
            rtfElements.add(new RtfAnnotation(rtfDoc, (Annotation) element));
            break;
        case Element.IMGRAW:
        case Element.IMGTEMPLATE:
        case Element.JPEG:
            rtfElements.add(new RtfImage(rtfDoc, (Image) element));
            break;
        case Element.AUTHOR:
        case Element.SUBJECT:
        case Element.KEYWORDS:
        case Element.TITLE:
        case Element.PRODUCER:
        case Element.CREATIONDATE:
            rtfElements.add(new RtfInfoElement(rtfDoc, (Meta) element));
            break;
        case Element.LIST:
            // TODO: Testing
            rtfElements.add(new RtfList(rtfDoc, (List) element));
            break;
        case Element.LISTITEM:
            // TODO: Testing
            rtfElements.add(new RtfListItem(rtfDoc, (ListItem) element));
            break;
        case Element.SECTION:
            rtfElements.add(new RtfSection(rtfDoc, (Section) element));
            break;
        case Element.CHAPTER:
            rtfElements.add(new RtfChapter(rtfDoc, (Chapter) element));
            break;
        case Element.TABLE:
            try {
                rtfElements.add(new RtfTable(rtfDoc, (Table) element));
            } catch (ClassCastException e) {
                rtfElements.add(new RtfTable(rtfDoc, ((SimpleTable) element).createTable()));
            }
            break;
        case Element.PTABLE:
            try {
                rtfElements.add(new RtfTable(rtfDoc, (PdfPTable) element));
            } catch (ClassCastException e) {
                rtfElements.add(new RtfTable(rtfDoc, ((SimpleTable) element).createTable()));
            }
            break;
    }
    return (RtfBasicElement[]) rtfElements.toArray(new RtfBasicElement[rtfElements.size()]);
}
Also used : Meta(com.lowagie.text.Meta) ArrayList(java.util.ArrayList) RtfImage(com.lowagie.text.rtf.graphic.RtfImage) Image(com.lowagie.text.Image) RtfImage(com.lowagie.text.rtf.graphic.RtfImage) RtfTab(com.lowagie.text.rtf.text.RtfTab) RtfAnchor(com.lowagie.text.rtf.field.RtfAnchor) PdfPTable(com.lowagie.text.pdf.PdfPTable) RtfNewPage(com.lowagie.text.rtf.text.RtfNewPage) ArrayList(java.util.ArrayList) List(com.lowagie.text.List) RtfList(com.lowagie.text.rtf.list.RtfList) RtfListItem(com.lowagie.text.rtf.list.RtfListItem) RtfTable(com.lowagie.text.rtf.table.RtfTable) PdfPTable(com.lowagie.text.pdf.PdfPTable) Table(com.lowagie.text.Table) SimpleTable(com.lowagie.text.SimpleTable) RtfTable(com.lowagie.text.rtf.table.RtfTable) RtfParagraph(com.lowagie.text.rtf.text.RtfParagraph) RtfChapter(com.lowagie.text.rtf.text.RtfChapter) Chapter(com.lowagie.text.Chapter) RtfSection(com.lowagie.text.rtf.text.RtfSection) RtfChunk(com.lowagie.text.rtf.text.RtfChunk) Phrase(com.lowagie.text.Phrase) RtfPhrase(com.lowagie.text.rtf.text.RtfPhrase) RtfAnnotation(com.lowagie.text.rtf.text.RtfAnnotation) Chunk(com.lowagie.text.Chunk) RtfChunk(com.lowagie.text.rtf.text.RtfChunk) RtfChapter(com.lowagie.text.rtf.text.RtfChapter) RtfSection(com.lowagie.text.rtf.text.RtfSection) Section(com.lowagie.text.Section) Annotation(com.lowagie.text.Annotation) RtfAnnotation(com.lowagie.text.rtf.text.RtfAnnotation) RtfParagraph(com.lowagie.text.rtf.text.RtfParagraph) Paragraph(com.lowagie.text.Paragraph) RtfList(com.lowagie.text.rtf.list.RtfList) RtfAnchor(com.lowagie.text.rtf.field.RtfAnchor) Anchor(com.lowagie.text.Anchor) RtfInfoElement(com.lowagie.text.rtf.document.RtfInfoElement) ListItem(com.lowagie.text.ListItem) RtfListItem(com.lowagie.text.rtf.list.RtfListItem) RtfPhrase(com.lowagie.text.rtf.text.RtfPhrase)

Aggregations

Annotation (com.lowagie.text.Annotation)16 Image (com.lowagie.text.Image)12 Chunk (com.lowagie.text.Chunk)9 Paragraph (com.lowagie.text.Paragraph)8 Rectangle (com.lowagie.text.Rectangle)8 Section (com.lowagie.text.Section)8 Document (com.lowagie.text.Document)7 Anchor (com.lowagie.text.Anchor)6 DocumentException (com.lowagie.text.DocumentException)6 Table (com.lowagie.text.Table)6 Phrase (com.lowagie.text.Phrase)5 BadElementException (com.lowagie.text.BadElementException)4 Element (com.lowagie.text.Element)4 List (com.lowagie.text.List)4 ListItem (com.lowagie.text.ListItem)4 TextElementArray (com.lowagie.text.TextElementArray)4 IOException (java.io.IOException)4 Cell (com.lowagie.text.Cell)3 Chapter (com.lowagie.text.Chapter)3 Meta (com.lowagie.text.Meta)3