Example usage for com.itextpdf.layout Document close

List of usage examples for com.itextpdf.layout Document close

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Closes the document and associated PdfDocument.

Usage

From source file:Accessor.MyPdfWriter.java

static <T extends Object & Serializable> void write(PdfAccessor pdfAccessor, T element) {
    try {//from www.j ava2  s.c  om
        String DEST = pdfAccessor.getPath();
        LOGGER.info("Writing pdf to: " + DEST);
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        if (element.getClass().equals(NewStudent.class)) {

            //PdfFont textFont = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H, true);
            NewStudent student = (NewStudent) element;
            //Initialize PDF writer
            PdfWriter writer = new PdfWriter(DEST);
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(writer);
            // Initialize document
            Document document = new Document(pdf);
            //Add paragraph to the document

            //Creating header
            document.add(new Paragraph("Anno scolastico: " + NewStudentWizBean.getSchoolYear())
                    .setTextAlignment(TextAlignment.CENTER));
            document.add(new Paragraph("SCHEDA D'ISCRIZIONE").setBold().setFontSize(18)
                    .setTextAlignment(TextAlignment.CENTER));

            //Creating Body pt 1
            document.add(new Paragraph("\nDati Personali").setBold());
            document.add(new Paragraph(student.toDatiPersonali()));
            document.add(new Paragraph("\nContatti").setBold());
            document.add(new Paragraph(student.toContatti()));

            //Creating Body pt 2
            document.add(new Paragraph("Ambito di interesse").setBold());
            document.add(new Paragraph("Corso di italiano"
                    + "\n [    ] 10.00 - 11.30       [    ] 18.00 - 19.30       [    ] 19.30  21.00"
                    + "\nCorso di informatica     [    ]" + "\nCertificazione A2     [    ]"));

            //Creating Tail
            document.add(new Paragraph("\n\nFirma studente: _______________________")
                    .setTextAlignment(TextAlignment.RIGHT));
            document.add(new Paragraph(
                    "Il sottoscritto autorizza al trattamento dei dati personali, secondo quanto previsto dal Decreto legislativo 30 giugno 2003, n. 196.")
                            .setTextAlignment(TextAlignment.RIGHT).setFontSize(9).setItalic());
            document.add(new Paragraph(student.toInfo()).setTextAlignment(TextAlignment.RIGHT));
            document.add(new Paragraph("\n\nTest d'ingresso:").setBold());
            document.add(new Paragraph("Esito: _______________________"));
            document.add(new Paragraph("Data: _______________________"));

            //Close document
            document.close();
        } else {
            LOGGER.info("Unsupported element class : " + element.getClass());
        }

    } catch (Exception e) {
        LOGGER.info("Exception writing pdf : " + e.getMessage());
    }

}

From source file:cl.a2r.wsmicampov2.dao.TrasladoDAO.java

