List of usage examples for com.itextpdf.text Document add
public boolean add(Element element) throws DocumentException
Element
to the Document
. From source file:admission_form.FXMLController1.java
@FXML private void doPrinting(ActionEvent event) { print_btn.setVisible(false);/* w ww . j a va2 s . c o m*/ back_btn.setVisible(false); Scene scene = print_btn.getScene(); WritableImage snapshot = scene.snapshot(null); BufferedImage image = SwingFXUtils.fromFXImage(snapshot, null); File f = new File("test2.png"); try { ImageIO.write(image, "png", f); } catch (IOException ex) { } Document document = new Document(PageSize.A4, 0, 0, 0, 0); try { PdfWriter.getInstance(document, new FileOutputStream("Image.pdf")); document.open(); // BufferedImage img = ImageIO.read(new File("test1.png")); //File f = new File("test1.png"); Image image1 = Image.getInstance("test2.png"); document.add(image1); document.close(); } catch (Exception e) { e.printStackTrace(); } try { InputStream is = new BufferedInputStream(new FileInputStream("Image.pdf")); DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF; PrintService service = PrintServiceLookup.lookupDefaultPrintService(); DocPrintJob printJob = service.createPrintJob(); printJob.addPrintJobListener(new JobCompleteMonitor()); Doc doc = new SimpleDoc(is, flavor, null); PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet(); //attributes.add(new Destination(new java.net.URI("file:/home/jayesh/NetBeansProjects/myFile.ps"))); printJob.print(doc, attributes); //while(jobRunning) //{ // Thread.sleep(1000); //} is.close(); } catch (Exception ex) { } finally { System.out.println("exiting"); } System.out.println("Done"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/pro", username, password); String query = "insert into log values(?,?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, getCurUser()); Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss"); ps.setString(2, "Printed Admission Form Page2 at " + df.format(date)); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } print_btn.setVisible(true); back_btn.setVisible(true); }
From source file:admission_form.FXMLDocumentController.java
@FXML private void doPrininting(ActionEvent event) { next.setVisible(false);//w w w . j a v a 2s .c om print_btn.setVisible(false); Scene scene = print_btn.getScene(); WritableImage snapshot = scene.snapshot(null); BufferedImage image = SwingFXUtils.fromFXImage(snapshot, null); File f = new File("test2.png"); try { ImageIO.write(image, "png", f); } catch (IOException ex) { } Document document = new Document(PageSize.A4, 0, 0, 0, 0); try { PdfWriter.getInstance(document, new FileOutputStream("Image.pdf")); document.open(); // BufferedImage img = ImageIO.read(new File("test1.png")); //File f = new File("test1.png"); Image image1 = Image.getInstance("test2.png"); document.add(image1); document.close(); } catch (Exception e) { e.printStackTrace(); } try { InputStream is = new BufferedInputStream(new FileInputStream("Image.pdf")); DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF; PrintService service = PrintServiceLookup.lookupDefaultPrintService(); DocPrintJob printJob = service.createPrintJob(); printJob.addPrintJobListener(new JobCompleteMonitor()); Doc doc = new SimpleDoc(is, flavor, null); PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet(); //attributes.add(new Destination(new java.net.URI("file:/home/jayesh/NetBeansProjects/myFile.ps"))); printJob.print(doc, attributes); //while(jobRunning) //{ // Thread.sleep(1000); //} is.close(); } catch (Exception ex) { } finally { System.out.println("exiting"); } System.out.println("Done"); try { con1(); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/pro", username, password); String query = "insert into log values(?,?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, getCurUser()); Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss"); ps.setString(2, "Printed Admission Form Page1 at " + df.format(date)); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } next.setVisible(true); print_btn.setVisible(true); }
From source file:airline.service.GeneratePDF.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Set content type to application / pdf //browser will open the document only if this is set response.setContentType("application/pdf"); //Get the output stream for writing PDF object OutputStream out = response.getOutputStream(); try {/*from www. j av a 2 s . c o m*/ RuntimeTypeAdapterFactory<Jsonable> rta = RuntimeTypeAdapterFactory.of(Jsonable.class, "_class") .registerSubtype(Reservacion.class, "Reservacion").registerSubtype(Tiquete.class, "Tiquete") .registerSubtype(Viaje.class, "Viaje"); Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).setDateFormat("dd/MM/yyyy").create(); String json; List<Viaje> viajes; String jsonReservacion = request.getParameter("reservacion"); Reservacion reservacion = gson.fromJson(jsonReservacion, Reservacion.class); String jsonViajes = request.getParameter("viajes"); viajes = gson.fromJson(jsonViajes, new TypeToken<ArrayList<Viaje>>() { }.getType()); Document document = new Document(); /* Basic PDF Creation inside servlet */ PdfWriter.getInstance(document, out); document.open(); document.add(new Paragraph(" FACTURA DE COMPRA")); document.add(Chunk.NEWLINE); document.add(new Paragraph("Viajes")); document.add(Chunk.NEWLINE); document.add(createViajesTable(viajes)); document.add(Chunk.NEWLINE); document.add(new Paragraph("Reservacion")); document.add(Chunk.NEWLINE); document.add(createReservacionTable(reservacion)); document.close(); } catch (DocumentException exc) { throw new IOException(exc.getMessage()); } finally { out.close(); } }
From source file:alessandrafx.MarcoVentanaController.java
@FXML private void generarReporteMenusal(MouseEvent event) { try {/*from ww w . j a v a 2 s . c om*/ FileChooser fileChooser = new FileChooser(); fileChooser.setInitialFileName("Reporte.pdf"); File file = fileChooser.showSaveDialog(null); file.getParentFile().mkdir(); Document document = new Document(); try { try { PdfWriter.getInstance(document, new FileOutputStream(file)); } catch (FileNotFoundException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Phrase("Factura emitida el " + new Date())); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); SistemaAleMC sistema = new SistemaAleMC(); Double balanceMonetario = 0.0; //Para salidas de dinero ArrayList<Capital> capitales = sistema.getRegistrosCapitalTipo('S'); cell = new PdfPCell(new Phrase("Gastos y pagos realizados")); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega los registros de salidas de dinero Double totalEgreso = 0.0; if (capitales.isEmpty()) { cell = new PdfPCell(new Phrase(" --- ")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(" --- ")); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } for (Capital capital : capitales) { cell = new PdfPCell(new Phrase(capital.getMotivo().toString())); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(capital.getMonto().toString())); balanceMonetario -= Double.valueOf(capital.getMonto()); totalEgreso -= Double.valueOf(capital.getMonto()); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } cell = new PdfPCell(new Phrase("TOTAL DE EGRESOS")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(totalEgreso.toString())); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); //Para Pago de mensualidades capitales = sistema.getRegistrosCapitalTipo('M'); cell = new PdfPCell(new Phrase("Pagos de mensualidad recibidos")); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega los registros de pago de mensualidades de los alumnos Double totalIngresoMen = 0.0; if (capitales.isEmpty()) { cell = new PdfPCell(new Phrase(" --- ")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(" --- ")); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } for (Capital capital : capitales) { cell = new PdfPCell(new Phrase(capital.getMotivo().toString())); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(capital.getMonto().toString())); balanceMonetario += Double.valueOf(capital.getMonto()); totalIngresoMen += Double.valueOf(capital.getMonto()); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } cell = new PdfPCell(new Phrase("TOTAL DE MENSUALIDADES")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(totalIngresoMen.toString())); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); //Para Pago de anualidades capitales = sistema.getRegistrosCapitalTipo('A'); cell = new PdfPCell(new Phrase("Pagos de anualidades recibidos")); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega los registros de pago de anualidades de los alumnos Double totalIngresoAnu = 0.0; if (capitales.isEmpty()) { cell = new PdfPCell(new Phrase(" --- ")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(" --- ")); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } for (Capital capital : capitales) { cell = new PdfPCell(new Phrase(capital.getMotivo().toString())); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(capital.getMonto().toString())); balanceMonetario += Double.valueOf(capital.getMonto()); totalIngresoAnu += Double.valueOf(capital.getMonto()); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } cell = new PdfPCell(new Phrase("TOTAL DE ANUALIDADES")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(totalIngresoAnu.toString())); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); //PARA EL BALANCE MONETARIO capitales = sistema.getRegistrosCapitalTipo('A'); cell = new PdfPCell(new Phrase("Total")); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega la celda del total monetario if (balanceMonetario == (Double) 0.0) { cell = new PdfPCell(new Phrase("No hubieron movimientos este mes")); } else { cell = new PdfPCell(new Phrase(balanceMonetario.toString())); } cell.setColspan(3); cell.setBackgroundColor(BaseColor.WHITE); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); try { document.add(table); } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.close(); Alert alerta = new Alert(Alert.AlertType.INFORMATION); alerta.setTitle("Corre a ver tu PDF!"); alerta.setHeaderText(null); alerta.setContentText("El PDF ha sido generado, puedes revisarlo"); alerta.showAndWait(); } catch (Exception e) { Alert alerta = new Alert(Alert.AlertType.INFORMATION); alerta.setTitle("Lo sentimos"); alerta.setHeaderText(null); alerta.setContentText("La ubicacin seleccionada no es vlida y por tanto, no se generar el PDF"); alerta.showAndWait(); } }
From source file:alessandrafx.VentanaEgresoController.java
private void generarReportePagoColaborador(int pagoColaborador, int pagoSugerido) throws DatoFaltante { try {/*from w w w . j ava 2s . c o m*/ FileChooser fileChooser = new FileChooser(); fileChooser.setInitialFileName("facturaNueva.pdf"); File file = fileChooser.showSaveDialog(null); file.getParentFile().mkdir(); Document document = new Document(); try { try { PdfWriter.getInstance(document, new FileOutputStream(file)); } catch (FileNotFoundException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Phrase("Factura emitida el " + new Date())); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega el pago IDEAL cell = new PdfPCell(new Phrase("Pago sugerido recibido")); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase("Pago sugerido")); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); //Agrega el pago realizado cell = new PdfPCell(new Phrase("Pago realizado")); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(String.valueOf(pagoColaborador))); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); try { document.add(table); } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.close(); } catch (Exception e) { throw new DatoFaltante("ubicacin no vlida", "La ubicacin que has escogido no es vlida"); } }
From source file:alessandrafx.VentanaEgresoController.java
private void generarReporteOtroGasto(int cantidad, String motivo) throws DatoFaltante { try {/* w w w. j a v a2 s . c o m*/ FileChooser fileChooser = new FileChooser(); fileChooser.setInitialFileName("facturaHecha.pdf"); File file = fileChooser.showSaveDialog(null); file.getParentFile().mkdir(); Document document = new Document(); try { try { PdfWriter.getInstance(document, new FileOutputStream(file)); } catch (FileNotFoundException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Phrase("Factura emitida el " + new Date())); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega el monto pagado cell = new PdfPCell(new Phrase("Pago realizado")); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(String.valueOf(cantidad))); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); //Agrega el motivo del pago cell = new PdfPCell(new Phrase("Motivo: \n" + motivo)); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setColspan(3); table.addCell(cell); try { document.add(table); } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.close(); } catch (Exception e) { throw new DatoFaltante("ubicacin no vlida", "La ubicacin que has escogido no es vlida"); } }
From source file:alessandrafx.VentanaIngresoController.java
public void generarReportePago(String pagoSugerido, String pagoRealizado) throws DatoFaltante { try {//w w w .j av a 2 s .c o m FileChooser fileChooser = new FileChooser(); fileChooser.setInitialFileName("facturaNueva.pdf"); File file = fileChooser.showSaveDialog(null); file.getParentFile().mkdir(); Document document = new Document(); try { try { PdfWriter.getInstance(document, new FileOutputStream(file)); } catch (FileNotFoundException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Phrase("Factura emitida el " + new Date())); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Agrega el pago IDEAL cell = new PdfPCell(new Phrase("Pago sugerido recibido")); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(pagoSugerido)); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); //Agrega el pago realizado cell = new PdfPCell(new Phrase("Pago realizado")); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(String.valueOf(pagoRealizado))); cell.setColspan(2); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); try { document.add(table); } catch (DocumentException ex) { Logger.getLogger(VentanaEgresoController.class.getName()).log(Level.SEVERE, null, ex); } document.close(); } catch (Exception e) { throw new DatoFaltante("ubicacin no vlida", "La ubicacin que has escogido no es vlida"); } }
From source file:analizadorventas.controlador.ControladorPdf.java
/** * @param lista //w w w . j ava 2 s . com */ public static void CrearPdf(List<Transaccion> lista) { try { Document documento = new Document(); PdfWriter.getInstance(documento, new FileOutputStream(new File("acercaDe.pdf"))); documento.open(); PdfPTable fila = new PdfPTable(5); fila.setHeaderRows(1); for (String cadena : header) { fila.addCell(cadena); } for (Transaccion transaccion : lista) { fila.setSpacingAfter(10); fila.addCell(transaccion.getNombreCliente()); fila.addCell(transaccion.getProductoComprado()); fila.addCell(transaccion.getPrecio() + ""); fila.addCell(transaccion.getFecha()); fila.addCell(transaccion.getCiudad()); } documento.add(fila); documento.close(); } catch (DocumentException | FileNotFoundException ex) { Logger.getLogger(ControladorPdf.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:app.logica.gestores.GestorPDF.java
License:Open Source License
/** * Mtodo para crear un PDF a partir de una pantalla. *//w w w .j a v a 2 s . co m * @param pantallaAPDF * pantalla que se imprimir en PDF * @return PDF de una captura de la pantalla pasada */ private PDF generarPDF(Node pantallaAPDF) throws Exception { //Se imprime la pantalla en una imagen new Scene((Parent) pantallaAPDF); WritableImage image = pantallaAPDF.snapshot(new SnapshotParameters(), null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos); byte[] imageInByte = baos.toByteArray(); baos.flush(); baos.close(); //Se carga la imagen en un PDF Image imagen = Image.getInstance(imageInByte); Document document = new Document(); ByteArrayOutputStream pdfbaos = new ByteArrayOutputStream(); PdfWriter escritor = PdfWriter.getInstance(document, pdfbaos); document.open(); imagen.setAbsolutePosition(0, 0); imagen.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); document.add(imagen); document.close(); //Se obtiene el archivo PDF byte[] pdfBytes = pdfbaos.toByteArray(); pdfbaos.flush(); escritor.close(); pdfbaos.close(); //Se genera un objeto PDF return (PDF) new PDF().setArchivo(pdfBytes); }
From source file:app.logica.gestores.GestorPDF.java
License:Open Source License
/** * Mtodo para crear un PDF a partir de varias pantalla. */*from w w w. j a v a 2s . co m*/ * @param pantallaAPDF * pantalla que se imprimir en PDF * @return PDF de una captura de la pantalla pasada */ private PDF generarPDF(ArrayList<Node> pantallasAPDF) throws Exception { Document document = new Document(); ByteArrayOutputStream pdfbaos = new ByteArrayOutputStream(); PdfWriter escritor = PdfWriter.getInstance(document, pdfbaos); document.open(); for (Node pantalla : pantallasAPDF) { new Scene((Parent) pantalla); WritableImage image = pantalla.snapshot(new SnapshotParameters(), null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos); byte[] imageInByte = baos.toByteArray(); baos.flush(); baos.close(); Image imagen = Image.getInstance(imageInByte); imagen.setAbsolutePosition(0, 0); imagen.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); document.add(imagen); document.newPage(); } document.close(); byte[] pdfBytes = pdfbaos.toByteArray(); pdfbaos.flush(); escritor.close(); pdfbaos.close(); return (PDF) new PDF().setArchivo(pdfBytes); }