Example usage for com.lowagie.text List add

List of usage examples for com.lowagie.text List add

Introduction

In this page you can find the example usage for com.lowagie.text List add.

Prototype

public boolean add(Object o) 

Source Link

Document

Adds an Object to the List.

Usage

From source file:classroom.filmfestival_b.Movies11.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//from   w ww. java  2s . c o m
    Document document = new Document();
    document.setMargins(36, 36, 48, 48);
    float middle = (document.right() + document.left()) / 2;
    float columns[][] = { { document.left(), document.bottom(), middle - 12, document.top() },
            { middle + 12, document.bottom(), document.right(), document.top() } };
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        writer.setPageEvent(new Movies11().new MoviePageEvents(middle, document.top(), document.bottom()));
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        ColumnText column = new ColumnText(writer.getDirectContent());
        column.setSimpleColumn(columns[0][0], columns[0][1], columns[0][2], columns[0][3]);

        float pos;
        int status;
        int ccount = 0;
        File f;
        Image img;
        Paragraph p;
        Chunk c;
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                img = Image.getInstance(f.getPath());
                img.setWidthPercentage(0);
                img.scaleToFit(72, 144);
            } else {
                img = null;
            }
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }

            if (img != null)
                column.addElement(img);
            column.addElement(p);
            column.addElement(list);
            pos = column.getYLine();
            status = column.go(true);
            if (ColumnText.hasMoreText(status)) {
                column.setText(null);
                ccount++;
                if (ccount > 1) {
                    ccount = 0;
                    document.newPage();
                    column.setSimpleColumn(columns[0][0], columns[0][1], columns[0][2], columns[0][3]);
                } else {
                    column.setSimpleColumn(columns[1][0], columns[1][1], columns[1][2], columns[1][3]);
                }
            } else {
                column.setYLine(pos);
            }
            if (img != null)
                column.addElement(img);
            column.addElement(p);
            column.addElement(list);
            column.addElement(Chunk.NEWLINE);
            column.go();
        }
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies13.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//from   w ww .j  a v  a2 s .  co m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell;
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies14.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1/* ww w .  j  a  va2  s  .  co  m*/
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies15.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1/*from w w  w  .  jav a  2s.c om*/
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setComplete(false);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        int counter = 10;
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
            if (counter % 10 == 0) {
                document.add(table);
            }
            System.out.println(writer.getPageNumber());
            counter++;
        }
        table.setComplete(true);
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_c.Movies17.java

@SuppressWarnings("unchecked")
protected static Element directors(FilmTitle movie) {
    Set<DirectorName> directors = movie.getDirectorNames();
    if (directors.size() == 0) {
        Paragraph p = new Paragraph("various directors");
        p.setLeading(16);/* w w  w .j a  v a2s .  c  om*/
        return p;
    }
    if (directors.size() == 1) {
        DirectorName name = directors.iterator().next();
        Paragraph p = new Paragraph(name.getName());
        p.setLeading(16);
        return p;
    }
    List list = new List(List.UNORDERED, 10);
    ListItem li;
    for (DirectorName director : directors) {
        li = new ListItem(director.getName());
        li.setLeading(16);
        list.add(li);
    }
    return list;
}

From source file:classroom.filmfestival_c.Movies17.java

@SuppressWarnings({ "unchecked", "deprecation" })
protected static Element screenings(FestivalScreening screening) {
    // the specific screening
    Paragraph p = getScreening(screening, BOLDSMALL);
    p.setLeading(16);//from   w w w .  jav a  2 s .  co  m

    FilmTitle movie = screening.getFilmTitle();
    Set<FestivalScreening> screenings = movie.getFestivalScreenings();
    if (screenings.size() == 1) {
        return p;
    }
    // the alternative screenings
    List list = new List(List.UNORDERED, 10);
    list.add(new ListItem(p));
    ListItem li;
    for (FestivalScreening ascreening : screenings) {
        if (ascreening.getId().equals(screening.getId()))
            continue;
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(ascreening.getId().getDay());
        if (gc.get(GregorianCalendar.YEAR) != YEAR)
            continue;
        li = new ListItem(getScreening(ascreening, SMALL));
        li.setLeading(12);
        list.add(li);
    }
    return list;
}