public static void generarDocumentoTraslado(Transaccion trx, Integer trasladoId) throws SQLException {

    Traslado traslado = selectTrasladoById(trx, trasladoId);
    List<String> listDiios = selectDiiosTrasladoById(trx, trasladoId);
    try {//from ww  w  .j av  a 2  s .  c o m

        Integer identificadorTraslado = trasladoId;
        String fundoOrigen = traslado.getFundoOrigen();
        String fundoDestino = traslado.getFundoDestino();
        Integer cantAnimales = listDiios.size();
        Date fecha = traslado.getFecha();
        String nombreChofer = traslado.getNombreChofer();
        String rutChofer = traslado.getRutChofer();
        String patenteCamion = traslado.getPatenteCamion();
        String patenteAcoplado = traslado.getAcopladoPatente();
        String nombreTransportista = traslado.getNombreTransportista();
        String rutTransportista = traslado.getRutTransportista();

        String correoDestino = traslado.getCorreo();

        DateFormat df = new SimpleDateFormat("dd-MM-yyyy hh_mm_ss");
        DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
        Date today = Calendar.getInstance().getTime();
        String reportDate = df.format(today);
        String reportDate2 = df2.format(today);

        String fileName = "Traslado Nro. " + identificadorTraslado + "-" + reportDate2 + " " + fundoOrigen + "_"
                + fundoDestino;
        //            String fileRoot="Z:\\Chilterra\\MiCampoGuias\\"+fileName+".pdf";

        String fileRoot = "/usr/share/MiCampoGuiasUpload/" + fileName + ".pdf";

        PdfWriter writer = new PdfWriter(fileRoot);

        PdfDocument pdf = new PdfDocument(writer);

        Document document = new Document(pdf);

        addPageToGuia(traslado, listDiios, document, cantAnimales);
        addSpaces(document);

        //Firmas        
        Table firmas = new Table(3);
        firmas.addCell(CellHelper.getCellFirma("Responsable fundo origen", TextAlignment.CENTER));
        firmas.addCell(CellHelper.getCell("", TextAlignment.LEFT));
        firmas.addCell(CellHelper.getCellFirma("Transportista", TextAlignment.CENTER));
        document.add(firmas);

        copiaPara("Fundo origen", document);

        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        addDiiosPage(document, listDiios);
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        addPageToGuia(traslado, listDiios, document, cantAnimales);
        addSpaces(document);

        Table firmas2 = new Table(3);
        firmas2.addCell(CellHelper.getCellFirma("Responsable fundo destino", TextAlignment.CENTER));
        firmas2.addCell(CellHelper.getCell("", TextAlignment.LEFT));
        firmas2.addCell(CellHelper.getCellFirma("Transportista", TextAlignment.CENTER));
        document.add(firmas2);

        copiaPara("Fundo destino", document);

        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        addDiiosPage(document, listDiios);

        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        addPageToGuia(traslado, listDiios, document, cantAnimales);
        addSpaces(document);

        Table firmas3 = new Table(3);
        firmas3.addCell(CellHelper.getCellFirma("Responsable fundo origen", TextAlignment.CENTER));
        firmas3.addCell(CellHelper.getCell("", TextAlignment.LEFT));
        firmas3.addCell(CellHelper.getCellFirma("Responsable fundo destino", TextAlignment.CENTER));
        document.add(firmas3);

        copiaPara("Transportista", document);

        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        addDiiosPage(document, listDiios);

        document.close();

        File file = new File(fileRoot);
        InputStream inputStream = new FileInputStream(file);
        int fileLength = (int) file.length();

        byte[] bytes = new byte[fileLength];
        inputStream.read(bytes);

        Correo correo = new Correo();
        correo.setFrom("desarrollador@chilterra.com");
        correo.setTo(correoDestino + ";" + "sipec@chilterra.com");

        correo.setSubject("Traslado interno de animales Nro: " + trasladoId);
        correo.setBody("");

        correo.addAdjunto(bytes, "application/pdf", fileName + ".pdf");
        correo.enviar();
    } catch (Exception ex) {

    }
}

From source file:com.asptt.plongee.resa.util.UtilsFSpdf.java

public Document createPdfFS(String dest, FicheSecurite fs)
            throws IOException, FileNotFoundException, java.io.IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        PageSize ps = PageSize.A4.rotate();
        //calcul du nombre de page (si + de 8 palanques => 2 pages)
        int nbPage = 1;
        if (fs.getPalanques().size() > 8) {
            nbPage = 2;//  w  w w . jav a2 s .  c  om
        }
        pdfDoc.addNewPage(ps);
        Document doc = new Document(pdfDoc);
        Table entete = createEntete(fs, 1, nbPage);
        doc.add(entete);

        // style pour les plongeurs
        Style s_plongeur = new Style();
        PdfFont fontPlongeur = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
        s_plongeur.setFont(fontPlongeur).setFontSize(10);
        s_plongeur.setFontColor(Color.BLACK);
        // Deuxieme table pour les palanques 
        Table tablePalanques = new Table(4);
        for (int i = 0; i < 8; i++) {
            createTablePlongeur(tablePalanques, fs, i, s_plongeur);
        }
        doc.add(tablePalanques);
        if (nbPage == 2) {
            Table tablePalanques2 = new Table(4);
            pdfDoc.addNewPage(ps);
            Table entete2 = createEntete(fs, 2, nbPage);
            doc.add(entete2);
            for (int i = 8; i < 16; i++) {
                createTablePlongeur(tablePalanques2, fs, i, s_plongeur);
            }
            doc.add(tablePalanques2);
        }
        doc.close();
        return doc;
    }

From source file:com.asptt.plongee.resa.util.UtilsFSpdf.java

