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:demo.dwr.simple.UploadDownload.java

License:Apache License

/**
 * Generates a PDF file with the given text
 * http://itext.ugent.be/itext-in-action/
 * @return A PDF file as a byte array/*from w w w .  j  a va  2 s .c  o  m*/
 */
public FileTransfer downloadPdfFile(String contents) throws Exception {
    if (contents == null || contents.length() == 0) {
        contents = "[BLANK]";
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    // ?itext-asian
    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    // ?WINDOW c:\windows\Fonts\xxx.ttf
    // ?classpath: /src/main/resources/fonts/simsong.ttf

    Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents, fontChinese));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
}

From source file:dinamica.AbstractPDFOutput.java

License:LGPL

/**
 * Receives a byte buffer that should be filled with resulting PDF.
 * @param data Data module that provides recordsets to this output module
 * @param buf Buffer to print PDF, then used to send to browser
 * @throws Throwable/*from w  ww. ja v a 2s.c o  m*/
 */
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //pdf objects
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);

    //header
    HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false);
    header.setBorder(Rectangle.BOTTOM);
    header.setAlignment(Rectangle.ALIGN_CENTER);
    doc.setHeader(header);

    //footer
    HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true);
    footer.setBorder(Rectangle.TOP);
    footer.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.setFooter(footer);

    //pagesize
    doc.setPageSize(PageSize.LETTER);

    doc.open();

    //title
    Paragraph t = new Paragraph(getReportTitle(), new Font(Font.HELVETICA, 18f));
    t.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(t);

    //paragraph
    Paragraph p = new Paragraph("Hello World");
    p.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(p);

    doc.close();
    docWriter.close();

}

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

@Override
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //inicializar documento: tamano de pagina, orientacion, margenes
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);
    doc.setPageSize(PageSize.LETTER.rotate());
    doc.setMargins(30, 30, 30, 40);//w ww.  j  a v a 2s . com

    doc.open();

    //crear fonts por defecto
    tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD);
    tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL);

    //definir pie de pagina del lado izquierdo
    String footerText = this.getFooter(); //read it from config.xml or web.xml
    String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm");

    //crear template (objeto interno de IText) y manejador de evento 
    //para imprimir el pie de pagina
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb = docWriter.getDirectContent();
    tpl = cb.createTemplate(20, 14);
    docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate));

    //titulo - lo lee de config.xml por defecto
    reportTitle = getReportTitle();
    Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD));
    t.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.add(t);

    //logo
    img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false));
    img.scalePercent(100);
    float imgY = doc.top() - img.getHeight();
    float imgX = doc.left();
    img.setAbsolutePosition(imgX, imgY);
    doc.add(img);

    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));

    //for each master record print a master/detail section
    MasterDetailReader dataobj = (MasterDetailReader) data;
    Recordset master = dataobj.getRecordset("master");
    master.top();
    while (master.next()) {
        //blank line
        doc.add(new Paragraph(" "));

        //print master section
        doc.add(getGroupMaster(master));

        //print detail section
        doc.add(getGroupDetail(master, dataobj.getDetail(master)));

    }

    //print grand total
    doc.add(new Paragraph(" "));

    doc.close();
    docWriter.close();

}

From source file:Driver.RunTestCases.java

License:Open Source License

