Example usage for com.itextpdf.text Document add

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

Introduction

In this page you can find the example usage for com.itextpdf.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.pdf.GetPdf.java

public static void docConvert(Document document, String url, String type)
        throws IOException, DocumentException {
    WordExtractor we;/*from w  ww.  j av a  2 s.c  o  m*/

    if (type.equals("doc")) {
        HWPFDocument wordDoc = new HWPFDocument(new URL(url).openStream());
        we = new WordExtractor(wordDoc);
        String[] paragraphs = we.getParagraphText();
        for (int i = 0; i < paragraphs.length; i++) {
            paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
            document.add(new Paragraph(paragraphs[i]));
        }
    } else {
        XWPFDocument wordDoc = new XWPFDocument(new URL(url).openStream());
        List<IBodyElement> contents = wordDoc.getBodyElements();

        for (IBodyElement content : contents) {
            if (content.getElementType() == BodyElementType.PARAGRAPH) {
                List<XWPFParagraph> paras = content.getBody().getParagraphs();
                for (XWPFParagraph para : paras) {
                    document.add(new Paragraph(para.getParagraphText()));
                }

            } else if (content.getElementType() == BodyElementType.TABLE) {
                List<XWPFTable> tables = content.getBody().getTables();
                for (XWPFTable table : tables) {
                    List<XWPFTableRow> rows = table.getRows();
                    for (XWPFTableRow row : rows) {
                        List<XWPFTableCell> tablecells = row.getTableCells();
                    }
                }
            }

        }
    }

}

From source file:com.pdfwriter.PrintInventoryReport.java

public void create(ObservableList list, String totalSales) {
    try {/*from   w w w .ja  v a 2s.  c o m*/
        Document document = new Document(PageSize.LETTER);
        document.setMargins(1, 1, 1, 1);

        PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        Font font2 = new Font(Font.FontFamily.UNDEFINED, 10, Font.BOLD);
        PdfPTable table = new PdfPTable(5);
        table.setWidthPercentage(95);
        table.setWidths(new int[] { 40, 40, 40, 40, 40 });
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("", font2));
        cell.setBorder(0);
        cell.setColspan(8);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(0);

        cell.setBorderWidthBottom(0);
        table.addCell(cell);

        cell = new PdfPCell(
                new Phrase("KELNOVI SHOPPING BOTIQUE", new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD)));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Pondol,Loon, Bohol", new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD)));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Phone/Fax#:000-000-000", new Font(Font.FontFamily.UNDEFINED, 9, Font.UNDERLINE)));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(" "));
        cell.setColspan(10);
        cell.setRowspan(3);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("SALES REPORT", new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD)));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(" "));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("NO."));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(14);
        cell.setBackgroundColor(BaseColor.GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("PRODUCT NAME"));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(14);
        cell.setBackgroundColor(BaseColor.GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("PRICE"));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(14);
        cell.setBackgroundColor(BaseColor.GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("QUANTITY"));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(14);
        cell.setBackgroundColor(BaseColor.GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("AMOUNT PAYABLE"));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(14);
        cell.setBackgroundColor(BaseColor.GRAY);
        table.addCell(cell);

        for (int i = 0; i < list.size(); i++) {
            it = (ProductClass) list.get(i);

            cell = new PdfPCell(new Phrase("" + it.idProperty().get()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(14);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("" + it.productDescriptionProperty().get()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(14);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("" + it.productPriceProperty().get()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(14);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("" + it.productQtyProperty().get()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(14);
            table.addCell(cell);
            //totalSales.setText(String.format("%,.2f",globalSales));

            cell = new PdfPCell(new Phrase(
                    String.format("%,.2f", Double.parseDouble(it.productTotalSalesProperty().get()))));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(14);
            table.addCell(cell);

        }

        cell = new PdfPCell(new Phrase(" "));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(" "));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("TOTAL AMOUNT PAYABLE:"));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Php " + totalSales, new Font(Font.FontFamily.UNDEFINED, 14, Font.UNDERLINE)));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(" "));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Approved by:"));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("MICHAEL NOVI MALUENDA II",
                new Font(Font.FontFamily.UNDEFINED, 14, Font.UNDERLINE)));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("General Manager"));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(" "));
        cell.setColspan(10);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(0);
        table.addCell(cell);

        document.add(table);
        document.close();
        openFile();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.pdg.ticket.utils.FirstPdf.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//from  w ww .  ja  v a2  s  .  c  o m
    // Lets write a big header
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    // 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$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ", smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-).",
            redFont));

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