public void createPdf(String dest, FicheSecurite fs)
            throws IOException, FileNotFoundException, java.io.IOException {
        //Initialize PDF writer
        PdfWriter writer = new PdfWriter(dest);

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(writer);

        // Initialize document
        Document document = new Document(pdf);
        //Add paragraph to the document
        document.add(new Paragraph(fs.getSite()));
        // Add content
        Text title1 = new Text("The Strange Case of ").setFontColor(Color.BLUE);
        Text title2 = new Text("Dr. Jekyll SIIMMOONN").setStrokeColor(Color.GREEN)
                .setTextRenderingMode(PdfCanvasConstants.TextRenderingMode.FILL_STROKE);
        Text title3 = new Text(" and ");
        Text title4 = new Text("Mr. Hyde").setStrokeColor(Color.RED).setStrokeWidth(0.5f)
                .setTextRenderingMode(PdfCanvasConstants.TextRenderingMode.STROKE);
        Paragraph p = new Paragraph().setFontSize(24).add(title1).add(title2).add(title3).add(title4);
        document.add(p);/*  w  w  w .j av a  2s.c  om*/

        Style normal = new Style();
        PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
        normal.setFont(font).setFontSize(14);
        Style code = new Style();
        PdfFont monospace = PdfFontFactory.createFont(FontConstants.COURIER);
        code.setFont(monospace).setFontColor(Color.RED).setBackgroundColor(Color.LIGHT_GRAY);
        Paragraph p2 = new Paragraph();
        p2.add(new Text("The Strange Case of ").addStyle(normal));
        p2.add(new Text("Dr. Jekyll").addStyle(code));
        p2.add(new Text(" and ").addStyle(normal));
        p2.add(new Text("Mr. Hyde").addStyle(code));
        p2.add(new Text(".").addStyle(normal));
        document.add(p2);

        //Close document
        document.close();
        //        PageSize ps = PageSize.A4.rotate();
        //        PdfPage page = pdf.addNewPage(ps);
        //        PdfCanvas canvas = new PdfCanvas(page);
        //        canvas.concatMatrix(1, 0, 0, 1, ps.getWidth() / 2, ps.getHeight() / 2);
        ////Draw X axis
        //        canvas.moveTo(-(ps.getWidth() / 2 - 15), 0)
        //                .lineTo(ps.getWidth() / 2 - 15, 0)
        //                .stroke();
        ////Draw X axis arrow
        //        canvas.setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND)
        //                .moveTo(ps.getWidth() / 2 - 25, -10)
        //                .lineTo(ps.getWidth() / 2 - 15, 0)
        //                .lineTo(ps.getWidth() / 2 - 25, 10).stroke()
        //                .setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.MITER);
        ////Draw Y axis
        //        canvas.moveTo(0, -(ps.getHeight() / 2 - 15))
        //                .lineTo(0, ps.getHeight() / 2 - 15)
        //                .stroke();
        ////Draw Y axis arrow
        //        canvas.saveState()
        //                .setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND)
        //                .moveTo(-10, ps.getHeight() / 2 - 25)
        //                .lineTo(0, ps.getHeight() / 2 - 15)
        //                .lineTo(10, ps.getHeight() / 2 - 25).stroke()
        //                .restoreState();
        ////Draw X serif
        //        for (int i = -((int) ps.getWidth() / 2 - 61);
        //                i < ((int) ps.getWidth() / 2 - 60); i += 40) {
        //            canvas.moveTo(i, 5).lineTo(i, -5);
        //        }
        ////Draw Y serif
        //        for (int j = -((int) ps.getHeight() / 2 - 57);
        //                j < ((int) ps.getHeight() / 2 - 56); j += 40) {
        //            canvas.moveTo(5, j).lineTo(-5, j);
        //        }
        //        canvas.stroke();
        ////        pdf.close();
        ////        PdfPage page = pdf.addNewPage();
        ////        Rectangle rectangle = new Rectangle(x, y, 100, 100);
        ////        Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
        //        float llx = 0;
        //        float lly = 0;
        //        float urx = 100;
        //        float ury = 100;
        //        for (Palanque palanque : fs.getPalanques()) {
        //            llx=llx+5;
        //            lly=lly+70;
        //            Rectangle rectangle = new Rectangle(llx, lly, urx-llx, ury-lly);
        ////            PdfCanvas canvas = new PdfCanvas(page);
        //            canvas = new PdfCanvas(page);
        ////            PdfCanvas canvas = new PdfCanvas(pdf.addNewPage());
        ////            pdfCanvas.rectangle(rectangle);
        //            canvas.setStrokeColor(Color.RED).setLineWidth(0.5f).rectangle(rectangle).stroke();
        ////            canvas = new Canvas(pdfCanvas, pdf, rectangle);
        ////            pdfCanvas.stroke();
        //            PdfFont fontRoman = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
        //            PdfFont bold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);
        //            Text title = new Text("GUIDE palanque:"+palanque.getNomCompletGuide()).setFont(bold);
        //            Text author = new Text("PLONGEUR 1 palanque:"+palanque.getNomCompletPlongeur1()).setFont(fontRoman);
        //            Paragraph p3 = new Paragraph().add(title).add(" by ").add(author);
        //            new Canvas(canvas,pdf,rectangle).add(p3);
        ////            canvas.add(p3);
        //        }
        //Close document
        pdf.close();

    }

