Example usage for com.lowagie.text Chunk NEWLINE

List of usage examples for com.lowagie.text Chunk NEWLINE

Introduction

In this page you can find the example usage for com.lowagie.text Chunk NEWLINE.

Prototype

Chunk NEWLINE

To view the source code for com.lowagie.text Chunk NEWLINE.

Click Source Link

Document

This is a Chunk containing a newline.

Usage

From source file:checker.ReportWriter.java

License:Open Source License

private void writePdfReport(ArrayList<String> text, String fileName) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();/*from   w  ww  .  j  a v a  2  s . com*/
    document.addTitle(getTitle());

    Paragraph paragraph = new Paragraph();
    for (String line : text) {
        if (line.equals("")) {
            paragraph.add(Chunk.NEWLINE);
        } else {
            paragraph.add(line);
            paragraph.add(Chunk.NEWLINE);
        }
    }
    document.add(paragraph);
    /*List list = new List(false);
    for (String line : text) {
       if (line.equals("")) {
    document.add(list);
    list = new List(false);
       } 
       else {
    list.add(new ListItem(line));
       }
    }*/
    //document.add(list);
    document.close();
}

From source file:classroom.filmfestival_b.Movies09.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // step 1/*from   ww w.j a  v  a2  s  . co  m*/
    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();

        ColumnText column = new ColumnText(writer.getDirectContent());
        column.setSimpleColumn(document.left(), document.bottom(), document.right(), document.top());

        float pos;
        int status;
        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)) {
                document.newPage();
                column.setText(null);
                column.setYLine(document.top());
            } 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.Movies10.java

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

    // step 1/*from  ww  w  . j  ava  2 s  . com*/
    Document document = new Document();
    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);
        // 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.Movies11.java

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

    // step 1/*w ww  .  ja v  a2s.  c om*/
    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:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