From source file:com.pdg.ticket.utils.FirstPdf.java

private static void addContent(Document document) throws DocumentException {
    Anchor anchor = new Anchor("First Chapter", catFont);
    anchor.setName("First Chapter");

    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Subcategory 1", subFont);
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Hello"));

    subPara = new Paragraph("Subcategory 2", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Paragraph 1"));
    subCatPart.add(new Paragraph("Paragraph 2"));
    subCatPart.add(new Paragraph("Paragraph 3"));

    // Add a list
    //createList(subCatPart);
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);/*from   ww w.  j  a v  a 2  s .co m*/
    subCatPart.add(paragraph);

    // Add a table
    createTable(subCatPart);

    // Now add all this to the document
    document.add(catPart);

    //      // Next section
    //      anchor = new Anchor("Second Chapter", catFont);
    //      anchor.setName("Second Chapter");
    //
    //      // Second parameter is the number of the chapter
    //      catPart = new Chapter(new Paragraph(anchor), 1);
    //
    //      subPara = new Paragraph("Subcategory", subFont);
    //      subCatPart = catPart.addSection(subPara);
    //      subCatPart.add(new Paragraph("This is a very important message"));
    //
    //      // Now add all this to the document
    //      document.add(catPart);

}

From source file:com.pdi.util.PdfGenerator.java