From source file:com.asptt.plongee.resa.util.UtilsFSpdf.java

public void createPdfPlongee(String dest, Plongee plongee)
            throws IOException, FileNotFoundException, java.io.IOException {
        PageSize ps = PageSize.A4.rotate();
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        pdfDoc.addNewPage(ps);// w  w  w.j a v a2 s.c om
        Document doc = new Document(pdfDoc);
        float[] columnWidths = { 20, 20, 5, 10, 15, 15, 15 };
        // table : premiere table pour les parametres de la plonge
        Table table = new Table(columnWidths);
        table.setMargins(0, 0, 0, 0);
        table.setWidthPercent(100);
        // entete style pour les titres
        Style s_titre = new Style();
        PdfFont fontEntete = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
        s_titre.setFont(fontEntete).setFontSize(12);
        s_titre.setFontColor(Color.ORANGE);
        // style pour l'entete de la table
        Style s_entete = new Style();
        PdfFont fontLibelle = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
        s_entete.setFont(fontLibelle).setFontSize(12);
        s_entete.setFontColor(Color.BLUE);

        Paragraph entete1 = new Paragraph();
        entete1.add(new Text("Plong\u00e9e du " + ResaUtil.getJourDatePlongee(plongee.getDatePlongee()) + "    '"
                + ResaUtil.getHeurePlongee(plongee.getDatePlongee()) + "'\n").addStyle(s_titre));
        entete1.add(
                new Text("Nombre de participants " + plongee.getParticipants().size() + "\n").addStyle(s_titre));
        entete1.add(new Text("\n").addStyle(s_titre));
        entete1.add(new Text("Inscrit\n").addStyle(s_titre));

        Cell cellEntete1 = new Cell(1, 7);
        cellEntete1.add(entete1);
        cellEntete1.setBorderRight(Border.NO_BORDER);
        //        cellEntete1.setBackgroundColor(Color.BLUE);
        cellEntete1.setHorizontalAlignment(HorizontalAlignment.LEFT);
        table.addCell(cellEntete1);

        Cell cellNom = new Cell().add(new Paragraph("Nom"));
        cellNom.setTextAlignment(TextAlignment.CENTER);
        cellNom.setFontSize(8);
        cellNom.setFontColor(Color.BLACK);
        cellNom.setPadding(5);
        cellNom.setBackgroundColor(new DeviceRgb(140, 221, 8));
        table.addCell(cellNom);

        Cell cellPrenom = new Cell().add(new Paragraph("Prnom"));
        cellPrenom.setTextAlignment(TextAlignment.CENTER);
        cellPrenom.setFontSize(8);
        cellPrenom.setFontColor(Color.BLACK);
        cellPrenom.setPadding(5);
        cellPrenom.setBackgroundColor(new DeviceRgb(140, 221, 8));
        table.addCell(cellPrenom);

        Cell cellNiveau = new Cell().add(new Paragraph("Niveau"));
        cellNiveau.setTextAlignment(TextAlignment.CENTER);
        cellNiveau.setFontSize(8);
        cellNiveau.setFontColor(Color.BLACK);
        cellNiveau.setPadding(5);
        cellNiveau.setBackgroundColor(new DeviceRgb(140, 221, 8));
        table.addCell(cellNiveau);

        Cell cellAptitude = new Cell().add(new Paragraph("Aptitude"));
        cellAptitude.setTextAlignment(TextAlignment.CENTER);
        cellAptitude.setFontSize(8);
        cellAptitude.setFontColor(Color.BLACK);
        cellAptitude.setPadding(5);
        cellAptitude.setBackgroundColor(new DeviceRgb(140, 221, 8));
        table.addCell(cellAptitude);

        Cell cellTelephone1 = new Cell().add(new Paragraph("Tlphone"));
        cellTelephone1.setTextAlignment(TextAlignment.CENTER);
        cellTelephone1.setFontSize(8);
        cellTelephone1.setFontColor(Color.BLACK);
        cellTelephone1.setPadding(5);
        cellTelephone1.setBackgroundColor(new DeviceRgb(140, 221, 8));
        table.addCell(cellTelephone1);

        Cell cellCommentaire = new Cell().add(new Paragraph("Commentaire"));
        cellCommentaire.setTextAlignment(TextAlignment.CENTER);
        cellCommentaire.setFontSize(8);
        cellCommentaire.setFontColor(Color.BLACK);
        cellCommentaire.setPadding(5);
        cellCommentaire.setBackgroundColor(new DeviceRgb(140, 221, 8));
        table.addCell(cellCommentaire);

        List<Adherent> adherentsInscrit = plongee.getParticipants();

        for (Adherent adherent : adherentsInscrit) {
            Cell cellNomP = new Cell().add(new Paragraph(adherent.getNom()));
            cellNomP.setTextAlignment(TextAlignment.CENTER);
            cellNomP.setFontSize(8);
            cellNomP.setFontColor(Color.BLACK);
            cellNomP.setPadding(5);
            cellNomP.setBackgroundColor(new DeviceRgb(140, 221, 8));
            table.addCell(cellNomP);

            Cell cellPrenomP = new Cell().add(new Paragraph(adherent.getPrenom()));
            cellPrenomP.setTextAlignment(TextAlignment.CENTER);
            cellPrenomP.setFontSize(8);
            cellPrenomP.setFontColor(Color.BLACK);
            cellPrenomP.setPadding(5);
            cellPrenomP.setBackgroundColor(new DeviceRgb(140, 221, 8));
            table.addCell(cellPrenomP);

            // Ds que le plongeur est encadrant, on affiche son niveau d'encadrement
            String niveauAffiche = adherent.getPrerogative();
            // Pour les externes, le niveau est suffix par (Ext.)
            if (adherent.getActifInt() == 2) {
                niveauAffiche = niveauAffiche + " (Ext.)";
            }
            Cell cellNiveauP = new Cell().add(new Paragraph(niveauAffiche));
            cellNiveauP.setTextAlignment(TextAlignment.CENTER);
            cellNiveauP.setFontSize(8);
            cellNiveauP.setFontColor(Color.BLACK);
            cellNiveauP.setPadding(5);
            cellNiveauP.setBackgroundColor(new DeviceRgb(140, 221, 8));
            table.addCell(cellNiveauP);

            Cell cellAptitudeP;
            if (null == adherent.getAptitude()) {
                cellAptitudeP = new Cell().add(new Paragraph("  "));
            } else {
                cellAptitudeP = new Cell().add(new Paragraph(adherent.getAptitude().getText()));
            }
            cellAptitudeP.setTextAlignment(TextAlignment.CENTER);
            cellAptitudeP.setFontSize(8);
            cellAptitudeP.setFontColor(Color.BLACK);
            cellAptitudeP.setPadding(5);
            cellAptitudeP.setBackgroundColor(new DeviceRgb(140, 221, 8));
            table.addCell(cellAptitudeP);

            Cell cellTelephone1P = new Cell().add(new Paragraph(adherent.getTelephone()));
            cellTelephone1P.setTextAlignment(TextAlignment.CENTER);
            cellTelephone1P.setFontSize(8);
            cellTelephone1P.setFontColor(Color.BLACK);
            cellTelephone1P.setPadding(5);
            cellTelephone1P.setBackgroundColor(new DeviceRgb(140, 221, 8));
            table.addCell(cellTelephone1P);

            Cell cellCommentaireP = new Cell().add(new Paragraph(adherent.getCommentaire()));
            cellCommentaireP.setTextAlignment(TextAlignment.CENTER);
            cellCommentaireP.setFontSize(8);
            cellCommentaireP.setFontColor(Color.BLACK);
            cellCommentaireP.setPadding(5);
            cellCommentaireP.setBackgroundColor(new DeviceRgb(140, 221, 8));
            table.addCell(cellCommentaireP);

        }
        doc.add(table);
        doc.close();
    }

