Example usage for com.itextpdf.text.pdf PdfWriter close

List of usage examples for com.itextpdf.text.pdf PdfWriter close

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter close.

Prototype

@Override
public void close() 

Source Link

Document

Signals that the Document was closed and that no other Elements will be added.

Usage

From source file:pkginterface.PayByCash.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    String validation = "[0-9]+(\\.){0,1}[0-9]";
    String cashReceive = cashReceived.getText();
    if (cashReceive.equals("")) {
        JOptionPane.showMessageDialog(null, "Please Fill in the Price!", "Error!", JOptionPane.ERROR_MESSAGE);
        cashReceived.setText("");
    } else if (!cashReceive.matches(validation)) {
        JOptionPane.showMessageDialog(null, "The Price Format is Incorrect! \nPlease try again!", "Error!",
                JOptionPane.ERROR_MESSAGE);
        cashReceived.setText("");
    } else {/* w  w  w. j  a  v  a  2  s. c o  m*/
        ResultSet trs = null;
        trs = tControl.getRecordWithTranstStatus("Pending");
        try {
            while (trs.next()) {

                TransactionDetails transID = tControl.getRecord(trs.getString(1));
                String id = transID.getTranstId();
                String status = "Paid";
                TransactionDetails setPaid = new TransactionDetails(status, id);
                tControl.setStatus(setPaid);

            }
        } catch (SQLException ex) {
            Logger.getLogger(Payment.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NumberFormatException e) {
        }
        int confirmDialog = JOptionPane.showConfirmDialog(rootPane,
                "Payment Completed!\nDo you want to generate receipt?", null, YES_NO_OPTION);

        //This part is to generate ticket
        Document document = new Document();
        Document document1 = new Document();
        BusDetailsControl bdControl = new BusDetailsControl();
        BusScheduleControl bsControl = new BusScheduleControl();
        CustTypeControl ctControl = new CustTypeControl();
        ResultSet rs = Payment.getForTandR();
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream("../" + Payment.getPaymentID() + ".pdf"));
            document.open();
            while (rs.next()) {
                BusScheduleDomain bs = bsControl.getRecord(rs.getString(2));
                BusDetailsDomain bd = bdControl.getRecord(bs.getBusId().getBusId());
                CustTypeDomain ct = ctControl.getRecord(rs.getString(3));
                tempD = bs.getDepartLocation();
                tempI = bs.getArriveLocation();
                document.add(new Paragraph("TICKET"));
                document.add(new Paragraph("Depart Location         : " + bs.getDepartLocation()));
                document.add(new Paragraph("Arrive Location          : " + bs.getArriveLocation()));
                document.add(new Paragraph("Depart Date              : " + bs.getScheduleDate()));
                document.add(new Paragraph("Depart Time              : " + bs.getScheduleTime()));
                document.add(new Paragraph("Customer Type         : " + ct.getCustType()));
                document.add(new Paragraph("Bus Plate Number    : " + bd.getBusPlateNum()));
                document.add(new Paragraph("Bus Type                  : " + bd.getBusType()));
                document.add(new Paragraph(
                        "Price                         : " + bs.getPrice() * ct.getDiscountRate()));
                document.add(new Paragraph(" " + " "));

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException ex) {
            Logger.getLogger(PayByCash.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (confirmDialog == JOptionPane.YES_OPTION) {
            PdfWriter writer1 = null;
            Date today = new Date();
            SimpleDateFormat dateF = new SimpleDateFormat("d-M-yyyy");
            SimpleDateFormat timeF = new SimpleDateFormat("HH:mm:ss");
            try {
                writer1 = PdfWriter.getInstance(document1,
                        new FileOutputStream("../" + Payment.getPaymentID() + " Receipt.pdf"));
                document1.open();
                document1.add(new Paragraph("                        SERI MEJU BUS Malaysia Sdn. Bhd."));
                document1.add(new Paragraph("                        L3-11, JLN LINGKARAN TENGAG LI,"));
                document1.add(new Paragraph("                               BANDAR TASIK SELATAN,"));
                document1.add(new Paragraph("                                57100 KUALA LUMPUR,"));
                document1.add(new Paragraph("                 WILAYAH PERSEKUTUAN KUALA LUMPUR,"));
                document1.add(new Paragraph("                                           MALAYSIA"));
                document1.add(new Paragraph(" "));
                document1.add(new Paragraph("RECEIPT"));
                document1.add(new Paragraph(
                        "---------------------------------------------------------------------------------------------"));
                document1.add(new Paragraph("Staff ID : " + new StaffMaintenance().getLoginUser()));
                document1.add(new Paragraph("Date : " + dateF.format(today)));
                document1.add(new Paragraph("Time : " + timeF.format(today)));
                document1.add(new Paragraph("From : " + tempD + ">>>>>>>>>>>>>>>>>>" + "To : " + tempI));
                document1.add(new Paragraph("Total : " + total));
                document1.add(new Paragraph("Payment Type : Cash "));
                document1.add(new Paragraph(
                        "---------------------------------------------------------------------------------------------"));
                document1.add(new Paragraph("Contact us : "));
                document1.add(new Paragraph("(Tel)1300-88-1111          (Email)serimejubusservice@gmail.com"));
                document1.close();
                JOptionPane.showMessageDialog(null,
                        "The Ticket(s) and Receipt have been stored to the Desktop of this PC.");
            } catch (FileNotFoundException ex) {
                Logger.getLogger(PayByCash.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(PayByCash.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(null, "The Ticket(s) have been stored to the Desktop of this PC.");
        }
        document.close();
        writer.close();
        //End of generate ticket
        dispose();
        new MainMenu();

    }

}

From source file:platnosci.WyszukPlatnosciController.java

public void akcjaDrukuj() {
    Drukowanie drukPanel = new Drukowanie(null, true);
    drukPanel.setLocationRelativeTo(null);
    drukPanel.setVisible(true);/*from w w  w . j av a 2 s  .c  o  m*/
    if (!drukPanel.isDruk()) {
        return;
    }

    FileOutputStream file = null;
    File druk = null;
    try {
        Document document = new Document();
        String userPath = System.getProperty("user.home");
        druk = new File(userPath + "/Baks wydruki");
        if (!druk.exists()) {
            druk.mkdirs();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String strdate = "";
        Date calendardate = new Date();
        strdate = sdf.format(calendardate.getTime());

        File wydruk = new File(druk + "/Platnosci - " + strdate + ".pdf");
        if (!wydruk.exists()) {
            try {
                wydruk.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        file = new FileOutputStream(wydruk);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(wydruk));
            document.open();

            PdfPTable table = new PdfPTable(4); // 3 columns.
            table.setWidthPercentage(100); //Width 100%
            table.setSpacingBefore(10f); //Space before table
            table.setSpacingAfter(10f); //Space after table

            //Set Column widths
            float[] columnWidths = { 1f, 1f, 1f, 1f };
            table.setWidths(columnWidths);
            BaseFont bf = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);

            PdfPCell cell1 = new PdfPCell(new Paragraph("Lp", new com.itextpdf.text.Font(bf, 16)));
            cell1.setPaddingLeft(10);
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell1.setVerticalAlignment(Element.ALIGN_LEFT);

            PdfPCell cell2 = new PdfPCell(new Paragraph("Firma", new com.itextpdf.text.Font(bf, 16)));
            cell2.setPaddingLeft(10);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setVerticalAlignment(Element.ALIGN_LEFT);

            PdfPCell cell3 = new PdfPCell(
                    new Paragraph("Data patnoci", new com.itextpdf.text.Font(bf, 16)));
            cell3.setPaddingLeft(10);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setVerticalAlignment(Element.ALIGN_LEFT);

            PdfPCell cell4 = new PdfPCell(new Paragraph("Kwota", new com.itextpdf.text.Font(bf, 16)));
            cell4.setPaddingLeft(10);
            cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell4.setVerticalAlignment(Element.ALIGN_LEFT);

            //To avoid having the cell border and the content overlap, if you are having thick cell borders
            cell1.setBorder(PdfPCell.NO_BORDER);
            cell2.setBorder(PdfPCell.NO_BORDER);
            cell3.setBorder(PdfPCell.NO_BORDER);
            cell4.setBorder(PdfPCell.NO_BORDER);
            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);
            table.addCell(cell4);

            TO_Invoice kryt = new TO_Invoice();
            kryt.setDataDo(drukPanel.getDateDo());
            kryt.setDataOd(drukPanel.getDateOd());
            kryt.setStatus(TO_InvoiceStatus.ZAPLACONA);
            List<TO_Invoice> listaFaktur = getDaoFactory().getDaoInvoice().getListaInvoiceDruk(getConnection(),
                    kryt);

            Integer i = 1;
            for (TO_Invoice item : listaFaktur) {
                table.addCell(getNewCell(i.toString() + "."));
                table.addCell(getNewCell(item.getPaymentCompany().getName()));
                table.addCell(getNewCell(item.getDataZaplacenia().toString()));
                table.addCell(getNewCell(TO_Invoice.getWynikSumaKoszt(item.getKoszt()) + " z"));
                i++;
            }

            document.add(table);

            document.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex);
        BaksSessionBean.getInstance().fireMessage(widok, "Wydruk",
                "Pdf do ktrego chcesz zapisa wynik jest otwarty!\n Zamknij i sprbuj jeszcze raz.");
    } finally {
        try {
            file.close();
        } catch (IOException ex) {
            Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    Desktop desktop = null;
    if (Desktop.isDesktopSupported()) {
        desktop = Desktop.getDesktop();
        try {
            desktop.open(druk);
        } catch (IOException ex) {
            Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    BaksSessionBean.getInstance().fireMessage(widok, "Zapis",
            "Wydruk zapisany w folderze: " + System.getProperty("user.home") + "/Baks wydruki");
}

From source file:Presentacion.Consentimientos.java

/**
 * Mtodo que permite generar el informe con base en el archivo adjunto del consentimiento
 * @param evt /*  w  w  w .  jav a2s .  com*/
 */
private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
    JFileChooser elegirCarpeta = new JFileChooser();
    elegirCarpeta.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int o = elegirCarpeta.showOpenDialog(this);
    if (o == JFileChooser.APPROVE_OPTION) {
        String path = elegirCarpeta.getSelectedFile().getAbsolutePath();
        String diaFecha = String.valueOf(FechaConsentimiento.getCalendar().get(Calendar.DAY_OF_MONTH));
        String mesFecha = String.valueOf(FechaConsentimiento.getCalendar().get(Calendar.MONTH) + 1);
        String annoFecha = String.valueOf(FechaConsentimiento.getCalendar().get(Calendar.YEAR));
        String fecha = diaFecha + "-" + mesFecha + "-" + annoFecha;
        try {
            File informe = new File(path + "\\Consentimiento N" + txtNConsentimiento.getText() + " "
                    + jcPaciente.getSelectedItem() + " (" + fecha + ").pdf");
            if (informe.exists()) {
                informe.delete();
            }
            try {
                String imagen = path + "\\Consentimiento N" + txtNConsentimiento.getText() + " "
                        + jcPaciente.getSelectedItem() + " (" + fecha + ").jpg";
                File outputfile = new File(imagen);
                ImageIO.write((RenderedImage) OpConsentimientos.getAdjunto(), "jpg", outputfile);
                Document document = new Document();
                FileOutputStream fos = new FileOutputStream(informe);
                PdfWriter writer = PdfWriter.getInstance(document, fos);
                writer.open();
                document.open();
                com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(imagen);
                img.scalePercent(45);
                document.add(img);
                outputfile.delete();
                document.close();
                writer.close();
            } catch (IOException | DocumentException ex) {
                Logger.getLogger(Consentimientos.class.getName()).log(Level.SEVERE, null, ex);
            }
            Desktop.getDesktop().open(informe);
        } catch (IOException ex) {
            Logger.getLogger(Consentimientos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:Print.Print.java

private void printToPDF(BufferedImage bufferedImage) {
    // define pdfprinter and within try clause create
    for (int i = 0; i < quantity; i++) {
        PdfWriter writer = null;
        try {/*from  ww w  . ja  v a2  s. com*/
            // define fileoutputstream and within try clause create
            FileOutputStream fos = null;

            document = new Document(PageSize.A4.rotate());
            fos = new FileOutputStream(output + photoID + "-" + Integer.toString(i + 1) + ".pdf");

            // create the writer object
            try {
                writer = PdfWriter.getInstance(document, fos);
            } catch (DocumentException ex) {
                System.out.println(ex.getMessage());
            }

            // open the writer and the document and add the image into the document
            writer.open();
            document.open();
            try {
                PdfContentByte pdfCB = new PdfContentByte(writer);
                if (bufferedImage == null) {
                    Image image = Image.getInstance(input);
                    image.scaleToFit(640, 480);
                    document.add(image);
                } else {
                    Image image = Image.getInstance(pdfCB, bufferedImage, 1);
                    image.scaleToFit(640, 480);
                    document.add(Image.getInstance(image));
                }

            } catch (DocumentException ex) {
                System.out.println(ex.getMessage());
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
            // close the document and writer
            document.close();
            writer.close();

            System.out.println("Printer done.");

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

From source file:Print.Print.java

public void printIndex(ArrayList<String> imagesPath, String customer) {
    try {//from w  ww . ja  va 2s.  c o  m
        //ArrayList<Image> images = new ArrayList<Image>();
        Map<Image, String> dict = new HashMap<Image, String>();
        for (String path : imagesPath) {
            try {
                System.out.println("path = /home/student" + path);
                int index = path.lastIndexOf("/");
                String photoId = path.substring(index + 1, path.length());
                Image newImage = Image.getInstance("/home/student" + path);
                //images.add(newImage);
                dict.put(newImage, photoId);
            } catch (BadElementException ex) {
                Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Total images = " + dict.size());
        Document index = new Document(PageSize.A4.rotate());
        FileOutputStream fos = new FileOutputStream("/home/student/Pictures/index.pdf");
        PdfWriter writer = PdfWriter.getInstance(index, fos);
        writer.open();
        index.open();

        PdfPTable adresTable = new PdfPTable(3);
        PdfPCell adresCell = new PdfPCell(new Paragraph(customer));
        adresCell.setColspan(3);
        adresTable.addCell(adresCell);
        adresTable.setHorizontalAlignment(Element.ALIGN_CENTER);
        adresTable.setWidthPercentage(100);
        index.add(adresTable);
        PdfPTable table = new PdfPTable(imagesPath.size());

        for (Map.Entry<Image, String> image : dict.entrySet()) {
            PdfPCell cell = new PdfPCell();
            table.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.setWidthPercentage(10);
            table.addCell(image.getValue());
            cell.addElement(image.getKey());
            table.addCell(cell);

        }
        index.add(table);
        //index.add(adresTable);
        index.close();
        writer.close();
        System.out.println("Index printed");

        //        // define pdfprinter and within try clause create
        //        PdfWriter writer = null;
        //        FileOutputStream fos = null;
        //        Document index = new Document(PageSize.A4.rotate());
        //        File file;
        //        try {
        //            file = new File("/home/student/Pictures/index.pdf");
        //            if(!file.exists()){
        //                file.createNewFile();
        //                
        //            }
        //            String test = "test data";
        //            fos = new FileOutputStream(file);
        //            fos.write(test.getBytes());
        //            fos.flush();
        //        } catch (FileNotFoundException ex) {
        //            Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
        //        } catch (IOException ex) {
        //            Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
        //        }
        //
        //        for (BufferedImage image : bufferedImages) {            
        //                try {
        //                    writer = PdfWriter.getInstance(index, fos);
        //                } catch (DocumentException ex) {
        //                    System.out.println(ex.getMessage());
        //                }
        //                writer.open();
        //                index.open();
        //                try {
        //                    PdfContentByte pdfCB = new PdfContentByte(writer);
        //                    Image newImage = Image.getInstance(pdfCB, image, 1);
        //                    index.add(Image.getInstance(newImage));
        //                } catch (DocumentException ex) {
        //                    System.out.println(ex.getMessage());
        //                } catch (IOException ex) {
        //                Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
        //            }
        //        }
        //        index.close();
        //        writer.close();
        //        System.out.println("Index done.");
    } catch (DocumentException ex) {
        Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:printInv.GenerateInvoice.java

private void createPDF(String pdfFilename) {

    Document doc = new Document();
    PdfWriter docWriter = null;
    initializeFonts();//from   w  ww . java  2  s  .  c om

    try {
        //   String path = "docs/" + pdfFilename;
        String path = pdfFilename;
        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.addAuthor("SmartWMS");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("SmartWMS");
        doc.addTitle("Invoice");
        doc.setPageSize(PageSize.LETTER);

        doc.open();
        PdfContentByte cb = docWriter.getDirectContent();

        boolean beginPage = true;
        int y = 0;
        System.out.println("n ===========" + n);
        for (int i = 0; i < n; i++) {
            if (beginPage) {
                beginPage = false;
                generateLayout(doc, cb);
                generateHeader(doc, cb);
                y = 615;
            }
            generateDetail(doc, cb, i, y);
            y = y - 15;
            if (y < 50) {
                printPageNumber(cb);
                doc.newPage();
                beginPage = true;
            }
        }
        printPageNumber(cb);
        cb.beginText();
        cb.setFontAndSize(bfBold, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "Grand Total : " + total, 570, 35, 0);
        cb.endText();

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }
}

From source file:procuracoes.classes.Digitalizacao.java

public void salva(String user) throws MorenaException, SQLException {

    source = TwainManager.selectSource(null);
    npag = 0;//from  ww  w . j a v a 2 s  .c om

    if (source != null) {
        morenaImage = new MorenaImage(source); //cria um objeto MorenaImage que manipula a imagem direta do scanner
        image = Toolkit.getDefaultToolkit().createImage(morenaImage); //cria um objeto Image para receber a imagem
        i.add(npag, image);
        bimg = new BufferedImage(morenaImage.getWidth(), //cria um bufferedImage para poder salvar a imagem
                morenaImage.getHeight(), BufferedImage.TYPE_INT_RGB);

        g = bimg.createGraphics();//cria um graphics2d para manipular a imagem do buffer
        g.drawImage(i.get(npag), 0, 0, null);//desenha o objeto Image no BufferedImage
        try {
            ImageIO.write(bimg, "jpg", new File("C:/temp/teste" + Integer.toString(npag) + ".jpg")); //Cria um novo arquivo jpg; 
            s.add("C:/temp/teste" + Integer.toString(npag) + ".jpg"); //Se a pasta no existir, a converso no funciona;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao salvar imagem " + ex);
        }
        //---------------------------------------//
        JFrame f = new JFrame();
        f.setBounds(50, 200, 1500, 600);
        f.setTitle("Visualizador");
        f.setMaximumSize(new Dimension(1500, 600));
        f.setMinimumSize(new Dimension(1500, 600));

        cx = 0;
        cy = 0;

        resizedImg = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB);
        g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(i.get(npag), 0, 0, 100, 150, null);
        g2.dispose();

        x = new JLabel(new ImageIcon(resizedImg));

        GridBagLayout grid = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        GridBagConstraints d = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;
        d.gridheight = 8;
        d.gridwidth = 3;
        c.ipadx = 10;
        c.ipady = 10;
        c.gridx = cx;
        c.gridy = cy;

        d.gridheight = 0;
        d.gridwidth = 3;
        d.fill = GridBagConstraints.VERTICAL;
        d.anchor = d.PAGE_END;
        d.gridy = 5;

        f.setLayout(grid);
        f.add(new JLabel("Deseja continuar escaniando?"), d);

        JButton j1 = new JButton("Sim");
        j1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                morenaImage = new MorenaImage(source); //cria um objeto MorenaImage que manipula a imagem direta do scanner
                image = Toolkit.getDefaultToolkit().createImage(morenaImage); //cria um objeto Image para receber a imagem
                i.add(npag, image);
                bimg = new BufferedImage(morenaImage.getWidth(), //cria um bufferedImage para poder salvar a imagem
                        morenaImage.getHeight(), BufferedImage.TYPE_INT_RGB);

                g = bimg.createGraphics(); //cria um graphics2d para manipular a imagem do buffer
                g.drawImage(i.get(npag), 0, 0, null);
                //desenha o objeto Image no BufferedImage
                try {
                    ImageIO.write(bimg, "jpg", new File("C:/temp/teste" + Integer.toString(npag) + ".jpg")); //Cria um novo arquivo jpg;
                    s.add("C:/temp/teste" + Integer.toString(npag) + ".jpg");
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, "Erro ao salvar imagem " + ex);
                }
                //--------------------------------------------//
                resizedImg = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB);
                g2 = resizedImg.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(i.get(npag), 0, 0, 100, 150, null);
                g2.dispose();

                if (npag < 8) {
                    cx = npag;
                } else if (npag >= 24) {
                    cx = npag - 24;
                    cy = 3;
                } else if (npag >= 16) {
                    cx = npag - 16;
                    cy = 2;
                } else if (npag >= 8) {
                    cx = npag - 8;
                    cy = 1;
                }

                x = new JLabel(new ImageIcon(resizedImg));
                c.gridx = cx;
                c.gridy = cy;

                f.add(x, c);
                f.validate();
                //----------------------------------------------//
                npag++;
            }
        });
        f.add(j1, d);

        JButton j2 = new JButton("Nao");
        j2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Document document = new Document();
                Rectangle r = new Rectangle(morenaImage.getWidth(), morenaImage.getHeight());
                document.setPageSize(r);
                try {
                    String output = getNovoCaminho();
                    FileOutputStream fos = new FileOutputStream(output);
                    PdfWriter writer = PdfWriter.getInstance(document, fos);
                    writer.open();
                    document.open();
                    int j = 0;
                    while (j < npag) {
                        document.add(com.itextpdf.text.Image.getInstance(s.get(j)));
                        j++;
                    }

                    document.close();
                    writer.close();
                } catch (DocumentException | IOException | SQLException ex) {
                    JOptionPane.showMessageDialog(null, "Erro ao criar arquivo pdf " + ex);
                }
                try {
                    TwainManager.close();
                    InsereProc in;
                    in = new InsereProc(user);
                    in.setVisible(true);
                    f.dispose();
                } catch (SQLException | TwainException ex) {
                    Logger.getLogger(Digitalizacao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        f.add(j2, d);
        f.add(x, c);

        npag++;
        f.validate();
        f.setVisible(true);
        f.toFront();
    } else {
        JOptionPane.showMessageDialog(null, "Documneto nao encontrado !");
    }
}

From source file:qcas.InstructorDashboardController.java

/**
 * method to export the image to pdf format
 * @throws IOException//from   w  w  w  . j  av  a  2 s . c  o m
 * @throws DocumentException
 */
@FXML
public void exportToPdf() throws IOException, DocumentException {
    Document document = new Document();
    String output = "Current" + time + ".pdf";
    FileOutputStream fos = new FileOutputStream(output);
    PdfWriter writer = PdfWriter.getInstance(document, fos);
    writer.open();
    document.open();
    WritableImage image = lineChartAnchorPaneBR.snapshot(new SnapshotParameters(), null);
    Image returnImage = pdfExport(image, document);
    document.add(returnImage);
    image = pieChartAnchorPane.snapshot(new SnapshotParameters(), null);
    returnImage = pdfExport(image, document);
    document.newPage();
    document.add(returnImage);
    image = stackedBarAnchorPane.snapshot(new SnapshotParameters(), null);
    returnImage = pdfExport(image, document);
    document.newPage();
    document.add(returnImage);
    image = lineChartAnchorPaneBR.snapshot(new SnapshotParameters(), null);
    returnImage = pdfExport(image, document);
    document.newPage();
    document.add(returnImage);
    document.close();
    writer.close();
    pdfDownloadedLabel.setVisible(true);

}

From source file:qcas.QuizResultsController.java

public void exportToPdf() throws IOException, DocumentException {

    String s = "";
    for (int i = 0; i < this.userAnswers.size(); i++) {
        s += "Question ".toUpperCase() + (i + 1) + ": " + "\t Your Answer: ".toUpperCase()
                + this.userAnswers.get(i) + "\t Correct Answer: ".toUpperCase() + this.userAnswerCheck.get(i)
                + "\n\n";
    }/* w  ww .  j  av a2  s . c  o  m*/

    WritableImage image = QuizResultsDashboardPane.snapshot(new SnapshotParameters(), null);

    File file = new File("Student Report.png");

    ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);

    Document document = new Document();
    String input = "Student Report.png"; // .gif and .jpg are ok too!
    String output = "Student Report.pdf";
    try {
        FileOutputStream fos = new FileOutputStream(output);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.open();
        document.open();
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();

        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", byteOutput);

        com.itextpdf.text.Image graph;
        graph = com.itextpdf.text.Image.getInstance(byteOutput.toByteArray());
        graph.scaleToFit(500, 500);
        document.add((com.itextpdf.text.Element) graph);
        Font f = new Font(FontFamily.TIMES_ROMAN, 10.0f, Font.UNDERLINE, BaseColor.BLACK);
        Paragraph p = new Paragraph(s, f);
        document.add(p);

        document.close();
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    QuizResultsDashboardPane.setVisible(true);

}

From source file:qcas.StudentPerformanceController.java

@FXML
public void exportToPdf() throws IOException, DocumentException {
    WritableImage image = performanceAnchorPane.snapshot(new SnapshotParameters(), null);
    //File file = new File("StudentPerformance.png");
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    try {/*from  ww w.  ja  va  2 s  .co  m*/
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", byteArray);
    } catch (IOException e) {
    }
    Document document = new Document();
    String output = "StudentPastPerformance.pdf";
    try {
        int indentation = 0;
        FileOutputStream fos = new FileOutputStream(output);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.open();
        document.open();
        Image newImage = Image.getInstance(byteArray.toByteArray());
        newImage.scaleToFit(500, 450);
        document.add(newImage);
        document.close();
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    pdfDownloadedLabel.setVisible(true);

}