Example usage for com.itextpdf.text Document Document

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

Introduction

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

Prototype


public Document() 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:com.algoboss.erp.util.report.PDFExporter.java

License:Apache License

@Override
public void export(FacesContext context, DataTable table, String filename, boolean pageOnly,
        boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor) throws IOException {
    try {/*from   w  ww  .  j  a v a2  s  .  c  o  m*/
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

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

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

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

        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:com.algoboss.erp.util.report.PDFExporter.java

License:Apache License

public void export(FacesContext context, DataTable table, String filename) throws IOException {
    try {//from  ww w  . j  a  va 2 s. c  o  m
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
        //XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        DataTableRenderer render = new DataTableRenderer();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.reset();
        ExternalContext externalContext = context.getExternalContext();
        PrintWriter writer = new PrintWriter(baos);

        context.setResponseWriter(context.getRenderKit().createResponseWriter(writer, "text/html", "utf-8"));
        render.encodeEnd(context, table);
        writer.write(
                "<link href=\"/ERP/f/javax.faces.resource/theme.css?ln=primefaces-cupertino\" rel=\"stylesheet\" type=\"text/css\">\n"
                        + "<link href=\"/ERP/f/javax.faces.resource/primefaces.css?ln=primefaces\" rel=\"stylesheet\" type=\"text/css\">\n"
                        + "<link href=\"/ERP/f/javax.faces.resource/schedule/schedule.css?ln=primefaces\" rel=\"stylesheet\" type=\"text/css\">\n"
                        + "<meta content=\"application/pdf; charset=UTF-8\" http-equiv=\"Content-Type\">\n"
                        + "<link type=\"text/css\" rel=\"stylesheet\" href=\"/ERP/resources/css/default.css\">\n"
                        + "<link type=\"text/css\" rel=\"stylesheet\" href=\"/ERP/resources/css/cssLayout.css\">\n"
                        + "<title>Plataforma de Gerenciamento</title>");
        /*
        externalContext.setResponseHeader("Expires", "0");
        externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        externalContext.setResponseHeader("Pragma", "public");
        externalContext.setResponseHeader("Content-disposition", "inline;filename=" + filename + ".pdf");
        externalContext.setResponseContentType("application/pdf");
        externalContext.setResponseContentLength(baos.size());
        externalContext.addResponseCookie(Constants.DOWNLOAD_COOKIE, "true", new HashMap<String, Object>());
        OutputStream out = externalContext.getResponseOutputStream();
        baos.writeTo(out);
        externalContext.responseFlushBuffer();     
        */

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline;filename=\"" + filename + "\";");

        response.setContentLength(baos.size());
        response.getOutputStream().write(baos.toByteArray(), 0, baos.size());
        FacesContext.getCurrentInstance().responseComplete();
        //worker.parseXHtml(pdfWriter, document, new StringReader(new String(baos.toByteArray())));
        document.close();

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

    } catch (IOException e) {
        throw new IOException(e.getMessage());
    } catch (DocumentException ex) {
        Logger.getLogger(PDFExporter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.algoboss.erp.util.report.PDFExporter2.java

License:Apache License

public void export(FacesContext context, DataTable table, String filename, String encodingType)
        throws IOException {
    try {/*from www  .jav a2  s  .  c om*/
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        if (!document.isOpen()) {
            document.open();
        }
        document.setMargins(1f, 1f, 1f, 1f);
        document.setPageSize(PageSize.A4);
        document.add(exportPDFTable(context, table, false, false, true, encodingType));
        document.setMargins(1f, 1f, 1f, 1f);
        document.setPageSize(PageSize.A4);

        document.close();

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

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

From source file:com.algoboss.erp.util.report.PDFExporter2.java

License:Apache License

public void export(FacesContext context, String cssstring, String htmlstring, String filename)
        throws IOException {
    try {//from   w  w w  .jav  a 2  s .  c om
        InputStream is = new ByteArrayInputStream(htmlstring.getBytes());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, baos);

        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);

        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        String[] cssstringArray = cssstring.split(";");
        FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context2 = (ServletContext) aFacesContext.getExternalContext().getContext();
        String realPath = context2.getRealPath("/");
        System.out.println(realPath);
        System.out.println(context2.getContextPath());
        //System.out.println(context2.getResource(""));  
        System.out.println(aFacesContext.getExternalContext().getContextName());
        System.out.println(aFacesContext.getExternalContext().getRequestContextPath()
                + aFacesContext.getExternalContext().getRequestServletPath());
        //System.out.println(aFacesContext.getExternalContext().getRequestServletPath());
        //System.out.println(aFacesContext.getExternalContext().getRequestPathInfo());
        //System.out.println(aFacesContext.getExternalContext().getRequestScheme());
        //System.out.println(aFacesContext.getExternalContext().getRequestScheme());
        //System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
        for (int i = 0; i < cssstringArray.length; i++) {
            String cssHref = cssstringArray[i];
            try {
                URL url = new URL(aFacesContext.getExternalContext().getRequestScheme(),
                        aFacesContext.getExternalContext().getRequestServerName(),
                        aFacesContext.getExternalContext().getRequestServerPort(), cssHref);
                InputStream csspathtest = url.openStream();
                CssFile cssfiletest = XMLWorkerHelper.getCSS(csspathtest);
                cssResolver.addCss(cssfiletest);
            } catch (IOException ex) {
                Logger.getLogger(PDFExporter2.class.getName()).log(Level.SEVERE, null, ex);
            }
            //String realPath2 = context2.getRealPath(cssHref);

            //InputStream csspathtest2 = aFacesContext.getExternalContext().getResourceAsStream(realPath2);
            //System.out.println(cssfiletest);
        }

        Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser p = new XMLParser(worker);
        p.parse(is, Charset.forName("iso-8859-1"));//new FileInputStream("results/demo2/walden.html"));

        // step
        document.close();

        // post back...
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-disposition", "inline;filename=\"" + filename + "\";");
        response.setContentLength(baos.size());
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
        context.responseComplete();

    } catch (IOException e) {
        throw new IOException(e.getMessage());
    } catch (Exception ex) {
        Logger.getLogger(PDFExporter2.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.alnaser.view.GestionProduit.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {
    System.out.println("!!!!!!!");
    try {//from w w w .j ava2s.co  m
        OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));

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

        document.open();
        // a table with three columns
        PdfPTable table = new PdfPTable(7);
        // the cell object
        PdfPCell cell, cel2, cel3, cel4, cel5, cel6, cel7;
        // we add a cell with colspan 3
        cell = new PdfPCell(new Phrase("Code"));
        cel2 = new PdfPCell(new Phrase("Ref"));
        cel3 = new PdfPCell(new Phrase("Desg"));
        cel4 = new PdfPCell(new Phrase("Four"));
        cel5 = new PdfPCell(new Phrase("Remise"));
        cel6 = new PdfPCell(new Phrase("Prix"));
        cel7 = new PdfPCell(new Phrase("Stock"));

        table.addCell(cell);
        table.addCell(cel2);
        table.addCell(cel3);
        table.addCell(cel4);
        table.addCell(cel5);
        table.addCell(cel6);
        table.addCell(cel7);

        for (Produit p : list) {
            table.addCell(p.getCodeProduit());
            table.addCell(p.getReference());
            table.addCell(p.getDeseignation());
            table.addCell(p.getFournisseur());
            table.addCell(p.getRemise() + "");
            table.addCell(p.getPrix() + "");
            table.addCell(p.getStock() + "");
        }
        document.add(table);
        document.add(new Paragraph(new Date().toString()));

        document.close();
        file.close();

    } catch (Exception e) {

        e.printStackTrace();
    }

}

From source file:com.apcb.utils.utils.PdfCreator.java

public static String createPdf(String fileName, String innerHTML) throws Exception {
    Document document = new Document();
    String pdfFileName = createPdf(fileName, innerHTML, document);
    return pdfFileName;
}

From source file:com.app.gpo.pdf.utils.AbstractITextPdfView.java

License:Open Source License

protected Document newDocument() {

    Document document = new Document();

    Rectangle pageSize = new Rectangle(226, 141);
    //226,7206478
    //141,6984733

    document.setPageSize(pageSize);/*  w ww. j a v a  2s . c o m*/
    document.setMargins(2, 2, 2, 2);

    return document;

}

From source file:com.asae.controllers.BeanGestionRutinas.java

public void generarPdf() {
    Document document = new Document();
    try {//  w w  w  .j a v  a  2 s .  c om
        File file = File.createTempFile("rutina-", ".pdf", new File("/var/webapp/pdf"));
        pdfFileName = file.getName();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        Font bold = new Font(Font.FontFamily.HELVETICA, 12f, Font.BOLD);
        URL url = FacesContext.getCurrentInstance().getExternalContext()
                .getResource("/resources/img/logo-unicauca-negro.png");
        Image imgLogoUnicauca = Image.getInstance(url);
        imgLogoUnicauca.scaleAbsolute(118f, 131f);

        PdfPTable tableEncabezado = new PdfPTable(2);
        tableEncabezado.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tableEncabezado.setWidthPercentage(100);
        tableEncabezado.setSpacingAfter(5);
        PdfPCell cell1 = new PdfPCell(imgLogoUnicauca);
        cell1.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell2 = new PdfPCell(new Paragraph("Vicerrectoria Administrativa"));
        cell2.setBorder(Rectangle.NO_BORDER);
        cell2.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        PdfPCell cell3 = new PdfPCell(new Paragraph("Universidad del Cauca", bold));
        cell3.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell4 = new PdfPCell(new Paragraph("Gimnasio y Actividad Fsica", bold));
        cell4.setBorder(Rectangle.NO_BORDER);
        cell4.setHorizontalAlignment(Element.ALIGN_RIGHT);
        tableEncabezado.addCell(cell1);
        tableEncabezado.addCell(cell2);
        tableEncabezado.addCell(cell3);
        tableEncabezado.addCell(cell4);

        PdfPTable tableDatosUsuario = new PdfPTable(3);
        tableDatosUsuario.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tableDatosUsuario.setWidthPercentage(100);
        tableDatosUsuario.setSpacingBefore(20);
        PdfPCell cell5 = new PdfPCell(new Paragraph("Nombre: " + rutinaVisualizar.getIdusuario().getFisrtname()
                + " " + rutinaVisualizar.getIdusuario().getSecondname() + " "
                + rutinaVisualizar.getIdusuario().getFirstlastname() + " "
                + rutinaVisualizar.getIdusuario().getSecondlastname()));
        cell5.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell6 = new PdfPCell();
        cell6.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell7 = new PdfPCell();
        cell7.setBorder(Rectangle.NO_BORDER);

        tableDatosUsuario.addCell(cell5);
        tableDatosUsuario.addCell(cell6);
        tableDatosUsuario.addCell(cell7);

        PdfPTable tableFechas = new PdfPTable(3);
        tableFechas.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tableFechas.setWidthPercentage(100);
        tableFechas.setSpacingBefore(10);
        PdfPCell cell8 = new PdfPCell(
                new Paragraph("Fecha de inicio: " + getMyFormattedDate(rutinaVisualizar.getFechaInicio())));
        cell8.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell9 = new PdfPCell(
                new Paragraph("Fecha de fin: " + getMyFormattedDate(rutinaVisualizar.getFechaFin())));
        cell9.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell10 = new PdfPCell();
        cell10.setBorder(Rectangle.NO_BORDER);

        tableFechas.addCell(cell8);
        tableFechas.addCell(cell9);
        tableFechas.addCell(cell10);

        PdfPTable tableMedidas = new PdfPTable(4);
        tableMedidas.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tableMedidas.setWidthPercentage(100);
        tableMedidas.setSpacingBefore(10);

        Usuario usuAux = rutinaVisualizar.getIdusuario();
        List<Evaluacion> lstEvalAux = usuAux.getEvaluacionList();
        Evaluacion evalAux;
        double peso = 0;
        if (lstEvalAux.size() > 0) {
            evalAux = lstEvalAux.get(lstEvalAux.size() - 1);
            peso = evalAux.getPeso().doubleValue();
        }

        double estatura = 0;
        MedidasGenerales medGenAux = usuAux.getMedidasGenerales();
        if (medGenAux != null) {
            estatura = medGenAux.getEstatura().doubleValue();
        }

        PdfPCell cell11 = new PdfPCell(new Paragraph("Peso: " + peso));
        cell11.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell12 = new PdfPCell(new Paragraph("Talla: " + estatura));
        cell12.setBorder(Rectangle.NO_BORDER);

        double imc = 0;
        if (peso != 0 && estatura != 0) {
            imc = peso / Math.pow(estatura, 2);
        }

        PdfPCell cell13 = new PdfPCell(new Paragraph("I.M.C: " + imc));
        cell13.setBorder(Rectangle.NO_BORDER);
        PdfPCell cell14 = new PdfPCell(new Paragraph("Rutina: " + rutinaVisualizar.getCodigoRutina()));
        cell14.setBorder(Rectangle.NO_BORDER);

        tableMedidas.addCell(cell11);
        tableMedidas.addCell(cell12);
        tableMedidas.addCell(cell13);
        tableMedidas.addCell(cell14);

        PdfPTable tableDias = new PdfPTable(2);
        tableDias.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tableDias.setWidthPercentage(100);
        tableDias.setSpacingBefore(20);
        tableDias.setHorizontalAlignment(Element.ALIGN_LEFT);
        tableDias.setWidths(new int[] { 1, 9 });

        List<Dia> lstDiasPDF = rutinaVisualizar.getDiaList();

        PdfPCell cellCabezeraDia = new PdfPCell(new Paragraph("Da", bold));
        PdfPCell cellCabezeraDia2 = new PdfPCell();
        cellCabezeraDia2.setBorder(Rectangle.NO_BORDER);

        tableDias.addCell(cellCabezeraDia);
        tableDias.addCell(cellCabezeraDia2);

        for (Dia dia : lstDiasPDF) {
            PdfPCell cellDia = new PdfPCell(new Paragraph(dia.getNumDia().toString()));
            PdfPCell cellDia2 = new PdfPCell();
            cellDia2.setBorder(Rectangle.NO_BORDER);

            List<GrupoMuscular> lstGMuscularPDF = dia.getGrupoMuscularList();

            if (lstGMuscularPDF.size() > 0) {
                PdfPTable tableGMuscular = new PdfPTable(2);
                tableGMuscular.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                tableGMuscular.setWidthPercentage(100);
                tableGMuscular.setHorizontalAlignment(Element.ALIGN_LEFT);
                tableGMuscular.setWidths(new int[] { 1, 6 });

                PdfPCell cellCabezeraGMuscular = new PdfPCell(new Paragraph("Grupo Muscular", bold));
                cellCabezeraGMuscular.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.TOP);
                PdfPCell cellCabezeraGMuscular2 = new PdfPCell();
                cellCabezeraGMuscular2.setBorder(Rectangle.NO_BORDER);
                tableGMuscular.addCell(cellCabezeraGMuscular);
                tableGMuscular.addCell(cellCabezeraGMuscular2);

                int aux = 1;
                for (GrupoMuscular gMuscularFor : lstGMuscularPDF) {
                    PdfPCell cellGMuscular = new PdfPCell(
                            new Paragraph(gMuscularFor.getIdgrupoMuscularGeneral().getNombre()));
                    cellGMuscular.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                    PdfPCell cellGMuscular2 = new PdfPCell();
                    cellGMuscular2.setBorder(Rectangle.NO_BORDER);

                    List<EjercicioGm> lstEjerciciosGMuscularPDF = gMuscularFor.getEjercicioGmList();
                    BaseColor myColor = WebColors.getRGBColor("#CCEEFF");
                    if (lstEjerciciosGMuscularPDF.size() > 0) {
                        PdfPTable tableEjercicioGMsucular = new PdfPTable(5);
                        tableEjercicioGMsucular.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        tableEjercicioGMsucular.setWidthPercentage(100);
                        tableEjercicioGMsucular.setHorizontalAlignment(Element.ALIGN_LEFT);

                        PdfPCell cellCabezeraEjercicioGM = new PdfPCell(new Paragraph("Ejercicio", bold));
                        cellCabezeraEjercicioGM.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.TOP);
                        cellCabezeraEjercicioGM.setLeading(20f, 0f);
                        cellCabezeraEjercicioGM.setBackgroundColor(myColor);
                        tableEjercicioGMsucular.addCell(cellCabezeraEjercicioGM);

                        PdfPCell cellCabezeraEjercicioGM2 = new PdfPCell(new Paragraph("Series", bold));
                        cellCabezeraEjercicioGM2.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.TOP);
                        cellCabezeraEjercicioGM2.setLeading(20f, 0f);
                        cellCabezeraEjercicioGM2.setBackgroundColor(myColor);
                        tableEjercicioGMsucular.addCell(cellCabezeraEjercicioGM2);

                        PdfPCell cellCabezeraEjercicioGM3 = new PdfPCell(new Paragraph("Repeticiones", bold));
                        cellCabezeraEjercicioGM3.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.TOP);
                        cellCabezeraEjercicioGM3.setLeading(20f, 0f);
                        cellCabezeraEjercicioGM3.setBackgroundColor(myColor);
                        tableEjercicioGMsucular.addCell(cellCabezeraEjercicioGM3);

                        PdfPCell cellCabezeraEjercicioGM4 = new PdfPCell(new Paragraph("Receso", bold));
                        cellCabezeraEjercicioGM4.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.TOP);
                        cellCabezeraEjercicioGM4.setLeading(20f, 0f);
                        cellCabezeraEjercicioGM4.setBackgroundColor(myColor);
                        tableEjercicioGMsucular.addCell(cellCabezeraEjercicioGM4);

                        PdfPCell cellCabezeraEjercicioGM5 = new PdfPCell(new Paragraph("Peso", bold));
                        cellCabezeraEjercicioGM5.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.TOP);
                        cellCabezeraEjercicioGM5.setLeading(20f, 0f);
                        cellCabezeraEjercicioGM5.setBackgroundColor(myColor);
                        tableEjercicioGMsucular.addCell(cellCabezeraEjercicioGM5);

                        int aux2 = 1;
                        for (EjercicioGm ejercicioGm : lstEjerciciosGMuscularPDF) {
                            PdfPCell cellEjercicioGM = new PdfPCell(
                                    new Paragraph(ejercicioGm.getEjercicio().getNombre()));
                            cellEjercicioGM.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                            cellEjercicioGM.setLeading(20f, 0f);

                            PdfPCell cellEjercicioGM2 = new PdfPCell(
                                    new Paragraph(ejercicioGm.getNumeroSeries().toString()));
                            cellEjercicioGM2.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                            cellEjercicioGM2.setLeading(20f, 0f);

                            PdfPCell cellEjercicioGM3 = new PdfPCell(
                                    new Paragraph(ejercicioGm.getRepeticiones().toString()));
                            cellEjercicioGM3.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                            cellEjercicioGM3.setLeading(20f, 0f);

                            PdfPCell cellEjercicioGM4 = new PdfPCell(
                                    new Paragraph(ejercicioGm.getReceso().toString()));
                            cellEjercicioGM4.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                            cellEjercicioGM4.setLeading(20f, 0f);

                            PdfPCell cellEjercicioGM5 = new PdfPCell(
                                    new Paragraph(ejercicioGm.getPeso().toString()));
                            cellEjercicioGM5.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                            cellEjercicioGM5.setLeading(20f, 0f);

                            if (aux2 % 2 == 0) {
                                cellEjercicioGM.setBackgroundColor(myColor);
                                cellEjercicioGM2.setBackgroundColor(myColor);
                                cellEjercicioGM3.setBackgroundColor(myColor);
                                cellEjercicioGM4.setBackgroundColor(myColor);
                                cellEjercicioGM5.setBackgroundColor(myColor);
                            }

                            tableEjercicioGMsucular.addCell(cellEjercicioGM);
                            tableEjercicioGMsucular.addCell(cellEjercicioGM2);
                            tableEjercicioGMsucular.addCell(cellEjercicioGM3);
                            tableEjercicioGMsucular.addCell(cellEjercicioGM4);
                            tableEjercicioGMsucular.addCell(cellEjercicioGM5);
                            aux2++;
                        }
                        cellGMuscular2.addElement(tableEjercicioGMsucular);
                    }
                    tableGMuscular.addCell(cellGMuscular);
                    tableGMuscular.addCell(cellGMuscular2);
                    aux++;
                }
                cellDia2.addElement(tableGMuscular);
            }
            tableDias.addCell(cellDia);
            tableDias.addCell(cellDia2);
        }

        LineSeparator ls = new LineSeparator();
        document.add(tableEncabezado);
        document.add(ls);
        document.add(tableDatosUsuario);
        document.add(tableFechas);
        document.add(tableMedidas);
        document.add(tableDias);
        document.close();
    } catch (DocumentException | FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ex) {
        Logger.getLogger(BeanGestionRutinas.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ashish.medicine.admin.invoice.InvoiceAction.java

public String printInvoice() {

    try {//from w w  w. j  a  v a  2s . c  o m
        ServletContext context = ServletActionContext.getServletContext();

        String logoPath = context.getRealPath("") + "\\resources\\js\\dashboard\\images\\shared\\logo.png";
        String pdfFilePath = context.getRealPath(".") + "\\Invoice.pdf";
        invoiceBean.setPdfPath(pdfFilePath);
        invoiceBean.setLogoPath(logoPath);
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));
        document.open();

        new InvoiceServiceImpl().printInvoice(invoiceBean);
        new MyAccountServiceImpl().myAccount(myaccountBean);
        viewInvoice();
        addInvoiceContentIntoPDF(document);

        document.close();
        try {
            filename = "Invoice";
            inputStream = new FileInputStream(pdfFilePath);
            if (totalRecords != null && totalRecords.size() > 0) {
                InvoiceBean iBean = totalRecords.get(0);
                filename = iBean.getCustomerName() + "-" + iBean.getBillDate();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AppException("");
        } finally {
            //              os.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
        return "failure";
    }
    return Action.SUCCESS;
}

From source file:com.atacadao.almoxarifado.model.GerandoPDF.java

public void pdfDeSaida(ArrayList<Equipamento> equipamentos, String solicitante, String autorizante,
        String responsavel, String numeroSaida) {
    Document documento = new Document();

    try {//w w  w . j  av  a  2 s.  c om

        Path path = Paths.get("\\files\\saidas.pdf");

        if (!Files.isDirectory(path.getParent())) {
            Files.createDirectory(path.getParent());
            Files.createFile(path);
        }

        PdfWriter pdf;
        pdf = PdfWriter.getInstance(documento, new FileOutputStream("\\files\\saidas.pdf"));

        documento.open();
        documento.addTitle("SOLICITAO DE EQUIPAMENTOS E PRODUTOS");

        /**
         * Responsavel pelo cabealho do documento
         */
        Image imagem = Image.getInstance("atacadao.jpg");
        imagem.setAlignment(Element.ALIGN_CENTER);
        documento.add(imagem);

        Paragraph titulo = new Paragraph("SOLICITAO DE EQUIPAMENTOS E PRODUTOS", new com.itextpdf.text.Font(
                com.itextpdf.text.Font.FontFamily.UNDEFINED, 16, 0, BaseColor.BLACK));

        titulo.setAlignment(Element.ALIGN_CENTER);
        documento.add(titulo);

        documento.setMargins(0, 0, 18, 0);

        Date datas = new Date();
        Locale local = new Locale("pt", "BR");
        SimpleDateFormat sdf = new SimpleDateFormat("E dd/MM/yyyy", local);

        Paragraph espaco = new Paragraph(
                "\n\nDeclaro para os devidos fins que eu " + solicitante + " recebi na " + sdf.format(datas)
                        + " os equipamentos abaixo relacionados da empresa " + "Atacado dos Pisos por "
                        + autorizante + " e autorizado por " + responsavel + ".\n",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, 0,
                        BaseColor.BLACK));

        documento.add(espaco);

        documento.add(new Paragraph("\n Numero de registro : " + numeroSaida + "\n\n"));
        /**
         * Responsavel por cria a tabela da sada dos equipamentos
         */
        PdfPTable pdfT = new PdfPTable(4);
        PdfPCell celulas = new PdfPCell(new Paragraph(
                "Relao de equipamentos solicitados para seus devidos fins."
                        + " Favor caso haja devoluo manter o maximo possvel do estado atual dos mesmos. Grato !!!",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.UNDEFINED, 11, 0,
                        BaseColor.GRAY)));
        celulas.setColspan(4);

        PdfPCell patrimonio = new PdfPCell(new Paragraph("PATRIMONIO", new com.itextpdf.text.Font(
                com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, 0, BaseColor.WHITE)));
        patrimonio.setBackgroundColor(BaseColor.GRAY);
        patrimonio.setPadding((float) 1);

        PdfPCell Nome = new PdfPCell(new Paragraph("NOME", new com.itextpdf.text.Font(
                com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, 0, BaseColor.WHITE)));
        Nome.setBackgroundColor(BaseColor.GRAY);
        Nome.setPadding((float) 1);

        PdfPCell Situacao = new PdfPCell(new Paragraph("SITUAO", new com.itextpdf.text.Font(
                com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, 0, BaseColor.WHITE)));
        Situacao.setBackgroundColor(BaseColor.GRAY);
        Situacao.setPadding((float) 1);

        PdfPCell valor = new PdfPCell(new Paragraph("DESTINO", new com.itextpdf.text.Font(
                com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, 0, BaseColor.WHITE)));
        valor.setBackgroundColor(BaseColor.GRAY);
        valor.setPadding((float) 1);

        pdfT.addCell(celulas);
        pdfT.addCell(patrimonio);
        pdfT.addCell(Nome);
        pdfT.addCell(Situacao);
        pdfT.addCell(valor);

        for (Equipamento equipamento : equipamentos) {

            PdfPCell patrimonios = new PdfPCell(
                    new Paragraph(equipamento.getPatrimonio(), new com.itextpdf.text.Font(
                            com.itextpdf.text.Font.FontFamily.UNDEFINED, 10, 0, BaseColor.BLACK)));
            patrimonios.setBackgroundColor(BaseColor.WHITE);
            Situacao.setPadding((float) 0.8);
            pdfT.addCell(patrimonios);

            PdfPCell nomes = new PdfPCell(new Paragraph(equipamento.getNome(), new com.itextpdf.text.Font(
                    com.itextpdf.text.Font.FontFamily.UNDEFINED, 10, 0, BaseColor.BLACK)));
            nomes.setBackgroundColor(BaseColor.WHITE);
            nomes.setPadding((float) 0.8);
            pdfT.addCell(nomes);

            PdfPCell situacoes = new PdfPCell(
                    new Paragraph(equipamento.getSituacao(), new com.itextpdf.text.Font(
                            com.itextpdf.text.Font.FontFamily.UNDEFINED, 10, 0, BaseColor.BLACK)));
            situacoes.setBackgroundColor(BaseColor.WHITE);
            situacoes.setPadding((float) 0.8);
            pdfT.addCell(situacoes);

            PdfPCell valores = new PdfPCell(new Paragraph(equipamento.getCodigo(), new com.itextpdf.text.Font(
                    com.itextpdf.text.Font.FontFamily.UNDEFINED, 10, 0, BaseColor.BLACK)));
            valores.setBackgroundColor(BaseColor.WHITE);
            valores.setPadding((float) 0.8);
            pdfT.addCell(valores);

        }
        documento.add(pdfT);

        /**
         * Cria tabela para assinatura do solicitante e autorizado
         */
        PdfPTable pdfTs = new PdfPTable(5);

        Paragraph sol = new Paragraph("\n\n" + solicitante,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, Font.ITALIC));
        sol.setAlignment(Element.ALIGN_CENTER);
        PdfPCell ass = new PdfPCell(sol);
        ass.setBorder(0);
        ass.setBorderWidthTop(1);
        ass.setColspan(2);

        PdfPCell espacos = new PdfPCell();
        espacos.setBorder(0);

        Paragraph auth = new Paragraph("\n\n" + autorizante,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.UNDEFINED, 12, Font.ITALIC));
        auth.setAlignment(Element.ALIGN_CENTER);
        PdfPCell ass2 = new PdfPCell(auth);
        ass2.setBorder(0);
        ass2.setBorderWidthTop(1);
        ass2.setColspan(2);

        pdfTs.addCell(ass);
        pdfTs.addCell(espacos);
        pdfTs.addCell(ass2);

        documento.add(new Paragraph("\n\n\n"));
        documento.add(pdfTs);

        documento.close();
        ImpressaoDeDocumentos imprimir = new ImpressaoDeDocumentos("\\files\\saidas.pdf");

        //            Desktop.getDesktop().open(new File("\\files\\saidas.pdf"));

    } catch (DocumentException ex) {
        Logger.getLogger(GerandoPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GerandoPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GerandoPDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}