From source file:com.isw.cec.Servlet.GenerarFoliosServlet.java

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String appPath = request.getServletContext().getRealPath("");
    String savePath = appPath + File.separator + SAVE_DIR;

    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists())
        fileSaveDir.mkdirs();//  w w w . j  av  a2  s . co m

    String fileName = java.util.UUID.randomUUID().toString() + ".pdf";
    Curso curso = (Curso) request.getAttribute("curso");
    List<Entry<String, String>> alum_fol = Reader.getAlumFolios(curso.getID());

    OutputStream fos = new FileOutputStream(savePath + File.separator + fileName);
    PdfWriter writer = new PdfWriter(fos);

    PdfDocument pdf = new PdfDocument(writer);

    Document document = new Document(pdf, PageSize.A4);
    document.setMargins(85, 57, 71, 71);

    PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
    PdfFont bold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);

    Paragraph p = new Paragraph("Folios de los alumnos inscritos al curso");
    p.setTextAlignment(TextAlignment.CENTER);
    document.add(p);

    p = new Paragraph(curso.getNombre());
    p.setFont(bold);
    p.setTextAlignment(TextAlignment.CENTER);
    p.setMarginBottom(70);
    document.add(p);

    Table table = new Table(new float[] { 1, 1 });
    table.setWidthPercent(100);

    Cell c = new Cell().add(new Paragraph("ALUMNO").setFont(bold));
    c.setTextAlignment(TextAlignment.CENTER);
    table.addHeaderCell(c);

    c = new Cell().add(new Paragraph("FOLIO").setFont(bold));
    c.setTextAlignment(TextAlignment.CENTER);
    table.addHeaderCell(c);

    for (Entry<String, String> e : alum_fol) {
        table.addCell(new Cell().add(new Paragraph(e.getKey()).setFont(font)));
        table.addCell(new Cell().add(new Paragraph(e.getValue()).setFont(font)));
    }

    document.add(table);

    document.close();

    Writer.openCurso(curso.getID(), fileName);
    response.getWriter().println("OK");
}

