Example usage for com.lowagie.text Document add

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

Introduction

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

Prototype


public boolean add(Element element) throws DocumentException 

Source Link

Document

Adds an Element to the Document.

Usage

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

License:Apache License

/**
 * Export a process/*from  ww w . j ava2s.com*/
 * @param filename the file name (including path) where the document will be generated
 * @param format can be docx, pdf, rtf, html and bpmn
 * @param canvas for printing process images
 * @param graph the process to be printed.
 */
public void exportProcess(String filename, String format, Graph process, DesignerCanvas canvas)
        throws Exception {

    initialize(false);

    String oldNodeIdType = process.getNodeIdType();

    try {
        process.setNodeIdType(nodeIdType);
        options.add(SECTION_NUMBER);
        if (format.equals(DOCX)) {
            DocxBuilder builder = printProcessDocx(filename, process, canvas);
            builder.save(new java.io.File(filename));
            return;
        } else if (format.equals(HTML)) {
            StringBuffer sb = printPrologHtml("Process " + process.getName());
            printProcessHtml(sb, canvas, 0, process, filename);
            printEpilogHtml(sb, filename);
            return;
        } else if (format.equals(JPG) || format.equals(PNG)) {
            byte[] imgBytes = printImage(-1f, canvas, process.getGraphSize(),
                    format.equals(JPG) ? "jpeg" : "png");
            OutputStream os = null;
            try {
                os = new FileOutputStream(new File(filename));
                os.write(imgBytes);
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            } finally {
                if (os != null)
                    os.close();
            }
        } else if (format.equals(BPMN2)) {
            new BPMNHelper().exportProcess(process.getProcessVO(), filename);
        } else { // itext processor
            Document document = new Document();
            try {
                DocWriter writer = null;
                if (format.equals(RTF)) {
                    writer = RtfWriter2.getInstance(document, new FileOutputStream(filename));
                } else if (format.equals(PDF)) {
                    writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
                }

                document.open();
                document.setPageSize(PageSize.LETTER);
                Rectangle page_size = document.getPageSize();
                Chapter chapter = printOneProcessPdf(writer, canvas, format, 1, process, filename, page_size);
                document.add(chapter);
            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            } finally {
                // step 5: we close the document
                document.close();
            }
        }
    } finally {
        process.setNodeIdType(oldNodeIdType);
    }
}

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

License:Apache License

/**
 * Export multiple processes//from w w w.  j a va  2  s. com
 * @param filename the file name (including path) where the document will be generated
 * @param type can be pdf, rtf and html
 * @param flowchart the designer page (for using its canvas and report errors)
 * @param graphs the list of processes to be printed.
 * @param options options for printing, from the print dialog.
 */
public void exportProcesses(String filename, String type, FlowchartPage flowchart, List<Graph> graphs)
        throws Exception {
    initialize(false);
    options.add(SECTION_NUMBER);
    // step 1: creation of a document-object
    Document document = new Document();
    try {
        // step 2: create PDF or RTF writer
        DocWriter writer;
        if (type.equals(RTF)) {
            writer = RtfWriter2.getInstance(document, new FileOutputStream(filename));
        } else if (type.equals(PDF)) {
            writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        } else {
            boolean directHtml = true;
            if (directHtml) {
                StringBuffer sb = printPrologHtml("Processes");
                Graph process;
                for (int i = 0; i < graphs.size(); i++) {
                    process = graphs.get(i);
                    flowchart.setProcess(process);
                    this.printProcessHtml(sb, flowchart.canvas, i + 1, process, filename);
                }
                printEpilogHtml(sb, filename);
                return;
            }
            writer = HtmlWriter.getInstance(document, new FileOutputStream(filename));
        }
        // step 3: we open the document
        document.open();
        // step 4: we add contents to the document
        document.setPageSize(PageSize.LETTER);
        Graph process;
        Chapter chapter;
        Rectangle page_size = document.getPageSize();
        for (int i = 0; i < graphs.size(); i++) {
            process = graphs.get(i);
            process.setNodeIdType(nodeIdType);
            flowchart.setProcess(process);
            chapter = printOneProcessPdf(writer, flowchart.canvas, type, i + 1, process, filename, page_size);
            document.add(chapter);
        }
    } finally {
        // step 5: we close the document
        document.close();
    }
}

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