public static void generarPresupuesto(String lugar, Date fecha, float cantidad, String tipo, Cliente cliente,
        float precio, Aliado aliado, String path) {

    try {/*from   w w w  .j ava2 s  .  com*/

        NEGRITA_12_VERDE.setColor(145, 189, 57);

        long miliSemana = System.currentTimeMillis() + (86400 * 7 * 1000);
        Date vtoPresup = new Date(miliSemana);
        float precioPers = precio / cantidad;
        int precioTotalInt = Math.round(precio);
        int precioPersInt = Math.round(precioPers);
        int cantPersonasInt = Math.round(cantidad);

        //Referencia al objeto Doc
        Document document = new Document(PageSize.A4, //Dimensiones
                36, //margIzq
                36, //margDer
                36, //margenSup
                36); // margenInf

        //Creamos el archivo fisico
        FileOutputStream salida = new FileOutputStream(path);

        //Referencia e inicializacion del objeto que "escribe" el PDF
        PdfWriter writer = PdfWriter.getInstance(document, salida);
        writer.setInitialLeading(0);

        //Imagen Logo
        Image logoPDI = Image.getInstance("Logo PDI.png");
        logoPDI.scaleToFit(215, 205);
        logoPDI.setAlignment(Chunk.ALIGN_LEFT);
        //image.setAbsolutePosition(200, 200);

        //Imagen QR
        Image qr = Image.getInstance("QR PDI.png");
        qr.scaleToFit(211, 165);
        qr.setAbsolutePosition(295, PageSize.A4.getHeight() - 390);

        //Parrafo info evento
        Paragraph infoEvento = new Paragraph();
        infoEvento.add(new Chunk("Informacin del Evento", NEGRITA_SUB_12));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.add(negritaNormal("Solicitante: ", cliente.toString()));
        infoEvento.add(negritaNormal("Evento: ", tipo));
        infoEvento.add(negritaNormal("Cantidad de personas: ", Integer.toString(cantPersonasInt)));
        infoEvento.add(negritaNormal("Fecha: ", General.formatoFecha.format(fecha)));
        infoEvento.add(negritaNormal("Lugar:  ", lugar));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Modalidad del Servicio
        Paragraph modalidadServicio = new Paragraph();
        modalidadServicio.add(new Chunk("Modalidad Servicio Integral", NEGRITA_SUB_12));
        modalidadServicio.add(Chunk.NEWLINE);
        modalidadServicio.add(new Chunk("Nuestro servicio incluye la totalidad de lo referido a"
                + " los elementos necesarios para el despacho de bebidas: Barras, Bartenders,"
                + " Artculos de Coctelera, Insumos de calidad para los tragos y Mucha Buena Onda."
                + " Con esta modalidad aseguramos la expedicin de "
                + "los tragos desde las 00hs hasta las 05hs, para que se desentiendan del asunto "
                + "y disfruten al mximo.", NORMAL_12));
        modalidadServicio.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Ver Carta
        Paragraph verCarta = new Paragraph();
        verCarta.add(negritaNormal("\u2022 Carta de Tragos: ", "Ver archivo adjunto."));
        verCarta.setIndentationLeft(20);
        verCarta.add(Chunk.NEWLINE);
        verCarta.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Titulo Info Contratacion
        Paragraph infoContratacionTitulo = new Paragraph();
        infoContratacionTitulo.add(new Chunk("Informacin de Contratacin", NEGRITA_SUB_12));
        infoContratacionTitulo.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Inf de Contratacion
        Paragraph infoContratacion = new Paragraph();
        infoContratacion.add(negritaNormal("\u2022 Mtodo de contratacin y reserva de la fecha: ",
                "A travs de contrato firmado por ambas partes. "));
        Phrase lineaCosto = new Phrase();
        lineaCosto.add(new Chunk("\u2022 Costo: ", NEGRITA_12));
        lineaCosto.add(new Chunk("$" + Integer.toString(precioPersInt) + " ", NEGRITA_14));
        lineaCosto.add(new Chunk("por persona ", NEGRITA_12));
        lineaCosto.add(new Chunk("(Total: $" + Integer.toString(precioTotalInt) + ")", NEGRITA_14));
        infoContratacion.add(lineaCosto);
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.add(negritaNormal("\u2022 Forma de Pago : ",
                "50% al momento de la firma del contrato y 50% como mximo una semana antes del evento. "));
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.setIndentationLeft(20);
        infoContratacion.setFirstLineIndent(0);
        infoContratacion.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Despedida
        Paragraph despedida = new Paragraph();
        despedida.add(new Phrase("Quedamos al aguardo de tus comentarios,", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(new Phrase("Muchas Gracias.", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(Chunk.NEWLINE);
        despedida.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Firma
        Paragraph firma = new Paragraph();
        firma.add(new Phrase("Piel de Iguana Tragos.-", NEGRITA_CUR_14));
        firma.add(Chunk.NEWLINE);
        firma.add(new Phrase("Cel.: 3462-15337860", NEGRITA_12_VERDE));
        firma.setAlignment(Paragraph.ALIGN_RIGHT);

        float llxLink = 279;
        float llyLink = PageSize.A4.getHeight() - 145;
        float anchoLink = 199;
        float altoLink = 16;

        //Link al facebook
        URL urlPDI = new URL("https://www.facebook.com/pieldeiguanatragos.vt");
        PdfAction irAlFace = new PdfAction(urlPDI);
        Rectangle linkLocation = new Rectangle(llxLink, llyLink, llxLink + anchoLink, llyLink + altoLink);
        PdfAnnotation link = PdfAnnotation.createLink(writer, linkLocation, PdfAnnotation.HIGHLIGHT_NONE,
                irAlFace);
        link.setBorder(new PdfBorderArray(0, 0, 0));
        writer.addAnnotation(link);

        //Espacios Vacios
        Paragraph dosEspacios = new Paragraph();
        dosEspacios.add(Chunk.NEWLINE);
        dosEspacios.add(Chunk.NEWLINE);

        //Hay que abrir el Documento, llenarlo con los elemntos creados
        //en el orden que queremos y cerrarlo
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        ColumnText ct = new ColumnText(cb);
        Phrase recuadro = new Phrase();
        recuadro.add(new Chunk("Piel de Iguana Tragos", NEGRITA_SUB_14));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Servicio de tragos para eventos", NEGRITA_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("\"Piel de Iguana, para que tu noche nica sea inigualable.\"", NORMAL_CUR_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        Image logoFB = Image.getInstance("Icono FB.png");
        logoFB.scaleToFit(13, 13);
        recuadro.add(new Chunk(logoFB, 0, -3));
        recuadro.add(new Chunk("/pieldeiguanatragos.vt  -> Click Aqu!", NORMAL_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Vencimiento del Prepuesto " + General.formatoFecha.format(vtoPresup),
                NORMAL_SUB_12));

        float llx = 279;
        float lly = PageSize.A4.getHeight() - 185;
        float ancho = 228;
        float alto = 150;

        ct.setSimpleColumn(recuadro, //Texto
                llx, //punta inf izquierda (x)
                lly, //punta inf izquierda (y) PageSize.A4.getHeight() - 185
                llx + ancho, //ancho del cuadro
                lly + alto, // alto del cuadro
                15, //espaciado
                Element.ALIGN_LEFT // Alineacion
        );

        ct.go();

        document.add(logoPDI);
        document.add(qr);
        document.add(dosEspacios);
        document.add(infoEvento);
        document.add(modalidadServicio);
        document.add(verCarta);
        document.add(infoContratacionTitulo);
        document.add(infoContratacion);
        document.add(despedida);
        document.add(firma);
        document.close();
        System.out.println("Archivo creado");
        int rta = JOptionPane.showConfirmDialog(VentanaMaestra.eventosCurrent,
                "Se guard el presupesto en:\n" + path + "\nDesea abrirlo?", "Presupuesto guardado",
                JOptionPane.YES_NO_OPTION);

        if (rta == JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
                try {
                    File myFile = new File(path);
                    Desktop.getDesktop().open(myFile);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                            "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                            "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                        "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                        "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
            }

        }

    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (DocumentException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (IOException ex) {
        System.out.println("Error: " + ex.toString());
    }

}

From source file:com.pearson.controller.PdfGentrate.java

public static void main(String[] args) {

    try {/* www  . j  a va 2 s .  c  o m*/
        /*Document document = new Document(PageSize.
        A4, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance
        (document, new FileOutputStream("C:\\my.pdf"));
        document.open();               
        // create a chunk object using chunk class  of itext library.
        Chunk underlined = new Chunk("Welcome to Pearson Q-Service Portal : ");   
        // set the distance between text and line.
        underlined.setTextRise(8.0f);      
        // set the width of the line, 'y' position,  color and design of the line
        underlined.setUnderline(new Color(0x00, 0x00, 0xFF),0.0f, 0.2f, 3.0f, 0.0f, PdfContentByte.LINE_CAP_PROJECTING_SQUARE);      // finally add object to the document.
        document.add(underlined);
        document.add(new Paragraph("Hi username",
        FontFactory.getFont(FontFactory.COURIER, 14, 
        Font.BOLD, new Color(255, 150, 200))));;
                 
                
             document.add(new Paragraph("Tiltle",catFont));
             document.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
               smallBold));
             document.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
               redFont));
                     
             PdfPTable table = new PdfPTable(3); // 3 columns.   
            table.setWidthPercentage(100); //Width 100%     
            table.setSpacingBefore(10f); //Space before table    
             table.setSpacingAfter(10f); //Space after table         //Set Column widths     
            float[] columnWidths = {1f, 1f, 1f};     
            table.setWidths(columnWidths);    
            PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));     
            cell1.setBorderColor(BaseColor.BLUE);     
            cell1.setPaddingLeft(10);     
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);     
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);    
            PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));    
          cell2.setBorderColor(BaseColor.GREEN);    
          cell2.setPaddingLeft(10);    
          cell2.setHorizontalAlignment(Element.ALIGN_CENTER);      
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);      
            PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));   
            cell3.setBorderColor(BaseColor.RED);      
            cell3.setPaddingLeft(10);      
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);    
          cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);   
            //To avoid having the cell border and the content overlap, if you are having thick cell borders     
            //cell1.setUserBorderPadding(true);     
            //cell2.setUserBorderPadding(true);   
            //cell3.setUserBorderPadding(true);   
            table.addCell(cell1);   
          table.addCell(cell2);   
          table.addCell(cell3);     
             document.add(table);     
             document.close();     
             writer.close();
                    
                  
                
        document.close();
        } 
        catch (Exception e2) {
        System.out.println(e2.getMessage());
        }
        }*/

        Document document = new Document();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTableExample.pdf"));
        document.open();
        PdfPTable table = new PdfPTable(3); // 3 columns.      
        table.setWidthPercentage(100); //Width 100%       
        table.setSpacingBefore(10f); //Space before table    
        table.setSpacingAfter(10f); //Space after table         //Set Column widths     
        float[] columnWidths = { 1f, 1f, 1f };
        table.setWidths(columnWidths);
        PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPaddingLeft(10);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
        cell2.setBorderColor(BaseColor.GREEN);
        cell2.setPaddingLeft(10);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
        cell3.setBorderColor(BaseColor.RED);
        cell3.setPaddingLeft(10);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
        //To avoid having the cell border and the content overlap, if you are having thick cell borders        //cell1.setUserBorderPadding(true);        //cell2.setUserBorderPadding(true);   
        //cell3.setUserBorderPadding(true);    
        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        document.add(table);
        document.close();
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.photon.phresco.framework.docs.impl.DocumentUtil.java

License:Apache License

/**
 * Adds title section./*from  w  w w  .j  a  v  a 2 s. c o m*/
 * @param info the project info object
 * @return PDF input stream
 * @throws PhrescoException 
 */
public static InputStream getTitleSection(ApplicationInfo info) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug(" Entering Method DocumentUtil.getTitleSection(ProjectInfo info)");
    }
    if (isDebugEnabled) {
        S_LOGGER.debug("getTitleSection() projectCode=" + info.getCode());
    }
    try {
        //create output stream
        com.itextpdf.text.Document docu = new com.itextpdf.text.Document();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfWriter.getInstance(docu, os);
        docu.open();

        //add standard title section with supplied info object
        Paragraph paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setFont(DocConstants.TITLE_FONT);
        addBlankLines(paragraph, MAGICNUMBER.DOCLINES);
        paragraph.add(info.getName());
        addBlankLines(paragraph, MAGICNUMBER.BLANKLINESFOUR);
        docu.add(paragraph);

        paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        addBlankLines(paragraph, MAGICNUMBER.DOCLINES);
        String techName = info.getTechInfo().getName();
        if (StringUtils.isNotEmpty(info.getTechInfo().getVersion())) {
            paragraph.add(techName + " - " + info.getTechInfo().getVersion());
        } else {
            paragraph.add(techName);
        }
        docu.add(paragraph);

        paragraph = new Paragraph();
        addBlankLines(paragraph, MAGICNUMBER.DOCLINES);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.add(DocumentMessages.getString("Documents.version.name") + getVersion(info)); //$NON-NLS-1$
        addBlankLines(paragraph, MAGICNUMBER.BLANKLINESSEVEN);
        docu.add(paragraph);

        if (StringUtils.isNotEmpty(info.getDescription())) {
            paragraph = new Paragraph();
            paragraph.setAlignment(Element.ALIGN_RIGHT);
            paragraph.setFont(DocConstants.DESC_FONT);
            paragraph.setFirstLineIndent(MAGICNUMBER.BLANKLINESEIGHT);
            docu.add(paragraph);

        }

        docu.close();

        //Create an inputstream to return.
        return new ByteArrayInputStream(os.toByteArray());
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }

}

From source file:com.photon.phresco.framework.docs.impl.DocumentUtil.java

License:Apache License

/**
 * Creates and returns PDF input stream for the supplied string.
 * @param string to be printed in the PDF
 * @return PDF input stream./*  ww w  . jav a 2 s .c o  m*/
 * @throws PhrescoException
 */
public static InputStream getStringAsPDF(String string) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method DocumentUtil.getStringAsPDF(String string)");
    }
    try {
        com.itextpdf.text.Document docu = new com.itextpdf.text.Document();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfWriter.getInstance(docu, os);
        docu.open();
        Paragraph paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_LEFT);
        paragraph.setFirstLineIndent(MAGICNUMBER.INDENTLINE);
        paragraph.add("\n"); //$NON-NLS-1$
        paragraph.add(string);
        paragraph.add("\n\n"); //$NON-NLS-1$
        docu.add(paragraph);

        docu.close();

        //Create an inputstream to return.
        return new ByteArrayInputStream(os.toByteArray());
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }

}

From source file:com.photon.phresco.framework.docs.impl.DocumentUtil.java

License:Apache License

private static void updateDoc(List<ArtifactGroup> modules, com.itextpdf.text.Document docu, PdfWriter writer,
        String moduleName) throws PhrescoException {
    try {/*from  www.j  a  v  a 2 s  . co m*/
        Paragraph para = new Paragraph();
        para.setAlignment(Element.ALIGN_CENTER);
        para.setFont(DocConstants.BODY_FONT);
        para.setFont(DocConstants.CATEGORY_FONT);
        para.add(moduleName);
        addBlankLines(para, MAGICNUMBER.BLANKLINESTWO);
        docu.add(para);

        for (ArtifactGroup artifactGroup : modules) {
            para = new Paragraph();
            para.setFont(DocConstants.CATEGORY_FONT);
            para.add(artifactGroup.getName());
            docu.add(para);

            if (StringUtils.isNotEmpty(artifactGroup.getDescription())) {
                para = new Paragraph();
                para.setFont(DocConstants.BODY_FONT);
                para.add(artifactGroup.getDescription());
                addBlankLines(para, 2);
                docu.add(para);
            }
            //          Documentation document = tupleBean.getDoc(DocumentationType.DESCRIPTION);
            //          if (document != null) {
            //              if(!StringUtils.isEmpty(document.getUrl())){
            //                  PdfInput convertToPdf = DocConvertor.convertToPdf(document.getUrl());
            //                  if(convertToPdf != null) {
            //                      DocumentUtil.addPages(convertToPdf.getInputStream(), writer, docu);
            //                  }
            //              } else {
            //                  para = new Paragraph();
            //                  para.setFont(DocConstants.BODY_FONT);
            //                  para.add(document.getContent());
            //                  addBlankLines(para, 2);
            //                  docu.add(para);
            //              }
            //          }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }
}

From source file:com.photon.phresco.service.docs.impl.DocumentUtil.java

License:Apache License

/**
 * Adds title section./*from w ww.j  av  a 2  s  . co  m*/
 * @param info the project info object
 * @return PDF input stream
 * @throws DocumentException
 */
public static InputStream getTitleSection(ProjectInfo info) throws DocumentException {
    if (isDebugEnabled) {
        S_LOGGER.debug(" Entering Method DocumentUtil.getTitleSection(ProjectInfo info)");
    }
    if (isDebugEnabled) {
        S_LOGGER.debug("getTitleSection() projectCode=" + info.getCode());
    }
    //create output stream
    com.itextpdf.text.Document docu = new com.itextpdf.text.Document();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PdfWriter.getInstance(docu, os);
    docu.open();

    //add standard title section with supplied info object
    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.setFont(DocConstants.TITLE_FONT);
    addBlankLines(paragraph, 10);
    paragraph.add(info.getName());
    addBlankLines(paragraph, 4);
    docu.add(paragraph);

    paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_CENTER);
    addBlankLines(paragraph, 10);
    String techName = info.getTechnology().getName();
    if (info.getTechnology().getVersions() != null) {
        paragraph.add(techName + " - " + info.getTechnology().getVersions().get(0));
    } else {
        paragraph.add(techName);
    }
    docu.add(paragraph);

    paragraph = new Paragraph();
    addBlankLines(paragraph, 10);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.add(DocumentMessages.getString("Documents.version.name") + getVersion(info)); //$NON-NLS-1$
    addBlankLines(paragraph, 7);
    docu.add(paragraph);
    paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_RIGHT);
    paragraph.setFont(DocConstants.DESC_FONT);
    paragraph.setFirstLineIndent(8);
    paragraph.add(info.getDescription());
    docu.add(paragraph);

    docu.close();

    //Create an inputstream to return.
    return new ByteArrayInputStream(os.toByteArray());

}