From source file:com.js.quickestquail.ui.actions.io.ExportToPDFAction.java

private void writeAll(File outputFile) throws FileNotFoundException, IOException {

    // progress dialog
    JProgressDialog dialog = new JProgressDialog(UI.get(), false);
    dialog.setMaximum(DriveManager.get().getSelected().size());
    dialog.setTitle(java.util.ResourceBundle.getBundle("i18n/i18n").getString("export.pdf"));
    dialog.setVisible(true);/*  ww  w  . j av  a2  s .com*/

    // run this in a new Thread
    new Thread() {
        @Override
        public void run() {
            try {
                int nrOfMovies = 0;
                List<Entry<File, String>> entries = new ArrayList<>(
                        DriveManager.get().getSelected().entrySet());
                java.util.Collections.sort(entries, new Comparator<Entry<File, String>>() {
                    @Override
                    public int compare(Entry<File, String> o1, Entry<File, String> o2) {
                        Movie mov1 = CachedMovieProvider.get().getMovieByID(o1.getValue());
                        Movie mov2 = CachedMovieProvider.get().getMovieByID(o2.getValue());
                        return mov1.getTitle().compareTo(mov2.getTitle());
                    }
                });

                PdfWriter writer = new PdfWriter(new FileOutputStream(outputFile));
                PdfDocument pdf = new PdfDocument(writer);
                Document doc = new Document(pdf);

                for (Entry<File, String> en : entries) {
                    Movie mov = CachedMovieProvider.get().getMovieByID(en.getValue());

                    // update progress dialog
                    dialog.setText(mov.getTitle());
                    dialog.setProgress(nrOfMovies);

                    // add table
                    Table table = new Table(new float[] { 0.5f, 0.25f, 0.25f });
                    table.setWidthPercent(100);
                    table.setBorder(Border.NO_BORDER);

                    Cell cell;
                    cell = new Cell(5, 1);
                    cell.setBorder(Border.NO_BORDER);

                    try {
                        Image img = new Image(ImageDataFactory.create(new URL(mov.getPoster())));
                        cell.setNextRenderer(new ImageBackgroundCellRenderer(cell, img));
                    } catch (Exception ex) {
                    }

                    cell.setHeight(160);
                    cell.setWidth(100);

                    table.addCell(cell);

                    cell = new Cell(1, 1).add("Title").setBorder(Border.NO_BORDER);
                    table.addCell(cell);
                    cell = new Cell(1, 1).add(mov.getTitle()).setBorder(Border.NO_BORDER);
                    table.addCell(cell);

                    cell = new Cell(1, 1).add("Year").setBorder(Border.NO_BORDER);
                    table.addCell(cell);
                    cell = new Cell(1, 1).add(mov.getYear() + "").setBorder(Border.NO_BORDER);
                    table.addCell(cell);

                    cell = new Cell(1, 1).add("IMDB ID").setBorder(Border.NO_BORDER);
                    table.addCell(cell);
                    cell = new Cell(1, 1).add(mov.getImdbID()).setBorder(Border.NO_BORDER);
                    table.addCell(cell);

                    cell = new Cell(1, 1).add("IMDB Rating").setBorder(Border.NO_BORDER);
                    table.addCell(cell);
                    cell = new Cell(1, 1).add(mov.getImdbRating() + "").setBorder(Border.NO_BORDER);
                    table.addCell(cell);

                    cell = new Cell(1, 1).add("IMDB Votes").setBorder(Border.NO_BORDER);
                    table.addCell(cell);
                    cell = new Cell(1, 1).add(mov.getImdbVotes() + "").setBorder(Border.NO_BORDER);
                    table.addCell(cell);

                    doc.add(table);

                    nrOfMovies++;
                    if (nrOfMovies % 4 == 0) {
                        doc.add(new AreaBreak());
                    }

                    doc.add(new Paragraph(""));

                }

                // close IO
                doc.close();
                pdf.close();
                writer.close();

                // close dialog
                dialog.setVisible(false);

            } catch (Exception ex) {
            }
        }
    }.start();

}