public void generateReport() {

    File file = new File("Report1.pdf");
    FileOutputStream fileout = null;
    try {//from  w  w  w .  j a  va 2s .  c o  m
        fileout = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, fileout);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.addAuthor("AGTT");
    document.addTitle("AGTT Report");

    document.open();
    Boolean status = true;
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("Results.txt"));
        String line = null;
        String testCase = null;
        Chunk chunk = null;
        int index = 0;
        List list = new List();
        while ((line = reader.readLine()) != null) {
            if (line.contains("Case")) {

                if (index > 0) {
                    System.out.println(line + status + list.size());
                    if (status == false) {
                        chunk.setBackground(Color.RED);
                    }
                    if (status == true) {
                        chunk.setBackground(Color.GREEN);
                    }
                    document.add(chunk);
                    document.add((Element) list);
                    status = true;
                    list = new List();
                    testCase = null;
                }
                chunk = new Chunk(line + "\n");
                Font font = new Font(Font.TIMES_ROMAN);
                font.setSize(18);
                chunk.setFont(font);
                index++;
            } else {
                if (line.contains("not")) {
                    status = false;
                }
                list.add(line);
            }
            //   document.add(chunk);
        }
    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:ec.edu.chyc.manejopersonal.managebean.PDFCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {
    try {//from   w  w  w  .  ja v a 2 s.  com
        Document document = new Document();
        if (orientation.equalsIgnoreCase("Landscape")) {
            document.setPageSize(PageSize.A4.rotate());
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        StringTokenizer st = new StringTokenizer(tableId, ",");
        while (st.hasMoreElements()) {
            String tableName = (String) st.nextElement();
            UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                    tableName);
            if (component == null) {
                throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
            }
            if (!(component instanceof DataTable || component instanceof DataList)) {
                throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                        + "\", exporter must target a PrimeFaces DataTable/DataList.");
            }

            if (preProcessor != null) {
                preProcessor.invoke(context.getELContext(), new Object[] { document });
            }

            if (!document.isOpen()) {
                document.open();
            }
            if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {

                Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE,
                        Font.BOLD);
                Paragraph title = new Paragraph(tableTitle, tableTitleFont);
                document.add(title);

                Paragraph preface = new Paragraph();
                addEmptyLine(preface, 3);
                document.add(preface);
            }
            PdfPTable pdf;
            DataList list = null;
            DataTable table = null;
            if (component instanceof DataList) {
                list = (DataList) component;
                pdf = exportPDFTable(context, list, pageOnly, encodingType);
            } else {
                table = (DataTable) component;
                pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable);
            }

            if (pdf != null) {
                document.add(pdf);
            }
            // add a couple of blank lines
            Paragraph preface = new Paragraph();
            addEmptyLine(preface, datasetPadding);
            document.add(preface);

            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { document });
            }
        }
        document.close();

        writePDFToResponse(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:ec.edu.uce.erp.web.common.util.CustomPDFExporter.java

@Override
public void export(FacesContext context, DataTable table, String filename, boolean pageOnly,
        boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor) throws IOException {

    try {/*from  ww  w.j  a  v a2s  . co  m*/
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        if (!document.isOpen()) {
            document.open();
        }

        //         addMetaData(document);
        addTitlePage(document);

        document.add(exportPDFTable(context, table, pageOnly, selectionOnly, encodingType));

        document.close();

        writePDFToResponse(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:ec.edu.uce.erp.web.common.util.CustomPDFExporter.java

private void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);/*from   ww  w  . ja v  a  2  s.co  m*/
    // Lets write a big header
    preface.add(new Paragraph(mapValuesPDF.get(ConstantesReporte.TITULO), titleFont));

    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.com ;-).",
    //            redFont));

    document.add(preface);
}

From source file:edu.eci.pdsw.g4.bean.control.web.SystemManageBean.java

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();//from  w  w  w .j  a v  a 2s .c o  m
    pdf.setPageSize(PageSize.A4);

    pdf.addTitle("Ficha del Equipo : " + loadTipoEquipo.getNombre_equipo());

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    String logo = externalContext.getRealPath("") + File.separator + "resource" + File.separator
            + "ecijulio.png";

    pdf.add(Image.getInstance(logo));
    pdf.bottom(30);

    pdf.add(new Chunk(
            "Datos del Equipo : " + loadTipoEquipo.getNombre_equipo() + " con Placa No : " + getPlacaficha()));
}