From source file:com.amphisoft.epub2pdf.content.XhtmlHandler.java

License:Open Source License

@Override
public void endElement(String uri, String localName, String qName) {
    //System.err.println("PRE-POP  -> " + saxElementStack);
    SaxElement closedElement = saxElementStack.pop();
    //System.err.println("POST-POP -> " + saxElementStack);
    currentITextStyle = closedElement.precedingItextStyle;

    //printlnerr("endElement:" + closedElement.toString());
    /*//from   w ww  .j av  a 2  s  .  co  m
    if("li".equals(qName)) {
       System.err.print("/" + qName + " ");
    }
            
    if("ol".equals(qName) || "ul".equals(qName)) {
       printlnerr("/" + qName + " ");
    }
     */
    //printlnerr("entering endElement " + localName + "; stack: " + stackStatus());
    try {
        //printlnerr("</" + qName + ">");
        if (document.isOpen()) {
            updateStack();
            for (int i = 0; i < 6; i++) {
                if (XhtmlTags.H[i].equals(qName)) {
                    //currentITextStyle ^= Font.BOLD;
                    if (specialParagraph != null) {
                        pushToStack(specialParagraph);
                    }
                    flushStack();
                    specialParagraph = null;
                    return;
                }
            }
            if (XhtmlTags.BLOCKQUOTE.equals(qName) || XhtmlTags.ORDEREDLIST.equals(qName)
                    || XhtmlTags.UNORDEREDLIST.equals(qName) || XhtmlTags.PRE.equals(qName)
                    || XhtmlTags.PARAGRAPH.equals(qName) || XhtmlTags.DIV.equals(qName)) {
                flushStack();
            } else if (XhtmlTags.TT.equals(qName)) {
                updateStack();
            } else if (XhtmlTags.LISTITEM.equals(qName)) {
                ListItem listItem = null;
                List list = null;
                try {
                    Element stackTop = (Element) popFromStack();
                    try {
                        listItem = (ListItem) stackTop;
                    } catch (ClassCastException cce) {
                        pushToStack(stackTop);
                    }
                    try {
                        Element stackTop2 = (Element) popFromStack();
                        try {
                            list = (List) stackTop2;
                        } catch (ClassCastException cce2) {
                            pushToStack(stackTop2);
                        }
                    } catch (EmptyStackException e) {
                        //printlnerr("*** EMPTY STACK (List)");
                    }
                } catch (EmptyStackException e) {
                    //printlnerr("*** EMPTY STACK (ListItem)");
                } finally {
                    if (listItem != null && list != null)
                        list.add(listItem);
                    if (list != null) {
                        pushToStack(list);
                    }
                }
            } else if (XhtmlTags.ANCHOR.equals(qName)) {
                Anchor anchor = null;
                Element stackTop = null;
                try {
                    stackTop = (Element) popFromStack();
                    try {
                        anchor = (Anchor) stackTop;
                    } catch (ClassCastException cce) {
                        if (stackTop != null) {
                            pushToStack(stackTop);
                        }
                    }
                    if (anchor != null) {
                        pushToStack(anchor);
                    }
                } catch (EmptyStackException es) {
                    if (anchor != null) {
                        pushToStack(anchor);
                    }
                }
            } else if (XhtmlTags.HTML.equals(qName)) {
                flushStack();
                if (this.controlOpenClose) {
                    document.close();
                }
            } else if (XhtmlTags.EM.equals(qName) || "I".equals(qName.toUpperCase())) {
                //currentITextStyle ^= Font.ITALIC;
            } else if (XhtmlTags.STRONG.equals(currentTag) || "B".equals(qName.toUpperCase())) {
                //currentITextStyle ^= Font.BOLD;
            } else if (XhtmlTags.STYLE.equals(qName)) {
                if (styleTagContents != null) {
                    CssStyleMap stylesFromHeadTag = cssParser
                            .getStylesFromStyleTag(styleTagContents.toString());
                    if (stylesFromHeadTag != null) {
                        styleMap.updateWith(stylesFromHeadTag);
                    }

                    styleTagContents = null;
                }
                inStyleTag = false;
            }

        }

        //printlnerr("leaving endElement " + localName + "; stack: " + stackStatus());
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
    if (saxElementStack.size()>0) {
            
       StyleSpecText revertStyles = saxElementStack.peek().textStyles;
       if (revertStyles != null) {
    currentITextStyle = Font.NORMAL;
    if (revertStyles.isBold()) {
       currentITextStyle |= Font.BOLD;
    }
    if (revertStyles.isItalic()) {
       currentITextStyle |= Font.ITALIC;
    }
       }
       else {
    currentITextStyle = Font.NORMAL;
       }
    }
    */
}

From source file:com.amphisoft.epub2pdf.content.XhtmlHandler.java

License:Open Source License

private java.util.List<String> getNoNewSpaceTagsList() {
    String[] noNewSpaceTags = { "a", "span", "em", "strong", "small", "br" };
    java.util.List<String> noNewSpaceTagsList = new ArrayList<String>();
    for (String tag : noNewSpaceTags) {
        noNewSpaceTagsList.add(tag);
    }//  w w w . j  av  a  2 s  . c om
    return noNewSpaceTagsList;

}

From source file:com.aryjr.nheengatu.pdf.PDFDocument.java

License:Open Source License

private void extractVisibleComponents(final Tag tag, final Document doc, final MultiColumnText mct,
        final Paragraph paragraph, final List list) throws DocumentException {
    final Iterator tags = tag.tags();
    Object component;/*from w  ww  . ja  v a2  s  .c  o m*/
    Image image;
    PDFTable table;
    final TagsManager tm = TagsManager.getInstance();

    PDFDocument.log.info("extractVisibleComponents");
    // PDFDocument.log.info(tm.states.size());
    // PDFDocument.log.info(tm.getTextIndent());
    // if (paragraph != null)
    // PDFDocument.log.info(paragraph.getFirstLineIndent());

    while (tags.hasNext()) {
        component = tags.next();
        if (component instanceof Text) {
            System.out.println("Processamento: Iniciou while -> if instanceof text");
            String s = ((Text) component).getText();
            if (s.contains("\\\"")) {
                s = s.replace("\\\"", "\"");
                ((Text) component).setText(s);
            }
            PDFDocument.log.info("text: " + ((Text) component).getText());
            // PDFDocument.log.info(tm.states.size());
            // PDFDocument.log.info(tm.getTextIndent());
            // PDFDocument.log.info(tm.getSpacingBefore());
            // PDFDocument.log.info(tm.getSpacingAfter());

            // If it's a text, create a iText text component for it
            if (paragraph != null)
                paragraph.add(PDFText.createChunk((Text) component));
            else if (list != null)
                list.add(PDFText.createParagraph((Text) component, tm));
            else
                mct.addElement(PDFText.createParagraph((Text) component, tm));
            System.out.println("Processamento: terminou while -> if instanceof text");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("br")) {
            // PDFDocument.log.info("br");
            // PDFDocument.log.info(tm.states.size());
            // PDFDocument.log.info(tm.getTextIndent());

            // If it's a HTML line break
            if (paragraph == null) {
                mct.addElement(new Paragraph("\n"));
            } else {
                paragraph.add("\n");
            }
            System.out.println("Processamento: Iniciou while -> if instanceof tag br");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("p")) {
            // If it's a HTML paragraph, create a iText paragraph for it

            tm.checkTag((Tag) component);
            final Paragraph p = PDFText.createParagraph(null, tm);

            PDFDocument.log.info("p");
            PDFDocument.log.info(tm.getFont().getSize());
            PDFDocument.log.info(p.getLeading());
            // PDFDocument.log.info(tm.states.size());
            // PDFDocument.log.info(tm.getTextIndent());
            // PDFDocument.log.info("align:");
            // PDFDocument.log.info(((Tag)
            // component).getPropertyValue("align"));
            // PDFDocument.log.info(tm.getAlign());

            // Paragraph p = new Paragraph();
            // p.setAlignment(tm.getAlign());
            // p.setKeepTogether(true);
            // // float b = tm.getSpacingBefore();
            // // float a = tm.getSpacingAfter();
            // p.setSpacingBefore(tm.getSpacingBefore());
            // p.setSpacingAfter(tm.getSpacingAfter());
            // p.setFirstLineIndent(tm.getTextIndent());
            extractVisibleComponents((Tag) component, doc, mct, p, list);
            if (paragraph != null)
                paragraph.add(p);
            else
                mct.addElement(p);

            // String align = ((Tag) component).getPropertyValue("align");
            // if (align != null) {
            // p.setAlignment(align.toLowerCase());
            // }
            tm.back();
            System.out.println("Processamento: Iniciou while -> if instanceof tag p");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("ol")) {
            // If it's a HTML paragraph, create a iText paragraph for it
            tm.checkTag((Tag) component);
            if (tm.getListStyleType() == null) {
                ((GraphicsState) tm.states.get(tm.states.size() - 1)).setListStyleType("upper-roman");
            } else if (tm.getListStyleType().equals("upper-roman")) {
                ((GraphicsState) tm.states.get(tm.states.size() - 1)).setListStyleType("lower-alpha");
            }
            final List l = new RomanList(tm.getListStyleType(), 30);
            if (list != null)
                list.add(l);
            else
                mct.addElement(l);
            extractVisibleComponents((Tag) component, doc, mct, null, l);
            tm.back();
            System.out.println("Processamento: Iniciou while -> if instanceof tag ol");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("ul")) {
            // If it's a HTML paragraph, create a iText paragraph for it
            final List l = new List(false, false, 20.0f);
            tm.checkTag((Tag) component);
            if (paragraph != null)
                paragraph.add(l);
            else
                mct.addElement(l);
            extractVisibleComponents((Tag) component, doc, mct, null, l);
            tm.back();
            System.out.println("Processamento: Iniciou while -> if instanceof tag ul");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("li")) {
            // If it's a HTML paragraph, create a iText paragraph for it
            final ListItem li = new ListItem(tm.getFont().getSize() * 1.25f);
            li.setSpacingAfter(tm.getFont().getSize() * 0.5f);

            PDFDocument.log.info("li");
            PDFDocument.log.info(tm.getFont().getSize());
            PDFDocument.log.info(li.getLeading());

            tm.checkTag((Tag) component);
            if (list == null)
                mct.addElement(li);
            else
                list.add(li);
            extractVisibleComponents((Tag) component, doc, mct, li, list);
            tm.back();
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("img")) {
            // If it's a HTML image, create a iText image component for it
            try {
                // TODO the image path can't be static
                image = PDFImage.createImage((Tag) component);
                if (paragraph == null) {
                    mct.addElement(image);
                } else {
                    paragraph.add(image);
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
            System.out.println("Processamento: Iniciou while -> if instanceof tag img");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("table")) {
            // If it's a HTML table, create a iText table component for it
            try {
                table = PDFTable.createTable((Tag) component);
                mct.addElement(table);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("div")) {
            final String s = ((Tag) component).getPropertyValue("style");
            if (s != null && s.equals("PAGE-BREAK-AFTER: always")) {
                doc.add(mct);
                mct.nextColumn();
            }
            tm.checkTag((Tag) component);
            extractVisibleComponents((Tag) component, doc, mct, paragraph, list);
            tm.back();
            System.out.println("Processamento: Iniciou while -> if instanceof tag div");
        } else {
            // If it's an another tag, check the name and call this method
            // again

            // PDFDocument.log.info("other!");
            // PDFDocument.log.info(tm.states.size());
            // PDFDocument.log.info(tm.getTextIndent());

            tm.checkTag((Tag) component);
            extractVisibleComponents((Tag) component, doc, mct, paragraph, list);
            tm.back();
            System.out.println("Processamento: Iniciou while -> else if");
        }
    }
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

License:Open Source License

private static boolean parseContent(WikiPDFContext context, Wiki wiki, String content, Document document,
        PdfPCell cell, Connection db, ArrayList<Integer> wikiListTodo, ArrayList<Integer> wikiListDone,
        float cellWidth) throws Exception {

    LOG.debug("PARSING CONTENT: " + content);

    // Parse the wiki page
    int lastIndent = 0;
    boolean preTag = false;
    boolean pre = false;
    boolean code = false;
    boolean header = true;

    try {//from   ww w  . j  av  a2s . c o  m

        BufferedReader in = new BufferedReader(new StringReader(content));
        String line = null;

        ArrayList unorderedParents = null;
        List thisList = null;
        Paragraph codeParagraph = null;

        while ((line = in.readLine()) != null) {
            // Tables
            if (line.startsWith("|")) {
                // @todo Close all ordered lists, unordered lists, and paragraphs

                // Parse the table
                line = parseTable(context, wiki, line, document, db, wikiListTodo, wikiListDone, in);

                if (line == null) {
                    continue;
                }
            }

            // Forms
            if (line.startsWith("[{form")) {
                // @todo close any lists or paragraphs

                // parseForm operates over all the lines that make up the form,
                // it will have to look forward so it returns an unparsed line
                parseForm(context, db, in, line, document, cell);
                continue;
            }

            // Handle code blocks
            // @todo chunk the content similar to WikiToHTMLUtils otherwise inaccurate
            if (line.startsWith("<pre>") || line.startsWith("<code>")) {
                if (!code && !pre) {
                    if (line.startsWith("<pre>")) {
                        preTag = true;
                        pre = true;
                    } else if (line.startsWith("<code>")) {
                        code = true;
                    }
                    codeParagraph = new Paragraph("", codeFont);
                    codeParagraph.setSpacingBefore(10);

                    if (pre && line.length() > ("<pre>").length()) {
                        int endOfLine = line.length();
                        if (line.endsWith("</pre>")) {
                            endOfLine = line.indexOf("</pre>");
                        }
                        // This line has some extra content that needs to be added
                        codeParagraph.add(new Chunk(
                                line.substring(line.indexOf("<pre>") + 5, endOfLine) + Chunk.NEWLINE));
                    }
                    if (code && line.length() > ("<code>").length()) {
                        int endOfLine = line.length();
                        if (line.endsWith("</code>")) {
                            endOfLine = line.indexOf("</code>");
                        }
                        // This line has some extra content that needs to be added
                        codeParagraph.add(new Chunk(
                                line.substring(line.indexOf("<code>") + 6, endOfLine) + Chunk.NEWLINE));
                    }
                    // See if this is a single line block
                    if (preTag && line.endsWith("</pre>")) {
                        // This is a single line block, so finish processing it
                    } else if (code && line.endsWith("</code>")) {
                        // This is a single line block, so finish processing it
                    } else {
                        // There are more lines to process, so do that
                        continue;
                    }
                }
            }
            if (line.startsWith("</code>") || line.endsWith("</code>")) {
                if (code) {
                    code = false;
                    if (line.indexOf("</code>") > 0 && !line.startsWith("<code>")) {
                        // This line has some extra content that needs to be added
                        codeParagraph
                                .add(new Chunk(line.substring(0, line.indexOf("</code>")) + Chunk.NEWLINE));
                    }
                    // Draw the final content
                    PdfPTable codeTable = new PdfPTable(1);
                    codeTable.setWidthPercentage(100);
                    codeTable.setSpacingBefore(10);
                    PdfPCell codeCell = new PdfPCell(codeParagraph);
                    codeCell.setPadding(20);
                    codeCell.setBorderColor(new Color(100, 100, 100));
                    codeCell.setBackgroundColor(new Color(200, 200, 200));
                    //            codeCell.setNoWrap(true);
                    codeTable.addCell(codeCell);
                    LOG.debug("document.add(codeTable)");
                    document.add(codeTable);
                    continue;
                }
            }
            if (line.startsWith("</pre>") || line.endsWith("</pre>")) {
                if (pre) {
                    preTag = false;
                    pre = false;
                    if (line.indexOf("</pre>") > 0 && !line.startsWith("<pre>")) {
                        // This line has some extra content that needs to be added
                        codeParagraph.add(new Chunk(line.substring(0, line.indexOf("</pre>")) + Chunk.NEWLINE));
                    }
                    // Draw the final content
                    PdfPTable codeTable = new PdfPTable(1);
                    codeTable.setWidthPercentage(100);
                    codeTable.setSpacingBefore(10);
                    PdfPCell codeCell = new PdfPCell(codeParagraph);
                    codeCell.setPadding(20);
                    codeCell.setBorderColor(new Color(100, 100, 100));
                    codeCell.setBackgroundColor(new Color(200, 200, 200));
                    //            codeCell.setNoWrap(true);
                    codeTable.addCell(codeCell);
                    LOG.debug("document.add(codeTable)");
                    document.add(codeTable);
                    continue;
                }
            }
            if (code || preTag) {
                // Append the chunk
                codeParagraph.add(new Chunk(line + Chunk.NEWLINE));
                continue;
            }

            // Section
            if (line.startsWith("=") && line.endsWith("=")) {
                // @todo close any open lists or paragraphs

                int hCount = parseHCount(line, "=");
                if (hCount > 6) {
                    hCount = 6;
                }
                String section = line.substring(line.indexOf("=") + hCount, line.lastIndexOf("=") - hCount + 1);
                header = true;
                context.foundHeader(hCount);
                String headerAnchor = null;

                // Store the h2's with anchors for table of contents or index
                if (hCount == 2) {
                    headerAnchor = StringUtils.toHtmlValue(section).replace(" ", "_");
                    context.getHeaderAnchors().put(headerAnchor, section);
                }
                if (hCount == 3) {
                    Paragraph title = new Paragraph(section.trim(), section2Font);
                    title.setSpacingBefore(10);
                    if (cell != null) {
                        LOG.debug("phrase.add(title)");
                        cell.addElement(title);
                    } else {
                        LOG.debug("document.add(title)");
                        document.add(title);
                    }
                } else if (hCount > 3) {
                    Paragraph title = new Paragraph(section.trim(), section3Font);
                    title.setSpacingBefore(10);
                    if (cell != null) {
                        LOG.debug("phrase.add(title)");
                        cell.addElement(title);
                    } else {
                        LOG.debug("document.add(title)");
                        document.add(title);
                    }
                } else {
                    Paragraph title = new Paragraph(section.trim(), sectionFont);
                    title.setSpacingBefore(10);
                    if (cell != null) {
                        LOG.debug("phrase.add(title)");
                        cell.addElement(title);
                    } else {
                        LOG.debug("document.add(title)");
                        document.add(title);
                    }
                }
                continue;
            }
            if (header) {
                header = false;
                if (line.trim().equals("")) {
                    // remove the extra space a user may leave after a header
                    continue;
                }
            }

            // Determine if this is a bulleted list
            if (line.startsWith("*") || line.startsWith("#")) {
                // Initialize the list array
                if (unorderedParents == null) {
                    unorderedParents = new ArrayList();
                    //            if (phrase != null) {
                    //              LOG.debug("phrase.add(new Paragraph(Chunk.NEWLINE))");
                    //              phrase.add(new Paragraph(Chunk.NEWLINE));
                    //            } else {
                    //              LOG.debug("document.add(new Paragraph(Chunk.NEWLINE))");
                    //              document.add(new Paragraph(Chunk.NEWLINE));
                    //            }
                }
                // Get the indent level
                boolean ol = line.startsWith("#");
                int hCount = WikiPDFUtils.parseHCount(line, ol ? "#" : "*");
                // Determine a shift in the tree
                if (lastIndent == 0) {
                    if (ol) {
                        thisList = new List(ol, 20);
                    } else {
                        thisList = new List(ol, 10);
                        thisList.setListSymbol(
                                new Chunk("\u2022", FontFactory.getFont(FontFactory.HELVETICA, 12)));
                    }
                    thisList.setIndentationLeft(36);
                    thisList.setIndentationRight(36);
                    unorderedParents.add(thisList);
                } else {
                    if (hCount > lastIndent) {
                        if (ol) {
                            thisList = new List(ol, 20);
                        } else {
                            thisList = new List(ol, 10);
                            thisList.setListSymbol(
                                    new Chunk("\u2022", FontFactory.getFont(FontFactory.HELVETICA, 12)));
                        }
                        thisList.setIndentationLeft(36);
                        thisList.setIndentationRight(36);
                        ((List) unorderedParents.get(unorderedParents.size() - 1)).add(thisList);
                        unorderedParents.add(thisList);
                    } else if (hCount < lastIndent) {
                        unorderedParents.remove(unorderedParents.size() - 1);
                        thisList = (List) unorderedParents.get(unorderedParents.size() - 1);
                    }
                }
                lastIndent = hCount;
                // Append the item...
                Paragraph thisItem = new Paragraph();
                parseLine(context, line.substring(hCount).trim(), thisItem, db, wikiListTodo, cellWidth, cell);
                thisList.add(new ListItem(thisItem));
                continue;
            }
            // List is finished, so append it to the document before working on
            // other paragraphs
            if (unorderedParents != null) {
                if (cell != null) {
                    LOG.debug("phrase.add((List) unorderedParents.get(0))");
                    cell.addElement((List) unorderedParents.get(0));
                } else {
                    LOG.debug("document.add((List) unorderedParents.get(0))");
                    document.add((List) unorderedParents.get(0));
                }
                unorderedParents = null;
                thisList = null;
                lastIndent = 0;
            }

            // Otherwise a simple paragraph
            Paragraph paragraph = new Paragraph();
            parseLine(context, line, paragraph, db, wikiListTodo, cellWidth, cell);
            if (cell != null) {
                LOG.debug("phrase.add(paragraph)");
                if (cell.getHorizontalAlignment() == Element.ALIGN_CENTER) {
                    paragraph.setAlignment(Element.ALIGN_CENTER);
                }
                paragraph.setSpacingBefore(5);
                cell.addElement(paragraph);
            } else {
                LOG.debug("document.add(paragraph)");
                paragraph.setSpacingBefore(5);
                document.add(paragraph);
            }
        }

        // Cleanup now that the lines are finished
        if (pre || code) {
            PdfPTable codeTable = new PdfPTable(1);
            codeTable.setWidthPercentage(100);
            codeTable.setSpacingBefore(10);
            PdfPCell codeCell = new PdfPCell(codeParagraph);
            codeCell.setPadding(20);
            codeCell.setBorderColor(new Color(100, 100, 100));
            codeCell.setBackgroundColor(new Color(200, 200, 200));
            //        codeCell.setNoWrap(true);
            codeTable.addCell(codeCell);
            LOG.debug("document.add(codeTable)");
            document.add(codeTable);
        }
        if (unorderedParents != null) {
            if (cell != null) {
                LOG.debug("phrase.add((List) unorderedParents.get(0))");
                cell.addElement((List) unorderedParents.get(0));
            } else {
                LOG.debug("document.add((List) unorderedParents.get(0))");
                document.add((List) unorderedParents.get(0));
            }
        }
        in.close();
    } catch (Exception e) {
        LOG.error("parseContent", e);
    }
    return true;
}