From source file:com.tcay.slalom.UI.PDF.PDF_Results.java

License:Open Source License

protected void manipulatePdf(String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    Table table = new Table(8);
    for (int i = 0; i < 16; i++) {
        table.addCell("hi");
    }//from   www. j av a2  s  .co  m
    doc.add(table);

    doc.close();
}

From source file:com.tcay.slalom.UI.PDF.PDF_Results.java

License:Open Source License

public void doit(String title, ArrayList<RaceRun> runs, boolean breakOnClassChange) {
    Document doc = null;
    Table table = null;//  www.  j  a va  2s. c om

    try {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        // new PDF_Results().manipulatePdf(DEST);

        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        //Document
        doc = new Document(pdfDoc);

        table = new Table(9); // # of columns
        // for (int i = 0; i < 16; i++) {
        //     table.addCell("hi");
        // }

    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
    }

    String lastBoatClass = null;
    for (RaceRun r : runs) {

        float totalTime;

        if (breakOnClassChange) {
            if (lastBoatClass != null) {
                if (lastBoatClass.compareTo(r.getBoat().getBoatClass()) != 0)
                    ;
                //   log.info("---");
            }
            lastBoatClass = r.getBoat().getBoatClass();
        }
        totalTime = (float) r.getTotalPenalties();
        totalTime += r.getElapsed();
    }

    try {

        ArrayList<Result> sorted = Race.getInstance().getTempResults();
        for (Result r : sorted) {
            if (true || breakOnClassChange) { //Fixme  constant true
                if (lastBoatClass != null) {
                    if (lastBoatClass.compareTo(r.getBoat().getBoatClass()) != 0)
                        ;
                    //                            output.newLine();
                }
                if (lastBoatClass == null || lastBoatClass.compareTo(r.getBoat().getBoatClass()) != 0) {
                    //                        output.write(r.getBoat().getBoatClass());
                    //                        output.newLine();
                }
                lastBoatClass = r.getBoat().getBoatClass();
            }
            String s1;

            //                Cell cell23 = new Cell(1, 6).add("a Class ???multi 1,3 and 1,4");
            //                table.addCell(cell23);
            //                table.startNewRow();

            s1 = String.format("%1$3s", r.getBoat().getRacer().getBibNumber());
            table.addCell(s1);

            String s = r.getBoat().getRacer().getShortName();
            s1 = String.format("%1$-15s", s);
            table.addCell(s1);

            s1 = r.getRun1().getResultString();
            table.addCell(s1);

            s1 = r.getRun1().getPenaltyString();
            table.addCell(s1);

            s1 = r.getRun1().getTotalTimeString();
            table.addCell(s1);

            if (r.getRun2() != null) {
                table.startNewRow();

                table.addCell(".");
                table.addCell("..");
                s1 = r.getRun2().getResultString();
                table.addCell(s1);

                s1 = r.getRun2().getPenaltyString();
                table.addCell(s1);

                s1 = r.getRun2().getTotalTimeString();
                table.addCell(s1);

            }
            //                else {
            //    table.addCell("")//;

            //}

            table.startNewRow();

            /// todo must integrate TH results before sort  - DONE VERIFY 10/11/2013
            //                output.write("   best=");
            //                s1 = r.getBestRun() != null ? r.getBestRun().formatTimeTotalOnly() : RaceRun.TIME_ONLY_FILL;
            //                output.write(s1);

            //                if (r.getBestRun().getPhotoCellRaceRun() != null) {    /// todo must integrate TH results before sort
            //                    output.write(ResultsTable.TIMINGMODE_AUTOMATIC);
            //                }
            //                output.newLine();
        }

        PdfFont f = PdfFontFactory.createFont(FontConstants.HELVETICA);
        Cell cell = new Cell(1, 3);

        cell.add(new Paragraph("Class K1 ... or whateever")).setFont(f).setFontSize(13)
                .setFontColor(DeviceGray.WHITE).setBackgroundColor(DeviceGray.BLACK);
        //  .setTextAlignment(TextAlignment.CENTER);

        table.addHeaderCell(cell);

        /*            for (int i = 0; i < 2; i++) {
        Cell[] headerFooter = new Cell[] {
                new Cell().setBackgroundColor(new DeviceGray(0.75f)).add("#"),
                new Cell().setBackgroundColor(new DeviceGray(0.75f)).add("Key"),
                new Cell().setBackgroundColor(new DeviceGray(0.75f)).add("Value")
        };
        for (Cell hfCell : headerFooter) {
            if (i == 0) {
                table.addHeaderCell(hfCell);
            } else {
                table.addFooterCell(hfCell);
            }
        }
                    }
                    for (int counter = 1; counter < 20; counter++) {
        table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(String.valueOf(counter)));
        table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add("key " + counter));
        table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add("value " + counter));
                    }
                
        */

        doc.add(table);

        doc.close();

    } catch (Exception e) {
        System.out.println(e);
        System.out.println(e.getStackTrace());
        e.printStackTrace();

        //           log.write(e);
    } finally {
        try {
            //                output.close();
        } catch (Exception ex) {
            System.out.println(ex);
            System.out.println(ex.getStackTrace());

            ex.printStackTrace();

        }
    }

}

