public void print(String filename) throws IOException, DocumentException { EventTree tree = app.getTimelines().getCurrentTree(); if (tree == null || tree.isEmpty()) return; ComplexEvent parent = tree.getTopSelectionParent(); if (parent == null) return; // Instantiation of document object Document document = new Document(PageSize.A4, 50, 50, 50, 50); // Creation of PdfWriter object PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); // Creation of table Paragraph title = new Paragraph( "A sample output from Zeitline:", FontFactory.getFont(FontFactory.TIMES_BOLD, 14, BaseColor.BLUE)); title.setSpacingAfter(20); document.add(title); // Setting width rations PdfPTable table = new PdfPTable(3); float[] tableWidth = {(float) 0.2, (float) 0.12, (float) 0.68}; table.setWidths(tableWidth); // Setting the header java.util.List<PdfPCell> headerCells = asList(getHeaderCell("Date"), getHeaderCell("MACB"), getHeaderCell("Short Description")); for (PdfPCell cell : headerCells) table.addCell(cell); // Setting the body int max = parent.countChildren(); for (int i = 0; i < max; i++) { AbstractTimeEvent entry = parent.getEventByIndex(i); table.addCell(getBodyCell(entry.getStartTime().toString())); String name = entry.getName(); if (name != null && name.length() > 5) { String macb = name.substring(0, 4); String desc = name.substring(5); table.addCell(getBodyCell(macb)); table.addCell(getBodyCell(desc)); } else { table.addCell(""); table.addCell(""); } } document.add(table); // Closure document.close(); writer.close(); }
/** * set values to writer * * @param writer * @throws Exception */ protected void setValues(IExporter<?> exporter, FileOutputStream writer) throws Exception { if (exporter != null && writer != null) { String encoding = SettingsManager.getInstance().getValue(SettingProperty.ENCODING); BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, encoding, BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont); List<String> properties = exporter.getProperties(); Document document = new Document(PageSize.A4); // step 2 PdfWriter.getInstance(document, writer); // step 3 document.open(); PdfPTable table = new PdfPTable(properties.size()); table.setFooterRows(1); table.setWidthPercentage(100f); table.getDefaultCell().setColspan(1); table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY); for (String p : properties) { table.addCell(new Phrase(p, font)); } // table.setHeaderRows(1); table.getDefaultCell().setBackgroundColor(null); List<List<String>> values = ((IExporter<String>) exporter).getValues(); String pValue; for (List<String> value : values) { for (String pv : value) { pValue = pv; if (pValue == null) { pValue = ""; } table.addCell(new Phrase(pValue, font)); } } document.add(table); document.close(); } }
/** * Writes out the information and PDF file to disk, and closes the stream. Returns a negative * Result if there was an error creating the document, and a positive result if the document was * successfully written and closed. */ public Result finish() { if (_open) { fillNullCells(); try { _d.add(_table); } catch (DocumentException e) { return new Result(false, "The document was not successfully constructed."); } _d.close(); _open = false; } return new Result(true, "The document is closed."); }
private void generateInvoicePDFByExamination( Examination examination, HttpServletResponse response) throws FileNotFoundException { Document document = new Document(); response.setHeader("Accept-ranges", "bytes"); response.setContentType("application/pdf"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Content-Description", "File Transfer"); response.setHeader("Content-Transfer-Encoding:", "binary"); try { PdfWriter.getInstance(document, response.getOutputStream()); document.open(); addMetaData(document); addTitlePage(document, examination); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public ReportLowStock() { rprtDBAccess = new RprtDBAccess(); orderDBAccess = new OrderDBAccess(); try { Document document = new Document(); Date date = new java.util.Date(); long timeStamp = date.getTime(); documentName = desktoppath + timeStamp + "_" + FILE; PdfWriter.getInstance(document, new FileOutputStream(documentName)); document.open(); addTitle(document, "Low Stock Report"); addLogo(document); addProductDetails(document); addDateGenerated(document); addReportGenerator(document); document.close(); System.out.println("wrote file"); } catch (Exception e) { e.printStackTrace(); } }
public void generaPdf() { Document documento = new Document(); FileOutputStream ficheroPdf; PdfPTable tabla_emple, tabla_proyec, tabla_relacional; empleados = consultas.recogerEmpleados(); ProjectX = consultas.recogerProyectos(); ArrayList<Empleado> relacional; try { ficheroPdf = new FileOutputStream("ejemplo.PDF"); PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20); } catch (Exception ex) { System.out.println(ex.toString()); } try { // abrimos el documento para editarlo documento.open(); // aqui agregamos todo el contenido del PDF... documento.add( new Paragraph( "Este informe es una manera de imprimir la informacion, en forma de tablas, de la base de datos")); documento.add(new Paragraph(" ")); // ***************TABLA DE LOS EMPLEADOS************** documento.add(new Paragraph("Empleados de la compañia:")); documento.add(new Paragraph(" ")); // inicio la tabla con las 4 columnas de los empleados tabla_emple = new PdfPTable(4); // cada 4 addCell, es una fila nueva tabla_emple.addCell("NIF"); tabla_emple.addCell("Nombre"); tabla_emple.addCell("Apellidos"); tabla_emple.addCell("Fecha de Nacimiento"); for (Empleado e : empleados) { tabla_emple.addCell(e.getNif()); tabla_emple.addCell(e.getNombre()); tabla_emple.addCell(e.getApellido()); tabla_emple.addCell(e.getFechaNacimiento()); } documento.add(tabla_emple); documento.add(new Paragraph(" ")); // *********TABLA DE LOS PROYECTOS************ documento.add(new Paragraph("Proyectos actuales en la compañia:")); documento.add(new Paragraph(" ")); tabla_proyec = new PdfPTable(5); tabla_proyec.addCell("Titulo"); tabla_proyec.addCell("Fecha de Inicio"); tabla_proyec.addCell("Fecha de Entrega"); tabla_proyec.addCell("Descripcion"); tabla_proyec.addCell("Nº Maximo de empleados"); for (Proyecto p : ProjectX) { tabla_proyec.addCell(p.getTitulo()); tabla_proyec.addCell(p.getFechaInicio()); tabla_proyec.addCell(p.getFechaFin()); tabla_proyec.addCell(p.getDescripcion()); tabla_proyec.addCell(String.valueOf(p.getMaxEmple())); } documento.add(tabla_proyec); documento.add(new Paragraph(" ")); // TABLA RELACIONAL documento.add(new Paragraph("Tabla relacional de empleados por proyecto")); documento.add(new Paragraph(" ")); tabla_relacional = new PdfPTable(4); for (Proyecto p : ProjectX) { Paragraph titulos = new Paragraph(p.getTitulo()); titulos.setAlignment(1); PdfPCell celda = new PdfPCell(titulos); celda.setColspan(4); celda.setRowspan(2); tabla_relacional.addCell(celda); tabla_relacional.addCell("NIF"); tabla_relacional.addCell("Nombre"); tabla_relacional.addCell("Apellidos"); tabla_relacional.addCell("Fecha de Nacimiento"); relacional = consultas.recogerEmpleProy(p.getId()); for (Empleado er : relacional) { tabla_relacional.addCell(er.getNif()); tabla_relacional.addCell(er.getNombre()); tabla_relacional.addCell(er.getApellido()); tabla_relacional.addCell(er.getFechaNacimiento()); } Paragraph fin = new Paragraph(" "); titulos.setAlignment(1); PdfPCell celda2 = new PdfPCell(fin); celda2.setColspan(4); celda2.setRowspan(2); } documento.add(tabla_relacional); documento.add(new Paragraph(" ")); documento.add(new Paragraph("Desarrollador del programa: Jairo Gallardo Zorrilla")); documento.add(new Paragraph("Cliente: Manuel Torres")); documento.add(new Paragraph("")); // cerramos el documento y se genera JOptionPane.showMessageDialog(null, "El archivo pdf se ha generado correctamente"); documento.close(); } catch (Exception ex) { System.out.println(ex.toString()); } }
/** * @param shiftsToAccount * @param month * @param year * @return */ public static String createAccounting(ShiftInstance[] shiftsToAccount, int month, int year) { // check if personal Data exists if (!PersonalData.getInstance().isDataSet()) { UtilityBox.getInstance() .displayInfoPopup( "Fehlende Daten", "Um die " + "Abrechnung zu erstellen müssen\npersönliche Daten gespeichert sein."); return null; } boolean success = false; String filePath = "Abrechnungen/" + year; // create directory if nessessary UtilityBox.createDirectory(filePath); // change filePath from directory to file filePath = filePath + "/Abrechnung" + UtilityBox.getMonthString(month) + year + ".pdf"; Document accounting = new Document(); ArrayList<ShiftInstance> rd = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> ktp = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> baby = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> breisach = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> kiza = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> event = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> sc = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> concert_hall = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> kvs = new ArrayList<ShiftInstance>(); ArrayList<ShiftInstance> elw = new ArrayList<ShiftInstance>(); // add shifts to seperate shift lists for (int i = 0; i < shiftsToAccount.length; i++) { switch (shiftsToAccount[i].getType()) { case KTW: ktp.add(shiftsToAccount[i]); break; case RTW: rd.add(shiftsToAccount[i]); break; case HINTERGRUND: rd.add(shiftsToAccount[i]); break; case ELW: elw.add(shiftsToAccount[i]); break; case EVENT: event.add(shiftsToAccount[i]); break; case SC: sc.add(shiftsToAccount[i]); break; case CONCERT_HALL: concert_hall.add(shiftsToAccount[i]); break; case KVS: kvs.add(shiftsToAccount[i]); break; case BREISACH: breisach.add(shiftsToAccount[i]); break; case KIZA: kiza.add(shiftsToAccount[i]); break; default: break; } } ArrayList<ShiftInstance>[] allShifts = (ArrayList<ShiftInstance>[]) (new ArrayList[] {rd, elw, ktp, baby, breisach, kiza, event, sc, concert_hall, kvs}); try { accounting.setPageSize(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(accounting, new FileOutputStream(filePath)); accounting.open(); for (int i = 0; i < allShifts.length; i++) { if (!allShifts[i].isEmpty()) { int numberOfPages = ((int) (allShifts[i].size() / 13)) + 1; int counter = allShifts[i].size() - 1; for (int j = 1; j <= numberOfPages; j++) { ArrayList<ShiftInstance> tempShiftInstances = new ArrayList<ShiftInstance>(); for (int k = 0; k < 13; k++) { if (counter < 0) { break; } tempShiftInstances.add(allShifts[i].get(counter)); counter--; } accounting.newPage(); success = createSingleAccounting(accounting, pdfWriter, tempShiftInstances, i * 10 + j); } } } // TODO: for JDK7 use Multicatch } catch (Exception e) { // DocumentException | IOException e) { UtilityBox.getInstance() .displayErrorPopup( "Abrechnung", "Fehler beim " + "Erstellen der Abrechnung:\n" + e.getMessage()); filePath = null; } finally { try { accounting.close(); } catch (Exception e) { UtilityBox.getInstance() .displayErrorPopup( "Abrechnung", "Fehler beim " + "Erstellen der Abrechnung:\nDokument nicht geschlossen:\n" + "" + e.getMessage()); filePath = null; } } return filePath; }