Example usage for com.lowagie.text Paragraph add

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

Introduction

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

Prototype

public boolean add(Object o) 

Source Link

Document

Adds an Object to the Paragraph.

Usage

From source file:com.ainfosec.macresponse.report.RtfGenerator.java

License:Open Source License

private static void addTables(TreeObject rootObject) {
    // TODO Paul add table of contents/etc.?
    // Table of Contents
    //document.add(new RtfTableOfContents("Table of Contents2"));
    Paragraph paragraph = new Paragraph();
    paragraph.add("Table of Contents\n\n");

    for (TreeObject treeObject : rootObject.getChildObjects()) {
        if (treeObject.isChecked()) {
            addTocSection(paragraph, treeObject, String.valueOf(currentChapter));
            currentChapter++;/*from  w  ww.ja va 2s .c  o  m*/
        }
    }
    currentChapter = 1;

    document.add(new RtfParagraph(document, paragraph));

    // Table of Figures
    // Table of Tables
}

From source file:com.ainfosec.macresponse.report.RtfGenerator.java

License:Open Source License

private static void addTocSection(Paragraph paragraph, TreeObject treeObject, String sectionNumber) {
    int subsectionNumber = 1;

    if (treeObject.isChecked()) {
        StringBuffer sb = new StringBuffer();
        sb.append(sectionNumber);//from  www  .j  a va2 s.co m
        sb.append(". ");
        sb.append(treeObject.getTitle());
        sb.append("\n");
        paragraph.add(sb.toString());
    }

    // TODO Paul Print out the data sections

    // Print out the children
    if ((treeObject.getChildObjects() != null) && (treeObject.getChildObjects().size() > 0)) {
        for (TreeObject childObject : treeObject.getChildObjects()) {
            String currentSection = sectionNumber + "." + String.valueOf(subsectionNumber);
            if (treeObject.isChecked()) {
                addTocSection(paragraph, childObject, currentSection);
                subsectionNumber++;
            }
        }
    }
}

From source file:com.ainfosec.macresponse.report.RtfGenerator.java

License:Open Source License

private static void populateChapter(TreeObject treeObject, Chapter chapter) {
    // If there are children, don't display this object's data
    if ((treeObject.getChildObjects() == null) || (treeObject.getChildObjects().size() == 0)) {
        // Create the Data Paragraphs (displayObjects)
        if ((treeObject.getDisplayData() != null)
                && (treeObject.getDisplayData().getDisplayObjects() != null)) {
            for (DisplayObject displayObject : treeObject.getDisplayData().getDisplayObjects()) {
                Paragraph paragraph = new Paragraph(displayObject.getTitle(), sectionTitleFont);

                paragraph.add("\n");
                createDataSection(paragraph, displayObject);

                chapter.addSection(paragraph);
            }/*from  www  .  java2s  . c om*/
        }
    }
    // If there are children, display them
    else {
        for (TreeObject childTreeObject : treeObject.getChildObjects()) {
            Paragraph title = new Paragraph(childTreeObject.getTitle(), sectionTitleFont);
            Paragraph content = new Paragraph("\n");

            generateData(content, childTreeObject);

            chapter.addSection(title);
            chapter.add(content);
        }
    }
}

From source file:com.ainfosec.macresponse.report.RtfGenerator.java

License:Open Source License

private static void generateData(Paragraph paragraph, TreeObject treeObject) {
    // TODO Paul take into consideration TreeObjects that have children (don't display current, make a section for each child)

    for (DisplayObject displayObject : treeObject.getDisplayData().getDisplayObjects()) {
        createDataSection(paragraph, displayObject);
        paragraph.add("\n");
    }/*from   w w w  . j  av  a 2  s . c om*/
}

From source file:com.ainfosec.macresponse.report.RtfGenerator.java

License:Open Source License

