Example usage for com.itextpdf.text Document newPage

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

Introduction

In this page you can find the example usage for com.itextpdf.text Document newPage.

Prototype


public boolean newPage() 

Source Link

Document

Signals that an new page has to be started.

Usage

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report that has no data in it (only the image).
 * The length is the given number of pages.
 * /*from  w  ww .ja v  a2 s .  c o m*/
 * @param numPages
 * @return True if the report was generated.
 */
public boolean generateBlank(Dao dao, Integer numPages) {
    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 1;
        while (true) {
            drawBout(cb, bf, 35, midPage - 35, null);
            drawBout(cb, bf, midPage + 35, pageWidth - 35, null);

            if (++count > numPages) {
                break;
            }

            document.newPage();
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report for the given list of bouts.
 * It is assumed that the list is in the desired order (no sorting is done here).
 *
 * @param list//  w ww .  j  a va2 s.c  o m
 * @return True if the report was generated.
 */
public boolean generateReport(Dao dao, List<Bout> list) {

    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 0;
        for (Bout b : list) {
            boolean rightSide = false;
            if ((count++ % 2) == 0) {
                if (count > 2) {
                    // We could put this after Bout 2 is added, but
                    // that could leave a blank last page.
                    document.newPage();
                }

                // Bout 1 (Left side)
                drawBout(cb, bf, 35, midPage - 35, b);
            } else {
                // Bout 2 (Right side)
                drawBout(cb, bf, midPage + 35, pageWidth - 35, b);
                rightSide = true;
            }

            // Print the watermark, if necessary
            boolean doWatermark = false;
            String gClass = b.getGroup().getClassification();
            String wmValues = dao.getBoutsheetWatermarkValues();
            if ((wmValues != null) && !wmValues.isEmpty()) {
                String[] tokens = wmValues.split(",");
                for (String s : tokens) {
                    if (s.trim().equalsIgnoreCase(gClass)) {
                        doWatermark = true;
                        break;
                    }
                }
            }
            if (doWatermark) {
                int rotation = 45;
                PdfContentByte ucb = writer.getDirectContentUnder();
                BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                ucb.saveState();
                ucb.setColorFill(BaseColor.LIGHT_GRAY);
                ucb.beginText();
                ucb.setFontAndSize(helv, 86);
                float centerWidth = document.getPageSize().getWidth() / 4;
                if (rightSide) {
                    centerWidth = centerWidth * 3;
                }
                ucb.showTextAligned(Element.ALIGN_CENTER, gClass, centerWidth,
                        document.getPageSize().getHeight() / 2, rotation);
                ucb.endText();
                ucb.restoreState();
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.bracketsheet.BracketSheetReport.java

License:Open Source License

public static boolean generateReport(Dao dao, List<Group> list, String outputFile, boolean doBoutNumbers,
        boolean doTimestamp) {

    if (list.isEmpty()) {
        return false;
    }/*w ww .  j a v a 2 s. c  o  m*/

    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile(outputFile);
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        String timestamp = "";
        if (doTimestamp) {
            timestamp = DateFormat.getInstance().format(new Date());
        }

        int rv;
        int i = 0;
        int size = list.size();
        for (Group g : list) {
            rv = addBracket(cb, dao, g, doBoutNumbers);
            if (rv != PAGE_ERROR) {
                // Print the watermark, if necessary
                boolean doWatermark = false;
                String gClass = g.getClassification();
                String wmValues = dao.getBracketsheetWatermarkValues();
                if ((wmValues != null) && !wmValues.isEmpty()) {
                    String[] tokens = wmValues.split(",");
                    for (String s : tokens) {
                        if (s.trim().equalsIgnoreCase(gClass)) {
                            doWatermark = true;
                            break;
                        }
                    }
                }

                int rotation = (rv == PAGE_ROUNDROBIN) ? 45 : 135;

                if (doWatermark) {
                    PdfContentByte ucb = writer.getDirectContentUnder();
                    BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                    ucb.saveState();
                    ucb.setColorFill(BaseColor.LIGHT_GRAY);
                    ucb.beginText();
                    ucb.setFontAndSize(helv, 86);
                    ucb.showTextAligned(Element.ALIGN_CENTER, gClass, document.getPageSize().getWidth() / 2,
                            document.getPageSize().getHeight() / 2, rotation);
                    ucb.endText();
                    ucb.restoreState();
                }

                if (doTimestamp) {
                    rotation -= 45;
                    float width = cb.getPdfWriter().getPageSize().getWidth();
                    int x = (rv == PAGE_ROUNDROBIN) ? 15 : (int) (width - 15);
                    int y = 15;
                    BracketSheetUtil.drawTimestamp(cb, null, x, y, 10, timestamp, rotation);
                }

                // If not doing bout numbers, this is an 'award' type of
                // bracket.  So print an image/logo, if configured.
                if (!doBoutNumbers && (dao.getBracketsheetAwardImage() != null)
                        && !dao.getBracketsheetAwardImage().isEmpty()) {
                    Image image = Image.getInstance(Image.getInstance(dao.getBracketsheetAwardImage()));
                    image.setRotationDegrees((rv == PAGE_ROUNDROBIN) ? 0 : 90);
                    PositionOnPage positionOnPage = dao.getBracketsheetAwardImagePosition();
                    if (PositionOnPage.UPPER_RIGHT == positionOnPage) {
                        float x = (rv == PAGE_ROUNDROBIN)
                                ? document.getPageSize().getWidth() - 10 - image.getWidth()
                                : 10;
                        float y = document.getPageSize().getHeight() - 10 - image.getHeight();
                        image.setAbsolutePosition(x, y);
                        cb.addImage(image);
                    } else if (PositionOnPage.CENTER == positionOnPage) {
                        // put the image in the background, in the middle of the page
                        PdfContentByte ucb = writer.getDirectContentUnder();
                        float pageX = document.getPageSize().getWidth() / 2;
                        float pageY = document.getPageSize().getHeight() / 2;
                        float imageX = image.getWidth() / 2;
                        float imageY = image.getHeight() / 2;
                        image.setAbsolutePosition(pageX - imageX, pageY - imageY);
                        ucb.addImage(image);
                    }
                }

                if (++i < size) {
                    document.newPage();
                }
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.weighin.WeighInReport.java

License:Open Source License

/**
 * Generate a report of the entries in the tournament for weigh-in.
 * @param sections List of sections for the report.  Each section will start
 *     on a new page.//  ww  w. ja v  a2s .  c o  m
 * @param headerString String to be used for the header of each page of the report.
 * @return True if the report was generated.
 */
public static boolean doReport(List<List<Wrestler>> sections, String headerString) {
    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: create and add content

        // create and add the header
        if (headerString != null) {
            Paragraph p1 = new Paragraph(
                    new Paragraph(headerString, FontFactory.getFont(FontFactory.HELVETICA, 10)));
            document.add(p1);
        }

        Font detailFont = new Font(Font.FontFamily.TIMES_ROMAN, 10);

        for (List<Wrestler> wrestlers : sections) {
            // create and add the table
            PdfPTable datatable = new PdfPTable(7);
            int colWidths[] = { 20, 20, 20, 10, 10, 10, 10 }; // percentage
            datatable.setWidths(colWidths);
            datatable.setWidthPercentage(100);
            datatable.getDefaultCell().setPadding(3);
            datatable.getDefaultCell().setBorderWidth(2);
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

            //datatable.setHeaderRows(1); // this is the end of the table header

            datatable.getDefaultCell().setBorderWidth(1);
            datatable.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

            int i = 0;
            for (Wrestler w : wrestlers) {
                if ((i++ % 2) == 0) {
                    datatable.getDefaultCell().setGrayFill(0.9f);
                } else {
                    datatable.getDefaultCell().setGrayFill(1);
                }

                datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                datatable.addCell(new Phrase(w.getLastName(), detailFont));
                datatable.addCell(new Phrase(w.getFirstName(), detailFont));
                datatable.addCell(new Phrase(w.getTeamName(), detailFont));
                datatable.addCell(new Phrase(w.getClassification(), detailFont));
                datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                datatable.addCell(new Phrase(w.getAgeDivision(), detailFont));
                datatable.addCell(new Phrase(w.getWeightClass(), detailFont));
                datatable.addCell(new Phrase()); // actual weight
            }

            datatable.setSpacingBefore(5f);
            datatable.setSpacingAfter(15f);
            document.add(datatable);
            document.newPage();
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:br.jus.jfpr.Divisor1.java

/**
 * Divide um arquivo inicialmente em 2, testa se o tamanho que todos
 * arquivos ficaram dentro do limite, se no ficaram apaga tudo e recomea
 * dividindo por, 3, 4, 5, etc. at que todos arquivo fiquem dentro do
 * limite//from  w w  w.ja  va2 s. co m
 *
 * @param arquivoEntrada O arquivo que ser dividido
 * @param arquivoSaida O nome do arquivo que ser criado
 * @param tamArqSel Tamanho selecionado que devero ficar os arquivos
 * divididos
 * @return String informativa do resultado
 */
public static String dividePDF(File arquivoEntrada, String arquivoSaida, int tamArqSel) {

    int daPagina = 1;
    int paraPagina;
    int tamInicial;
    // FileOutputStream arquivoSair = null;
    String MensagemErro = "ok";
    int fatorDivisao = 2; //Incialmente dividir em 2
    arquivoSaida = arquivoSaida.substring(0, arquivoSaida.indexOf('.')) + "-divido"; //PAra definir o nome do arquivo de sada

    try {
        PdfReader PdfDeEntrada = new PdfReader(arquivoEntrada.getAbsolutePath()); //Para ler o arquivo de entrada
        final int totalPaginas = PdfDeEntrada.getNumberOfPages(); //Verifica o total de pginas
        tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Define o tamanho (em pginas) do 1 arquivo e em quanto dever incrementar(sero o mesmo)
        PdfImportedPage pagina;

        int i = 1; //Contador simples
        while (i <= fatorDivisao && totalPaginas > fatorDivisao) { //Enquanto no fizer todas as divises
            Document documento = new Document();
            FileOutputStream arquivoSair = new FileOutputStream(arquivoSaida + "-" + i + ".pdf"); //Cria o arquivo, vazio
            PdfWriter writer = PdfWriter.getInstance(documento, arquivoSair); //
            documento.open();
            PdfContentByte PContentByte = writer.getDirectContent();
            while (daPagina <= paraPagina) {
                documento.newPage(); //Aloca uma nova pginA
                pagina = writer.getImportedPage(PdfDeEntrada, daPagina); //Seleciona uma pgina especfica. indicada pelo contador
                PContentByte.addTemplate(pagina, 0, 0); //Adiciona a pagina ao contedo
                daPagina++; //Contador simples
            }
            arquivoSair.flush();
            documento.close(); //Grava o arquivo de sada
            arquivoSair.close();
            File arquivoDest = new File(arquivoSaida + "-" + i + ".pdf");
            if (arquivoDest.length() > tamArqSel) { // O tamanho do arquivo de destino ficou maior do que deveria
                delete(arquivoSaida, i); //Chamar a funo para deletar todos arquivos at a chave i
                daPagina = i = 1; //Para recomear tudo de novo
                fatorDivisao++; //Se um arquivo ficou maior, ento deve aumentar a diviso
                tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Para recomear tudo de novo
            } else {
                i++; //Continua a divisao
                if (i == fatorDivisao) { //Ou seja, chegou a ultima divisao
                    paraPagina = totalPaginas; //O ultimo arquivo conter mais pginas
                } else {
                    paraPagina += tamInicial; //Cada arquivo ter o mesmo nmero de pginas//Incrementa sempre o tamanho inicial
                }
            }
        }
    } catch (IOException | DocumentException e) {
        System.err.println(e.getMessage());
        MensagemErro = e.getMessage();
    }
    return MensagemErro;
}

From source file:br.unifor.mia.xmpsemantico.xmp.MetadataXmp.java

License:GNU General Public License

/**
 * create PDF document/*from ww  w  .  j av a  2s  .  c  o m*/
 * @param filename of new archive PDF
 * @throws DocumentException 
 * @throws IOException 
 */
public void createPdf() throws IOException {

    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(pathPdf));

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XmpWriter xmp = new XmpWriter(os);

        MiaSchema miaSchema = new MiaSchema();
        miaSchema.addDescription(this.descricao);
        miaSchema.setProperty(MiaSchema.DISCIPLINA, this.disciplina);
        miaSchema.setProperty(MiaSchema.PROFESSOR, this.professor);
        miaSchema.setProperty(MiaSchema.CARGA_HORARIA, this.cargaHoraria);
        miaSchema.setProperty(MiaSchema.CREDITOS, this.creditos);
        xmp.addRdfDescription(miaSchema);

        xmp.close();
        writer.setXmpMetadata(os.toByteArray());

        document.open();
        document.addAuthor("docsemantico");
        Paragraph paragraph = new Paragraph("Quick brown ");
        Anchor foxRefence = new Anchor("fox");
        foxRefence.setReference("#fox");
        paragraph.add(foxRefence);
        paragraph.add(" jumps over the lazy dog.");
        document.add(paragraph);
        document.newPage();
        Anchor foxName = new Anchor("This is the FOX");
        foxName.setName("fox");
        document.add(foxName);
        document.add(new Paragraph(this.texto));

        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    //teste commit
}

From source file:bsf.conn.DBMS.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//  w w  w.  j  a va2 s.c  om
    // Lets write a big header
    catFont.setColor(BaseColor.BLUE);
    preface.add(new Paragraph("BSF DATABASE", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph(
            "Report generated by: " + System.getProperty("user.name") + ", " + new java.util.Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document gives Database of BSF ", smallBold));

    addEmptyLine(preface, 20);

    preface.add(new Paragraph("@copyright BSF", redFont));

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

From source file:ca.sqlpower.wabit.report.LayoutToPDF.java

License:Open Source License

public void writePDF() throws DocumentException, FileNotFoundException, PrinterException {
    monitorableHelper.setStarted(true);/*from   ww  w .j  av  a  2s.  com*/
    int pageNum = 0;

    int numPages = layout.getNumberOfPages();
    monitorableHelper.setJobSize(numPages);
    Page page = layout.getPage();
    OutputStream out = fileOS;
    Rectangle pageSize;
    pageSize = new Rectangle(page.getWidth(), page.getHeight());

    Document pdfDoc = new Document(pageSize, 0f, 0f, 0f, 0f);

    PdfWriter pdfOut = PdfWriter.getInstance(pdfDoc, out);
    pdfDoc.open();
    pdfDoc.addCreator("Wabit " + WabitVersion.VERSION);
    PdfContentByte pdfContent = pdfOut.getDirectContent();
    Graphics2D pdfGraphics = null;
    try {
        while (pageNum < numPages) {
            monitorableHelper.checkCancelled();
            monitorableHelper.setProgress(pageNum);
            pdfGraphics = pdfContent.createGraphics(pageSize.getWidth(), pageSize.getHeight());
            int flag = layout.print(pdfGraphics, layout.getPageFormat(pageNum), pageNum);

            if (watermarker != null) {
                java.awt.Rectangle watermarkSize = new java.awt.Rectangle();
                watermarkSize.setSize(Math.round(pageSize.getWidth()), Math.round(pageSize.getHeight()));
                watermarker.watermark(pdfGraphics, watermarkSize);
            }

            pdfGraphics.dispose();
            pdfGraphics = null;

            if (flag == Printable.NO_SUCH_PAGE)
                break;

            pdfDoc.newPage();

            pageNum++;
        }
    } finally {
        if (pdfGraphics != null)
            pdfGraphics.dispose();
        if (pdfDoc != null)
            pdfDoc.close();
        monitorableHelper.setFinished(true);
    }
}

From source file:Capa_Modelo.Reportes.java

public void generarReporteESMedicamentos() {
    Connection con;/*w  w  w .j  a v  a 2 s .co  m*/
    ResultSet res, res2;
    Statement sentencia;
    Document documento = new Document(PageSize.A4);
    con = ConexionDB.GetConnection();
    try {
        sentencia = con.createStatement();
        res = sentencia.executeQuery(
                "SELECT Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio, Medicamento.FechaLlegada, Inventario.Cantidad FROM Medicamento INNER JOIN Inventario ON Medicamento.ID_Medicamento = Inventario.ID_Medicamento ORDER BY Inventario.Cantidad, Medicamento.Nombre desc");
        PdfWriter.getInstance(documento, new FileOutputStream("reportes/reporte_de_entrada-salida_medicamentos "
                + fechaActual() + " " + horaActual() + ".pdf"));
        documento.open();
        float[] columnWidths = { 2, 2, 2, 2, 2 };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
        Font f = new Font(Font.FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de Entrada de Medicamentos", f));
        cell.setBackgroundColor(GrayColor.GRAYBLACK);
        cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell.setColspan(8);
        table.addCell(cell);
        table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table.addCell("Medicamento");
            table.addCell("Composicion");
            table.addCell("Laboratorio");
            table.addCell("Fecha de Entrada");
            table.addCell("Cantidad");
        }
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res.next()) {
            table.addCell(res.getString("Nombre"));
            table.addCell(res.getString("Composicion"));
            table.addCell(res.getString("Laboratorio"));
            table.addCell(res.getString("FechaLlegada"));
            table.addCell(res.getString("Cantidad"));
        }
        documento.add(table);
        documento.newPage();
        res2 = sentencia.executeQuery(
                "SELECT Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio, MedicinaPaciente.FechaEntrega, SUM(MedicinaPaciente.Cantidad) AS Entregados FROM Medicamento INNER JOIN MedicinaPaciente ON Medicamento.ID_Medicamento = MedicinaPaciente.ID_Medicamento  group by Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio,MedicinaPaciente.FechaEntrega ORDER BY Entregados");
        float[] columnWidths2 = { 2, 2, 2, 2, 2 };
        PdfPTable table2 = new PdfPTable(columnWidths);
        table2.setWidthPercentage(100);
        table2.getDefaultCell().setUseAscender(true);
        table2.getDefaultCell().setUseDescender(true);
        PdfPCell cell2 = new PdfPCell(new Phrase("Reporte de Salida de Medicamentos", f));
        cell2.setBackgroundColor(GrayColor.GRAYBLACK);
        cell2.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell2.setColspan(8);
        table2.addCell(cell2);
        table2.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table2.addCell("Medicamento");
            table2.addCell("Composicion");
            table2.addCell("Laboratorio");
            table2.addCell("Fecha de Salida");
            table2.addCell("Cantidad");
        }
        table2.setHeaderRows(3);
        table2.setFooterRows(1);
        table2.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table2.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res2.next()) {
            table2.addCell(res2.getString("Nombre"));
            table2.addCell(res2.getString("Composicion"));
            table2.addCell(res2.getString("Laboratorio"));
            table2.addCell(res2.getString("FechaEntrega"));
            table2.addCell(res2.getString("Entregados"));
        }
        documento.add(table2);
        documento.close();
        JOptionPane.showMessageDialog(null,
                "Reporte de Entrada y Salida de Medicamentos generado correctamente");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Error al conectar con la base de datos");
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar la ruta del archivo");
    } catch (DocumentException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar el archivo");
    }
}

From source file:ch.java_akademie.pdf.FirstPdf.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//w  w w  . j  a v  a  2 s . c  om
    // 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: " //$NON-NLS-1$
            + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$
            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);
    // Start a new page
    document.newPage();
}