From source file:controller.PasesDeCortesiaController.java

public void exportPDF() throws RemoteException, NotBoundException, FileNotFoundException, IOException {
    Registry reg = LocateRegistry.getRegistry(host, 27019);
    oasiscrud.oasisrimbd inter = (oasiscrud.oasisrimbd) reg.lookup("OasisSev");
    FileChooser file = new FileChooser();
    file.getExtensionFilters().add(new FileChooser.ExtensionFilter("Documento PDF", " *.pdf"));
    File f = file.showSaveDialog(null);
    PdfWriter writer = new PdfWriter(f.getAbsolutePath());
    PdfDocument pdf = new PdfDocument(writer);
    pdf.setDefaultPageSize(PageSize.LETTER);
    Document document = new Document(pdf);
    com.itextpdf.layout.element.Image img = new com.itextpdf.layout.element.Image(
            ImageDataFactory.create(getClass().getResource("/images/pdf-logo.png")));
    img.setHorizontalAlignment(HorizontalAlignment.CENTER);
    document.add(img);//from  w ww .  j  a va 2s. co m
    generaTitulo(document, "Lista de Pases de Cortesia");
    document.add(new Paragraph("\n"));
    Table t = generaCabezera(Arrays.asList("Nombre", "Cedula", "Telefono", "Codigo", "Invitados", "Fecha"));
    document.add(t);
    for (int i = 0; i < tabla.getItems().size(); i++) {
        generaPaseCortesia(document, tabla.getItems().get(i));
        white *= -1;
    }

    document.close();
}