private static void createDataSection(Paragraph paragraph, DisplayObject displayObject) {
    if (displayObject == null || displayObject.getObjects() == null) {
        return;//w ww  . ja  v  a  2 s . c o m
    }

    // See if the DisplayObject has a list or a single object
    if (displayObject.getObjects().size() == 1) {
        TreeObject treeObject = displayObject.getObjects().get(0); // There's only 1 item

        // For each column, create/add a label with the title and the data
        int i = 0;
        for (String columnName : displayObject.getColumnNames()) {
            StringBuffer sb = new StringBuffer();

            // Add the column title
            sb.append(displayObject.getColumnTitles()[i]);
            sb.append(": ");

            // Get the value of the field
            try {
                Field field = treeObject.getClass().getDeclaredField(columnName);
                String val = (String) field.get(treeObject);
                if (val == null) {
                    val = "";
                }
                // Add the value
                sb.append(val);
                sb.append("\n");
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Put the string into the paragraph
            paragraph.add(sb.toString());
            i++;
        }
    } else {
        PdfPTable table = new PdfPTable(displayObject.getColumnTitles().length);
        table.setWidthPercentage(100);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        for (String columnName : displayObject.getColumnTitles()) {
            table.getDefaultCell().setBackgroundColor(Color.CYAN);
            table.addCell(columnName);
            table.getDefaultCell().setBackgroundColor(Color.WHITE);
        }

        for (TreeObject to1 : displayObject.getObjects()) {
            for (String columnName : displayObject.getColumnNames()) {
                try {
                    Field field = to1.getClass().getDeclaredField(columnName);
                    String val = (String) field.get(to1);
                    if (val == null) {
                        val = "";
                    }
                    table.addCell(val);
                } catch (NoSuchFieldException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        table.getDefaultCell().setColspan(displayObject.getColumnTitles().length);
        table.getDefaultCell().setBorder(SWT.NONE);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

        // TODO Paul number the tables
        table.addCell("Table: " + displayObject.getTitle());
        document.add(new RtfTable(document, table));
    }
}

From source file:com.aripd.clms.service.ContractServiceBean.java

private static void addTitlePage(Document document, ContractEntity contract) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//from   ww  w  .  jav  a  2s .  c  om
    // Lets write a big header
    preface.add(new Paragraph(contract.getName()));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date()));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important "));

    addEmptyLine(preface, 8);

    preface.add(
            new Paragraph("This document is a preliminary version and not subject to your license agreement."));

    document.add(preface);
    // Start a new page
    document.newPage();
}

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;/*w w  w . j  a  va  2  s  .co 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.aryjr.nheengatu.pdf.PDFTable.java

License:Open Source License

private static float extractVisibleComponents(final Tag tag, final PdfPCell cell, final Paragraph paragraph,
        float cellWidth) throws DocumentException {
    final Iterator tags = tag.tags();// tags inside the cell
    Object component;//  www . j  a  v  a 2 s.c o m
    final TagsManager tm = TagsManager.getInstance();
    // Seting the HTML row or table background color
    if (tag.getName().equalsIgnoreCase("TD")) {
        cell.setBorderColor(tm.getPreviousState(2).getBgcolor());
        cell.setBorderWidth(tag.getPropertyValue(PDFTable.CELLSPACING) == null ? 1
                : Integer.parseInt(tag.getPropertyValue(PDFTable.CELLSPACING)));
        //cell.setBackgroundColor(tm.getBgcolor());
        cell.setBackgroundColor(new Color(255, 255, 255));
        cell.setVerticalAlignment(tm.getValign());
        cell.setHorizontalAlignment(tm.getAlign());
        paragraph.setAlignment(tm.getAlign());
    }
    while (tags.hasNext()) {
        component = tags.next();
        if (component instanceof Text) {
            String s = ((Text) component).getText();
            if (s.contains("\\\"")) {
                s = s.replace("\\\"", "\"");
                ((Text) component).setText(s);
            }
            // If it's a text, create a iText text component for it
            paragraph.add(PDFText.createChunk((Text) component));
            cellWidth += PDFText.getWidth((Text) component);
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("br")) {
            // If it's a HTML line break
            paragraph.add("\n");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("img")) {
            // If it's a HTML image, create a iText image component for it
            try {
                final Image img = PDFImage.createImage((Tag) component);
                //Nato: paragraph.add(new Chunk(img, 0, -2));
                paragraph.add(new Chunk(img, 0, 0));
                cellWidth += img.getScaledWidth();
                // TODO Is there an iText bug here?
                //if (img.scaledHeight() == 1f) {
                //cell.setFixedHeight(img.getScaledHeight());
                //}
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("table")) {
            // If it's a HTML table, create a iText table component for it
            try {
                // TODO the default value of nowrap here will be true or
                // false??? If true, there is a problem with the cell width
                cell.setNoWrap(false);
                final PDFTable t = PDFTable.createTable((Tag) component);
                cell.addElement(t);
                final float[] cw = t.getWidths();
                for (final float element : cw) {
                    cellWidth += element;
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("select")) {
            // If it's a HTML select field, I will get only the selected
            // option
            final Tag select = (Tag) component;
            Tag opt;
            tm.checkTag(select);
            final Iterator opts = select.tags();
            boolean selected = false;
            while (opts.hasNext()) {
                opt = (Tag) opts.next();
                if (opt.getPropertyValue("selected") != null) {
                    tm.checkTag(opt);
                    cellWidth = PDFTable.extractVisibleComponents(opt, cell, paragraph, cellWidth);
                    selected = true;
                    break;
                }
            }
            if (!selected) {
                // if none option have the selected attribute the first will
                // be shown
                opt = select.getFirstTag("option");
                tm.checkTag(opt);
                cellWidth = PDFTable.extractVisibleComponents(opt, cell, paragraph, cellWidth);
            }
        } else {
            // If it's an another tag, check the name and call this method
            // again
            tm.checkTag((Tag) component);
            cellWidth = PDFTable.extractVisibleComponents((Tag) component, cell, paragraph, cellWidth);
            tm.back();
        }
    }
    return cellWidth;
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

private Object generateElementHtml(Element element, int depth, Font font) {
    String tag = element.getName();
    Object myself;/* ww w  . j a v  a 2 s  .c  o m*/
    Object av;
    if (element instanceof HTMLDocument.RunElement) {
        HTMLDocument.RunElement re = (HTMLDocument.RunElement) element;
        int start = re.getStartOffset();
        int end = re.getEndOffset();
        try {
            String content = re.getDocument().getText(start, end - start);
            HtmlAttr htmlattr = printAttributesHtml(re);
            av = re.getAttribute(CSS.Attribute.FONT_SIZE);
            String fontsize = av == null ? null : av.toString();
            av = re.getAttribute(CSS.Attribute.FONT_FAMILY);
            String fontfamily = av == null ? null : av.toString();
            av = re.getAttribute(CSS.Attribute.COLOR);
            String fontcolor = av == null ? null : av.toString();
            if (fontcolor != null || fontsize != null || fontfamily != null) {
                if (fontfamily == null)
                    fontfamily = font.getFamilyname();
                if (fontsize != null && fontsize.endsWith("pt"))
                    fontsize = fontsize.substring(0, fontsize.indexOf("pt"));
                float size = fontsize == null ? font.getSize() : (Float.parseFloat(fontsize) + 8);
                int style = font.getStyle();
                Color color;
                if (fontcolor != null) {
                    color = Color.decode(fontcolor);
                } else
                    color = font.getColor();
                font = FontFactory.getFont(fontfamily, size, style, color);
            } else if (htmlattr.bold || htmlattr.italic) {
                String family = font.getFamilyname();
                float size = font.getSize();
                Color color = font.getColor();
                if (htmlattr.bold && htmlattr.italic)
                    font = FontFactory.getFont(family, size, Font.BOLDITALIC, color);
                else if (htmlattr.italic)
                    font = FontFactory.getFont(family, size, Font.ITALIC, color);
                else if (htmlattr.bold)
                    font = FontFactory.getFont(family, size, Font.BOLD);
            }
            myself = new Chunk(content, font);
        } catch (BadLocationException e) {
            e.printStackTrace();
            myself = null;
        }
    } else if (element instanceof HTMLDocument.BlockElement) {
        HTMLDocument.BlockElement be = (HTMLDocument.BlockElement) element;
        HtmlAttr htmlattr = printAttributesHtml(be);
        if (htmlattr.bold) {
            System.out.println("+++BOLD!!!");
        }
        av = be.getAttribute(javax.swing.text.html.HTML.Attribute.ALIGN);
        String align = av == null ? null : av.toString();
        if (htmlattr.bold || htmlattr.italic) {
            String family = font.getFamilyname();
            float size = font.getSize();
            Color color = font.getColor();
            if (htmlattr.bold && htmlattr.italic)
                font = FontFactory.getFont(family, size, Font.BOLDITALIC, color);
            else if (htmlattr.italic)
                font = FontFactory.getFont(family, size, Font.ITALIC, color);
            else if (htmlattr.bold)
                font = FontFactory.getFont(family, size, Font.BOLD, Color.blue);
        }
        if (tag.equalsIgnoreCase("html")) {
            myself = generateElementChildrenHtml(element, depth + 1, font);
        } else if (tag.equalsIgnoreCase("head")) {
            myself = null;
        } else if (tag.equalsIgnoreCase("body")) {
            myself = generateElementChildrenHtml(element, depth + 1, font);
        } else if (tag.equalsIgnoreCase("p") || tag.equalsIgnoreCase("p-implied")) {
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            Paragraph paragraph = new Paragraph();
            paragraph.setFirstLineIndent(0F);
            for (Object child : children) {
                if (child instanceof Chunk) {
                    Chunk chunk = (Chunk) child;
                    /*if (!chunk.getContent().equals("\n"))*/ paragraph.add(chunk);
                } else
                    paragraph.add(child);
            }
            if (align != null)
                paragraph.setAlignment(align);
            myself = paragraph;
        } else if (tag.equalsIgnoreCase("h1") || tag.equalsIgnoreCase("h2") || tag.equalsIgnoreCase("h3")) {
            List<Object> children = generateElementChildrenHtml(element, depth + 1, subSectionFont);
            Paragraph title = new Paragraph();
            for (Object child : children) {
                title.add(child);
            }
            myself = new TempSectionPdf(title);
        } else if (tag.equalsIgnoreCase("ul")) {
            com.lowagie.text.List list = new com.lowagie.text.List(false, false, 20.0f);
            list.setIndentationLeft(25.0f);
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            for (Object child : children) {
                list.add(child);
            }
            myself = list;
        } else if (tag.equalsIgnoreCase("ol")) {
            com.lowagie.text.List list = new com.lowagie.text.List(true, false, 20.0f);
            list.setIndentationLeft(25.0f);
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            for (Object child : children) {
                list.add(child);
            }
            myself = list;
        } else if (tag.equalsIgnoreCase("li")) {
            ListItem li = new ListItem();
            li.setSpacingAfter(0.0f);
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            for (Object child : children) {
                li.add(child);
            }
            myself = li;
        } else if (tag.equalsIgnoreCase("table")) {
            List<Object> rows = generateElementChildrenHtml(element, depth + 1, normalFont);
            try {
                int ncols = 0;
                for (Object row : rows) {
                    if (row instanceof List<?>) {
                        int n = ((List<?>) row).size();
                        if (n > ncols)
                            ncols = n;
                    }
                }
                Table table = new Table(2);
                table.setBorderWidth(1);
                table.setBorderColor(new Color(0, 128, 128));
                table.setPadding(1.0f);
                table.setSpacing(0.5f);
                Cell c = new Cell("header");
                c.setHeader(true);
                c.setColspan(ncols);
                table.addCell(c);
                table.endHeaders();
                for (Object row : rows) {
                    if (row instanceof List<?>) {
                        for (Object cell : (List<?>) row) {
                            if (cell instanceof Cell)
                                table.addCell((Cell) cell);
                        }
                    }
                }
                myself = table;
            } catch (BadElementException e) {
                e.printStackTrace();
                myself = null;
            }
        } else if (tag.equalsIgnoreCase("tr")) {
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            myself = children;
        } else if (tag.equalsIgnoreCase("td")) {
            Cell cell = new Cell();
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            for (Object child : children) {
                cell.add(child);
            }
            myself = cell;
        } else if (tag.equalsIgnoreCase("div")) {
            List<Object> children = generateElementChildrenHtml(element, depth + 1, normalFont);
            Paragraph paragraph = new Paragraph();
            paragraph.setFirstLineIndent(0F);
            for (Object child : children) {
                paragraph.add(child);
            }
            if (align != null)
                paragraph.setAlignment(align);
            myself = paragraph;
        } else {
            System.err.println("Unknown element " + element.getName());
            myself = null;
        }
    } else {
        myself = null; // could be BidiElement - not sure what it is
    }
    return myself;
}

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 a  v a 2 s. 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;
}