public static void convertHSSF2Pdf(Workbook wb, String header, File reportFile) throws Exception {
    assert wb != null;
    assert reportFile != null;

    //Precompute formula
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);//from   w  w w.j a va 2 s . c  o m

        for (Row r : sheet) {
            for (Cell c : r) {
                if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                    try {
                        evaluator.evaluateFormulaCell(c);
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                }
            }
        }
    }

    File tmp = File.createTempFile("tmp_", ".xlsx");
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) {
        wb.write(out);
    }

    //Find page orientation
    int maxColumnsGlobal = 0;
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            maxColumnsGlobal = Math.max(maxColumnsGlobal, row.getLastCellNum());
        }
    }

    Rectangle pageSize = maxColumnsGlobal < 10 ? PageSize.A4 : PageSize.A4.rotate();
    Document pdfDocument = new Document(pageSize, 10f, 10f, 20f, 20f);

    PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(reportFile));
    addHeader(writer, header);
    pdfDocument.open();
    //we have two columns in the Excel sheet, so we create a PDF table with two columns
    //Note: There are ways to make this dynamic in nature, if you want to.
    //Loop through sheets
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);

        //Loop through rows, to find number of columns
        int minColumns = 1000;
        int maxColumns = 0;
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            if (row.getFirstCellNum() >= 0)
                minColumns = Math.min(minColumns, row.getFirstCellNum());
            if (row.getLastCellNum() >= 0)
                maxColumns = Math.max(maxColumns, row.getLastCellNum());
        }
        if (maxColumns == 0)
            continue;

        //Loop through first rows, to find relative width
        float[] widths = new float[maxColumns];
        int totalWidth = 0;
        for (int c = 0; c < maxColumns; c++) {
            int w = sheet.getColumnWidth(c);
            widths[c] = w;
            totalWidth += w;
        }

        for (int c = 0; c < maxColumns; c++) {
            widths[c] /= totalWidth;
        }

        //Create new page and a new chapter with the sheet's name
        if (sheetNo > 0)
            pdfDocument.newPage();
        Chapter pdfSheet = new Chapter(sheet.getSheetName(), sheetNo + 1);

        PdfPTable pdfTable = null;
        PdfPCell pdfCell = null;
        boolean inTable = false;

        //Loop through cells, to create the content
        //         boolean leftBorder = true;
        //         boolean[] topBorder = new boolean[maxColumns+1];
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);

            //Check if we exited a table (empty line)
            if (row == null) {
                if (pdfTable != null) {
                    addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
                    pdfTable = null;
                }
                inTable = false;
                continue;
            }

            //Check if we start a table (>MIN_COL_IN_TABLE columns)
            if (row.getLastCellNum() >= MIN_COL_IN_TABLE) {
                inTable = true;
            }

            if (!inTable) {
                //Process the data outside table, just add the text
                boolean hasData = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
                        continue;
                    Chunk chunk = getChunk(wb, cell);
                    pdfSheet.add(chunk);
                    pdfSheet.add(new Chunk(" "));
                    hasData = true;
                }
                if (hasData)
                    pdfSheet.add(Chunk.NEWLINE);

            } else {
                //Process the data in table
                if (pdfTable == null) {
                    //Create table
                    pdfTable = new PdfPTable(maxColumns);
                    pdfTable.setWidths(widths);
                    //                  topBorder = new boolean[maxColumns+1];
                }

                int cellNumber = minColumns;
                //               leftBorder = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    for (; cellNumber < cell.getColumnIndex(); cellNumber++) {
                        pdfCell = new PdfPCell();
                        pdfCell.setBorder(0);
                        pdfTable.addCell(pdfCell);
                    }

                    Chunk phrase = getChunk(wb, cell);
                    pdfCell = new PdfPCell(new Phrase(phrase));
                    pdfCell.setFixedHeight(row.getHeightInPoints() - 3);
                    pdfCell.setNoWrap(!cell.getCellStyle().getWrapText());
                    pdfCell.setPaddingLeft(1);
                    pdfCell.setHorizontalAlignment(
                            cell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER ? PdfPCell.ALIGN_CENTER
                                    : cell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT
                                            ? PdfPCell.ALIGN_RIGHT
                                            : PdfPCell.ALIGN_LEFT);
                    pdfCell.setUseBorderPadding(false);
                    pdfCell.setUseVariableBorders(false);
                    pdfCell.setBorderWidthRight(cell.getCellStyle().getBorderRight() == 0 ? 0 : .5f);
                    pdfCell.setBorderWidthBottom(cell.getCellStyle().getBorderBottom() == 0 ? 0
                            : cell.getCellStyle().getBorderBottom() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthLeft(cell.getCellStyle().getBorderLeft() == 0 ? 0
                            : cell.getCellStyle().getBorderLeft() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthTop(cell.getCellStyle().getBorderTop() == 0 ? 0
                            : cell.getCellStyle().getBorderTop() > 1 ? 1 : .5f);
                    String color = cell.getCellStyle().getFillForegroundColorColor() == null ? null
                            : ((XSSFColor) cell.getCellStyle().getFillForegroundColorColor()).getARGBHex();
                    if (color != null)
                        pdfCell.setBackgroundColor(new Color(Integer.decode("0x" + color.substring(2))));
                    pdfTable.addCell(pdfCell);
                    cellNumber++;
                }
                for (; cellNumber < maxColumns; cellNumber++) {
                    pdfCell = new PdfPCell();
                    pdfCell.setBorder(0);
                    pdfTable.addCell(pdfCell);
                }
            }

            //Custom code to add all images on the first sheet (works for reporting)
            if (sheetNo == 0 && row.getRowNum() == 0) {
                for (PictureData pd : wb.getAllPictures()) {
                    try {
                        Image pdfImg = Image.getInstance(pd.getData());
                        pdfImg.scaleToFit(
                                pageSize.getWidth() * .8f - pageSize.getBorderWidthLeft()
                                        - pageSize.getBorderWidthRight(),
                                pageSize.getHeight() * .8f - pageSize.getBorderWidthTop()
                                        - pageSize.getBorderWidthBottom());
                        pdfSheet.add(pdfImg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (pdfTable != null) {
            addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
        }

        pdfDocument.add(pdfSheet);
    }
    pdfDocument.close();

}

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

License:Open Source License

private static void addTitlePage() {
    Paragraph preface = new Paragraph();
    // We add one empty line
    preface.add(Chunk.NEWLINE);
    // Lets write a big header
    preface.add(new Paragraph("MAC Response", chapterTitleFont));

    preface.add(Chunk.NEWLINE);/*from  w  w w.  j a va 2 s.c o m*/
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            contentFont));
    preface.add(Chunk.NEWLINE);
    preface.add(Chunk.NEWLINE);
    preface.add(Chunk.NEWLINE);
    preface.add(new Paragraph("This document describes something which is very important ", contentFont));

    document.add(new RtfParagraph(document, preface));
    // Start a new page
    // TODO Paul do this again
    //document.newPage();
}

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