License:Apache License

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {//from  w w w. j  a v a 2  s  . c  om
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // mapper.insertDirectory("c:\\windows\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        int margin = 72; // 1 inch
        float scale = 0.5f;
        boolean multiple_page = true;
        Rectangle page_size;
        if (multiple_page) {
            page_size = PageSize.LETTER.rotate();
        } else {
            page_size = new Rectangle((int) (graphsize.getWidth() * scale) + margin,
                    (int) (graphsize.getHeight() * scale) + margin);
        }
        Document document = new Document(page_size);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(page_size);
        int image_w = (int) page_size.getWidth() - margin;
        int image_h = (int) page_size.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        if (multiple_page) {
            int horizontal_pages = (int) (graphsize.width * scale) / image_w + 1;
            int vertical_pages = (int) (graphsize.height * scale) / image_h + 1;
            for (int i = 0; i < horizontal_pages; i++) {
                for (int j = 0; j < vertical_pages; j++) {
                    Image img;
                    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                    PdfTemplate tp = cb.createTemplate(image_w, image_h);
                    Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
                    tp.setWidth(image_w);
                    tp.setHeight(image_h);
                    g2.scale(scale, scale);
                    g2.translate(-i * image_w / scale, -j * image_h / scale);
                    canvas.paintComponent(g2);
                    g2.dispose();
                    img = new ImgTemplate(tp);
                    document.add(img);
                }
            }
        } else {
            Image img;
            PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
            PdfTemplate tp = cb.createTemplate(image_w, image_h);
            Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
            tp.setWidth(image_w);
            tp.setHeight(image_h);
            g2.scale(scale, scale);
            canvas.paintComponent(g2);
            g2.dispose();
            img = new ImgTemplate(tp);
            document.add(img);
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.compomics.pepshell.controllers.dataexport.PDFExport.java

License:Apache License

@Override
public void exportImage(BufferedImage imageToExport, String filename) {
    File exportFile = new File(ProgramVariables.EXPORTFOLDER, filename + ".pdf");
    if (append && exportFile.exists()) {

    } else {// w ww. ja va  2 s . c om
        File exportImageFile = new File(System.getProperty("file.temp"), filename);
        try {
            ImageIO.write(imageToExport, "png", new FileOutputStream(exportImageFile));
            Image pdfImage = Image.getInstance(exportImageFile.getAbsolutePath());
            Document document = new Document(new Rectangle(pdfImage.absoluteX(), pdfImage.absoluteY()));
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(exportFile));
            document.open();
            document.newPage();
            document.add(pdfImage);
            document.close();
        } catch (DocumentException | IOException ex) {
            FaultBarrier.getInstance().handleException(ex);
        }
    }
}

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

License:Open Source License

public static boolean functionsToUse(Project project, Wiki wiki, File file, HashMap imageList)
        throws Exception {
    // remove this.
    Document document = new Document();

    // Parse each line to see if paragraph, table, section heading, list
    // Parse within the line to see if bold, italic, links, code fragment, images

    // Define styles
    Font exampleFont = FontFactory.getFont(FontFactory.HELVETICA, 24, Font.NORMAL, new Color(255, 0, 0));

    // Add title and paragraphs

    // TODO: Construct a title page... with logo
    Paragraph title = new Paragraph(wiki.getSubject(), exampleFont);

    //Chunk title = new Chunk(wiki.getSubject());
    //title.setBackground(new Color(0xFF, 0xDE, 0xAD));
    ////title.setUnderline(new Color(0xFF, 0x00, 0x00), 3.0f, 0.0f, -4.0f, 0.0f, PdfContentByte.LINE_CAP_ROUND);
    //title.setUnderline(0.2f, -2f);
    LOG.debug("document.add(title)");
    document.add(title);

    // Link from/*from w w w.  j  a  v a 2 s .c  o m*/
    // a paragraph with a local goto
    //Paragraph p1 = new Paragraph("We will do something special with this paragraph. If you click on ", FontFactory.getFont(FontFactory.HELVETICA, 12));
    //p1.add(new Chunk("this word", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 255))).setLocalGoto("test"));
    //p1.add(" you will automatically jump to another location in this document.");

    // a paragraph with a local destination
    //Paragraph p3 = new Paragraph("This paragraph contains a ");
    //p3.add(new Chunk("local destination", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 255, 0))).setLocalDestination("test"));

    // Ext A Href
    //Paragraph paragraph = new Paragraph("Please visit my ");
    //Anchor anchor1 = new Anchor("website (external reference)", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, new Color(0, 0, 255)));
    //anchor1.setReference("http://www.lowagie.com/iText/");
    //anchor1.setName("top");
    //paragraph.add(anchor1);

    //Image jpg = Image.getInstance("otsoe.jpg");
    //document.add(jpg);

    return false;
}

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

License:Open Source License

public static boolean exportToFile(WikiPDFContext context, Connection db) throws Exception {

    LOG.debug("exportToFile-> begin");

    // Context Objects
    Wiki wiki = context.getWiki();//from  w  w w .  j a  va  2s  .  com
    Project project = context.getProject();
    File file = context.getFile();
    WikiExportBean exportBean = context.getExportBean();

    // Determine the content to parse
    String content = wiki.getContent();
    if (content == null) {
        return false;
    }

    // Create a pdf
    Document document = new Document(PageSize.LETTER);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

    // Meta data
    document.addTitle(project.getTitle());
    document.addSubject(wiki.getSubject());
    document.addCreator("Concursive ConcourseConnect");
    document.addAuthor("Wiki Contributor");
    //writer.setPageEvent(new PageNumbersWatermark());

    if (!exportBean.getIncludeTitle()) {
        boolean hasTitle = StringUtils.hasText(wiki.getSubject());
        HeaderFooter pageFooter = new HeaderFooter(
                new Phrase(project.getTitle() + (hasTitle ? ": " + wiki.getSubject() : "") + " - page "),
                new Phrase(""));
        pageFooter.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(pageFooter);
    }

    document.open();

    if (exportBean.getIncludeTitle()) {
        //HeaderFooter pageHeader = new HeaderFooter(new Phrase(project.getTitle()), false);
        //document.setHeader(pageHeader);
        boolean hasTitle = (StringUtils.hasText(wiki.getSubject()));
        HeaderFooter pageFooter = new HeaderFooter(
                new Phrase(project.getTitle() + (hasTitle ? ": " + wiki.getSubject() : "") + " - page "),
                new Phrase(""));
        pageFooter.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(pageFooter);

        // Draw a title page
        Rectangle rectangle = new Rectangle(600, 30);
        rectangle.setBackgroundColor(new Color(100, 100, 100));
        LOG.debug("document.add(rectangle)");
        document.add(rectangle);

        document.add(new Paragraph(project.getTitle(), titleFont));
        if (!"".equals(wiki.getSubject())) {
            document.add(new Paragraph(wiki.getSubject(), titleFont));
        }
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Last Modified: " + wiki.getModified(), titleSmallFont));
        document.newPage();
    }

    ArrayList<Integer> wikiListDone = new ArrayList<Integer>();

    appendWiki(context, context.getWiki(), document, db, wikiListDone);
    // Close everything
    document.close();
    writer.close();
    LOG.debug("exportToFile-> finished");
    return true;
}

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

License:Open Source License

private static void appendWiki(WikiPDFContext context, Wiki currentWiki, Document document, Connection db,
        ArrayList<Integer> wikiListDone) throws SQLException {

    LOG.debug("appendWiki-> " + currentWiki.getSubject());

    // Context Objects
    Project project = context.getProject();
    WikiExportBean exportBean = context.getExportBean();

    // Track the wikis to get appended to the output
    ArrayList<Integer> wikiListTodo = new ArrayList<Integer>();

    try {//from  w ww .  j  a  v  a 2s . c om
        // Output the name of the Wiki
        boolean hasTitle = StringUtils.hasText(currentWiki.getSubject());
        if (hasTitle) {
            Anchor wikiAnchor = new Anchor(currentWiki.getSubject(), wikiFont);
            wikiAnchor.setName(currentWiki.getSubject().toLowerCase());
            LOG.debug("Add anchor: " + currentWiki.getSubject().toLowerCase());
            document.add(wikiAnchor);
            LOG.debug("document.add(wikiAnchor)");
        }

        // Output the wiki content
        parseContent(context, currentWiki, currentWiki.getContent(), document, null, db, wikiListTodo,
                wikiListDone, 0f);
        wikiListDone.add(currentWiki.getId());

        // See if any linked wikis should be appended
        if (exportBean.getFollowLinks() && wikiListTodo.size() > 0) {
            Iterator i = wikiListTodo.iterator();
            while (i.hasNext()) {
                Integer id = (Integer) i.next();
                if (id > -1 && !wikiListDone.contains(id)) {
                    Wiki subwiki = new Wiki(db, id);
                    document.add(Chunk.NEXTPAGE);
                    appendWiki(context, subwiki, document, db, wikiListDone);
                }
                //i.remove();
            }
        }
    } catch (Exception e) {
        LOG.error("appendWiki", e);
    }
}

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 {// w  ww  .j av 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;
}

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

License:Open Source License

private static String parseTable(WikiPDFContext context, Wiki wiki, String line, Document document,
        Connection db, ArrayList<Integer> wikiListTodo, ArrayList<Integer> wikiListDone, BufferedReader in)
        throws Exception {
    if (line == null) {
        return null;
    }//from   w  ww.j a  va2s  .  c  om
    PdfPTable pdfTable = null;
    int columnCount = 0;
    int rowCount = 0;

    // Keep track of the table's custom styles
    HashMap<Integer, String> cStyle = new HashMap<Integer, String>();

    while (line != null && (line.startsWith("|") || line.startsWith("!"))) {

        // Build a complete line
        String lineToParse = line;
        while (!line.endsWith("|")) {
            line = in.readLine();
            if (line == null) {
                // there is an error in the line to process
                return null;
            }
            if (line.startsWith("!")) {
                lineToParse += CRLF + line.substring(1);
            }
        }
        line = lineToParse;

        // Determine if the row can output
        boolean canOutput = true;

        ++rowCount;

        String cellType = null;
        Scanner sc = null;
        if (line.startsWith("||") && line.endsWith("||")) {
            cellType = "th";
            sc = new Scanner(line).useDelimiter("[|][|]");
            //        sc = new Scanner(line.substring(2, line.length() - 2)).useDelimiter("[|][|]");
        } else if (line.startsWith("|")) {
            cellType = "td";
            sc = new Scanner(line.substring(1, line.length() - 1)).useDelimiter("\\|(?=[^\\]]*(?:\\[|$))");
        }

        if (sc != null) {

            if (rowCount == 1) {
                // Count the columns, get the specified widths too...
                while (sc.hasNext()) {
                    ++columnCount;
                    sc.next();
                }
                // Reset the scanner now that the columns have been counted
                if (line.startsWith("||") && line.endsWith("||")) {
                    sc = new Scanner(line).useDelimiter("[|][|]");
                } else if (line.startsWith("|")) {
                    sc = new Scanner(line.substring(1, line.length() - 1))
                            .useDelimiter("\\|(?=[^\\]]*(?:\\[|$))");
                }

                // Start the table
                pdfTable = new PdfPTable(columnCount);
                //pdfTable.setWidthPercentage(100);
                pdfTable.setHorizontalAlignment(Element.ALIGN_LEFT);
                pdfTable.setSpacingBefore(10);
                pdfTable.setWidthPercentage(100);
                pdfTable.setKeepTogether(true);
            }

            // Determine the column span
            int colSpan = 1;
            // Determine the cell being output
            int cellCount = 0;

            while (sc.hasNext()) {
                String cellData = sc.next();
                if (cellData.length() == 0) {
                    ++colSpan;
                    continue;
                }

                // Track the cell count being output
                ++cellCount;

                if (rowCount == 1) {
                    // Parse and validate the style input
                    LOG.debug("Checking style value: " + cellData);
                    if (cellData.startsWith("{") && cellData.endsWith("}")) {
                        String[] style = cellData.substring(1, cellData.length() - 1).split(":");
                        String attribute = style[0].trim();
                        String value = style[1].trim();
                        // Determine the width of each column and store it
                        if ("width".equals(attribute)) {
                            // Validate the width style
                            if (StringUtils.hasAllowedOnly("0123456789%.", value)) {
                                cStyle.put(cellCount, attribute + ": " + value + ";");
                            }
                        } else {
                            LOG.debug("Unsupported style: " + cellData);
                        }
                        canOutput = false;
                    }
                }

                // Output the header
                if (canOutput) {

                    PdfPCell cell = new PdfPCell();
                    cell.setPadding(10);
                    cell.setBorderColor(new Color(100, 100, 100));
                    if ("th".equals(cellType)) {
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
                    }
                    if (colSpan > 1) {
                        cell.setColspan(colSpan);
                    }

                    // Output the data
                    if (" ".equals(cellData) || "".equals(cellData)) {
                        // Put a blank space in blank cells for output consistency
                        cell.addElement(new Chunk(" "));
                        LOG.debug("   OUTPUTTING A BLANK");
                    } else {
                        // Output the cell as a complete wiki
                        float cellWidth = (100.0f / columnCount);
                        parseContent(context, wiki, cellData, document, cell, db, wikiListTodo, wikiListDone,
                                cellWidth);
                        LOG.debug("   OUTPUTTING CONTENT");
                    }
                    pdfTable.addCell(cell);
                }
            }
        }
        // read another line to see if it's part of the table
        line = in.readLine();
    }
    if (pdfTable != null) {
        LOG.debug("document.add(pdfTable)");
        document.add(pdfTable);
        //          document.add(Chunk.NEWLINE);
    }
    return line;
}

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

License:Open Source License

protected static String parseForm(WikiPDFContext context, Connection db, BufferedReader in, String line,
        Document document, PdfPCell cell) throws Exception {
    if (line == null) {
        return line;
    }//from  w w w.ja  v a 2s  . c o  m
    CustomForm form = WikiToHTMLUtils.retrieveForm(in, line);
    LOG.debug("parseForm");
    for (CustomFormGroup group : form) {
        LOG.debug(" group...");
        // Start the table

        PdfPTable pdfTable = new PdfPTable(2);
        pdfTable.setHorizontalAlignment(Element.ALIGN_LEFT);
        pdfTable.setSpacingBefore(10);
        //      pdfTable.setWidthPercentage(100);
        pdfTable.setKeepTogether(true);

        if (group.getDisplay() && StringUtils.hasText(group.getName())) {
            // output the 1st row with a colspan of 2
            if (StringUtils.hasText(group.getName())) {
                Paragraph groupParagraph = new Paragraph(group.getName());
                PdfPCell groupCell = new PdfPCell(groupParagraph);
                groupCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                groupCell.setColspan(2);
                groupCell.setPadding(20);
                groupCell.setBorderColor(new Color(100, 100, 100));
                groupCell.setBackgroundColor(new Color(200, 200, 200));
                groupCell.setNoWrap(true);
                pdfTable.addCell(groupCell);
            }
        }
        for (CustomFormField field : group) {
            LOG.debug("  field...");
            if (field.hasValue()) {
                // output the row (2 columns: label, value)
                Paragraph fieldLabelParagraph = new Paragraph(field.getLabel());
                PdfPCell fieldLabelCell = new PdfPCell(fieldLabelParagraph);
                fieldLabelCell.setPadding(20);
                fieldLabelCell.setBorderColor(new Color(100, 100, 100));
                //          fieldLabelCell.setNoWrap(true);
                pdfTable.addCell(fieldLabelCell);

                Paragraph fieldValueParagraph = new Paragraph(getFieldValue(context, field));
                PdfPCell fieldValueCell = new PdfPCell(fieldValueParagraph);
                fieldValueCell.setPadding(20);
                fieldValueCell.setBorderColor(new Color(100, 100, 100));
                //          fieldValueCell.setNoWrap(true);
                pdfTable.addCell(fieldValueCell);
            }
        }
        LOG.debug("document.add(pdfTable)");
        document.add(pdfTable);

    }
    return null;
}