From source file:edu.harvard.mcz.imagecapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(List<UnitTrayLabel> taxa) throws PrintFailedException {
    boolean result = false;
    UnitTrayLabel label = new UnitTrayLabel();
    LabelEncoder encoder = new LabelEncoder(label);
    Image image = encoder.getImage();
    int counter = 0;
    try {//  w  ww . j  a  v a 2  s . c  o  m
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("labels.pdf"));
        document.setPageSize(PageSize.LETTER);
        document.open();

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100f);
        //table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        float[] cellWidths = { 30f, 20f, 30f, 20f };
        table.setWidths(cellWidths);

        UnitTrayLabelLifeCycle uls = new UnitTrayLabelLifeCycle();
        if (taxa == null) {
            taxa = uls.findAll();
        }
        Iterator<UnitTrayLabel> i = taxa.iterator();
        PdfPCell cell = null;
        PdfPCell cell_barcode = null;
        // Create two lists of 12 cells, the first 6 of each representing
        // the left hand column of 6 labels, the second 6 of each 
        // representing the right hand column.  
        // cells holds the text for each label, cells_barcode the barcode.
        ArrayList<PdfPCell> cells = new ArrayList<PdfPCell>(12);
        ArrayList<PdfPCell> cells_barcode = new ArrayList<PdfPCell>(12);
        for (int x = 0; x < 12; x++) {
            cells.add(null);
            cells_barcode.add(null);
        }
        int cellCounter = 0;
        while (i.hasNext()) {
            // Loop through all of the taxa (unit tray labels) found to print 
            label = i.next();
            for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                // For each taxon, loop through the number of requested copies 
                // Generate a text and a barcode cell for each, and add to array for page
                log.debug("Label " + toPrint + " of " + label.getNumberToPrint());
                cell = new PdfPCell();
                cell.setBorderColor(Color.LIGHT_GRAY);
                cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                cell.disableBorderSide(PdfPCell.RIGHT);
                cell.setPaddingLeft(3);

                String higherNames = "";
                if (label.getTribe().trim().length() > 0) {
                    higherNames = label.getFamily() + ": " + label.getSubfamily() + ": " + label.getTribe();
                } else {
                    higherNames = label.getFamily() + ": " + label.getSubfamily();
                }
                Paragraph higher = new Paragraph();
                higher.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                higher.add(new Chunk(higherNames));
                cell.addElement(higher);

                Paragraph name = new Paragraph();
                Chunk genus = new Chunk(label.getGenus().trim() + " ");
                genus.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                Chunk species = new Chunk(label.getSpecificEpithet().trim());
                Chunk normal = null; // normal font prefix to preceed specific epithet (nr. <i>epithet</i>)
                if (label.getSpecificEpithet().contains(".") || label.getSpecificEpithet().contains("[")) {
                    if (label.getSpecificEpithet().startsWith("nr. ")) {
                        normal = new Chunk("nr. ");
                        normal.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                        species = new Chunk(label.getSpecificEpithet().trim().substring(4));
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                    } else {
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                    }
                } else {
                    species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                String s = "";
                if (label.getSubspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk subspecies = new Chunk(s + label.getSubspecificEpithet().trim());
                if (label.getSubspecificEpithet().contains(".")
                        || label.getSubspecificEpithet().contains("[")) {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                } else {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                if (label.getInfraspecificRank().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infraRank = new Chunk(s + label.getInfraspecificRank().trim());
                infraRank.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                if (label.getInfraspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infra = new Chunk(s + label.getInfraspecificEpithet().trim());
                infra.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                if (label.getUnNamedForm().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk unNamed = new Chunk(s + label.getUnNamedForm().trim());
                unNamed.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                name.add(genus);
                if (normal != null) {
                    name.add(normal);
                }
                name.add(species);
                name.add(subspecies);
                name.add(infraRank);
                name.add(infra);
                name.add(unNamed);
                cell.addElement(name);

                Paragraph authorship = new Paragraph();
                authorship.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                if (label.getAuthorship() != null && label.getAuthorship().length() > 0) {
                    Chunk c_authorship = new Chunk(label.getAuthorship());
                    authorship.add(c_authorship);
                }
                cell.addElement(authorship);
                //cell.addElement(new Paragraph(" "));
                if (label.getDrawerNumber() != null && label.getDrawerNumber().length() > 0) {
                    Paragraph drawerNumber = new Paragraph();
                    drawerNumber.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                    Chunk c_drawerNumber = new Chunk(label.getDrawerNumber());
                    drawerNumber.add(c_drawerNumber);
                    cell.addElement(drawerNumber);
                } else {
                    if (label.getCollection() != null && label.getCollection().length() > 0) {
                        Paragraph collection = new Paragraph();
                        collection.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                        Chunk c_collection = new Chunk(label.getCollection());
                        collection.add(c_collection);
                        cell.addElement(collection);
                    }
                }

                cell_barcode = new PdfPCell();
                cell_barcode.setBorderColor(Color.LIGHT_GRAY);
                cell_barcode.disableBorderSide(PdfPCell.LEFT);
                cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);

                encoder = new LabelEncoder(label);
                image = encoder.getImage();
                image.setAlignment(Image.ALIGN_TOP);
                cell_barcode.addElement(image);

                cells.add(cellCounter, cell);
                cells_barcode.add(cellCounter, cell_barcode);

                cellCounter++;
                // If we have hit a full set of 12 labels, add them to the document
                // in two columns, filling left column first, then right
                if (cellCounter == 12) {
                    // add a page of 12 cells in columns of two.
                    for (int x = 0; x < 6; x++) {
                        if (cells.get(x) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x));
                            table.addCell(cells_barcode.get(x));
                        }
                        if (cells.get(x + 6) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x + 6));
                            table.addCell(cells_barcode.get(x + 6));
                        }
                    }
                    // Reset to begin next page
                    cellCounter = 0;
                    document.add(table);
                    table = new PdfPTable(4);
                    table.setWidthPercentage(100f);
                    table.setWidths(cellWidths);
                    for (int x = 0; x < 12; x++) {
                        cells.set(x, null);
                        cells_barcode.set(x, null);
                    }
                }
            } // end loop through toPrint (for a taxon)
            counter++;
        } // end while results has next (for all taxa requested)
          // get any remaining cells in pairs
        for (int x = 0; x < 6; x++) {
            if (cells.get(x) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x));
                table.addCell(cells_barcode.get(x));
            }
            if (cells.get(x + 6) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x + 6));
                table.addCell(cells_barcode.get(x + 6));
            }
        }
        // add any remaining cells
        document.add(table);
        try {
            document.close();
        } catch (Exception e) {
            throw new PrintFailedException("No labels to print." + e.getMessage());
        }
        // Check to see if there was content in the document.
        if (counter == 0) {
            result = false;
        } else {
            // Printed to pdf ok.
            result = true;
            // Increment number printed.
            i = taxa.iterator();
            while (i.hasNext()) {
                label = i.next();
                for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                    label.setPrinted(label.getPrinted() + 1);
                }
                label.setNumberToPrint(0);
                try {
                    uls.attachDirty(label);
                } catch (SaveFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("File not found.");
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("Error buiding PDF document.");
    } catch (OutOfMemoryError e) {
        System.out.println("Out of memory error. " + e.getMessage());
        System.out.println("Failed.  Too many labels.");
        throw new PrintFailedException("Ran out of memory, too many labels at once.");
    }
    return result;
}