License:Open Source License

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
    /*/*from   w w  w  . ja  va2 s  .  c o  m*/
    if("ol".equals(qName) || "ul".equals(qName) || "li".equals(qName)) {
       System.err.print(qName + " ");
    }
     */
    currentSaxElemId = saxElemIdCounter;

    Map<String, String> attrMap = new HashMap<String, String>();
    // parse attributes
    for (int ai = 0; ai < attributes.getLength(); ai++) {
        attrMap.put(attributes.getQName(ai), attributes.getValue(ai));
    }
    String idAttr = attrMap.get("id");
    if (idAttr == null) {
        idAttr = "";
    }
    String className = attrMap.get("class");
    if (className == null) {
        className = "";
    }
    SaxElement sE = new SaxElement(qName, saxElemIdCounter++, className, idAttr, currentITextStyle);
    //printlnerr("startElement: " + sE.toString());
    saxElementStack.push(sE);

    try {
        if (attrMap.get("class") != null) {
            String[] elemClasses = attrMap.get("class").split(" ");

            for (String eClass : elemClasses) {

                StyleSpecText classTextStyles = styleMap.getTextStyleSpecFor(qName, eClass);
                if (classTextStyles != null) {
                    sE.applyTextStyles(classTextStyles);
                }

            }
        }
        if (attrMap.get("style") != null) {
            // TODO this needs more thought, and careful tracking of which tags are still open, etc.
            //String styleSource = attrMap.get("style");
            //CssStyleMap styleTagStyles = cssParser.getStylesFromStyleTag(styleSource);
            // ...
        }
        if (sE.textStyles == null) {
            try {
                int stackSize = saxElementStack.size();
                if (stackSize > 1) {
                    SaxElement enclosingElement = saxElementStack.elementAt(stackSize - 2);
                    StyleSpecText enclosingSST = enclosingElement.textStyles;
                    if (enclosingSST != null)
                        sE.applyTextStyles(enclosingSST);
                }
            } catch (Exception e) {
            }
        }

        StyleSpecText currentTextStyles = sE.textStyles;
        if (currentTextStyles != null) {
            if (currentTextStyles.isBold()) {
                currentITextStyle |= Font.BOLD;
            }
            if (currentTextStyles.isItalic()) {
                currentITextStyle |= Font.ITALIC;
            }
        }

        //System.err.println("PUSH -> " + saxElementStack);

        previousTag = currentTag;
        currentTag = qName;
        if (document.isOpen()) {
            if (XhtmlTags.NEWLINE.equals(qName)) {
                if (stack.size() > 0) {
                    TextElementArray currentTEA = (TextElementArray) stack.peek();
                    currentTEA.add(Chunk.NEWLINE);
                } else if (specialParagraph != null) {
                    specialParagraph.add(Chunk.NEWLINE);
                }
            }

            updateStack();

            String xmlElementId = attrMap.get("id");

            if (XhtmlTags.ANCHOR.equals(qName)) {
                //concession to nonconformists...
                if (xmlElementId == null) {
                    xmlElementId = attrMap.get("name");
                }
                Anchor anchor = textFactory.newAnchor();
                String ref = attrMap.get(XhtmlTags.REFERENCE);

                if (ref != null) {
                    int aNameStartIdx = ref.lastIndexOf("#") + 1;
                    ref = ref.substring(aNameStartIdx);
                    anchor.setReference(ref);
                }
                if (xmlElementId != null) {
                    anchor.setName(xmlElementId);
                }
                pushToStack(anchor);
            } else {
                if (xmlElementId != null) {
                    //flushStack();
                    Anchor dest = textFactory.newAnchor();
                    dest.setName(xmlElementId);
                    pushToStack(dest);
                    //flushStack();
                }
                for (int i = 0; i < 6; i++) {
                    if (XhtmlTags.H[i].equals(qName)) {
                        flushStack();
                        freshParagraph = true;
                        currentITextStyle |= Font.BOLD;
                        specialParagraph = textFactory.newHeadline(i + 1);
                        return;
                    }
                }
                if ("blockquote".equals(qName)) {
                    flushStack();
                    freshParagraph = true;
                    Paragraph p = textFactory.newParagraph();
                    p.setIndentationLeft(50);
                    p.setIndentationRight(20);
                    p.setAlignment(defaultAlignment);
                    pushToStack(p);
                } else if (XhtmlTags.PARAGRAPH.equals(qName)) {
                    flushStack();
                    freshParagraph = true;
                    Paragraph p = textFactory.newParagraph();
                    pushToStack(p);
                } else if (XhtmlTags.DIV.equals(qName)) {
                    if (stack.size() > 0 && stack.peek().getChunks().size() > 0) {
                        flushStack();
                    }
                    if (stack.size() == 0) {
                        Paragraph brandNewParagraph = textFactory.newParagraph();
                        pushToStack(brandNewParagraph);
                        freshParagraph = true;
                    }
                } else if (XhtmlTags.PRE.equals(qName)) {
                    flushStack();
                    freshParagraph = true;
                    Paragraph p = textFactory.newParagraphPre();
                    pushToStack(p);
                } else if (XhtmlTags.ORDEREDLIST.equals(qName)) {
                    flushStack();
                    List oList = new List(List.ORDERED, 10);
                    pushToStack(oList);
                } else if (XhtmlTags.UNORDEREDLIST.equals(qName)) {
                    flushStack();
                    List uList = new List(List.UNORDERED, 10);
                    pushToStack(uList);
                } else if (XhtmlTags.LISTITEM.equals(qName)) {
                    freshParagraph = true;
                    ListItem listItem = new ListItem();
                    pushToStack(listItem);
                } else if (XhtmlTags.IMAGE.equals(qName)) {
                    handleImage(attributes);
                } else if (qName != null && qName.endsWith("image")) {
                    handleSvgImage(attributes);
                } else if (XhtmlTags.LINK.equals(qName)) {
                    // if it's a stylesheet, parse it & update current-style
                    if ("stylesheet".equals(attrMap.get("rel")) && "text/css".equals(attrMap.get("type"))
                            && attrMap.get("href") != null) {
                        String cssHref = xhtmlDir.getAbsoluteFile().toURI().toString() + attrMap.get("href");
                        CssStyleMap stylesFromLink = cssParser.getStylesFromFileURI(cssHref);
                        if (stylesFromLink != null) {
                            styleMap.updateWith(stylesFromLink);
                        }
                    }
                } else if (XhtmlTags.STYLE.equals(qName)) {
                    inStyleTag = true;
                } 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.BODY.equals(qName)) {
            document.open();
            freshParagraph = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //printlnerr("leaving startElement " + localName + "; stack: " + stackStatus());
}

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 v a2 s .  co m*/
    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 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 a2  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.nokia.s60tools.swmtanalyser.wizards.ReportCreationJob.java

License:Open Source License

private void addComments(Document document) throws DocumentException {
    //Create new line
    document.add(Chunk.NEWLINE);
    //Comments heading
    Paragraph comments_title = new Paragraph("User given comments", fontHeading1);
    document.add(comments_title);/*w  ww. ja  v  a2 s. com*/

    Paragraph comments = new Paragraph(this.comment, fontNormal);
    document.add(comments);
}