List of usage examples for com.itextpdf.text PageSize A4
Rectangle A4
To view the source code for com.itextpdf.text PageSize A4.
Click Source Link
From source file:researchbehaviour.TextToPDF.java
public void convertToPdf() { try {//w ww. j a v a 2s . c o m FileReader f = new FileReader("data2.txt"); BufferedReader bin = new BufferedReader(f); String text = bin.readLine(); Document document = new Document(PageSize.A4, 36, 72, 108, 180); PdfWriter.getInstance(document, new FileOutputStream("pdfFile1.pdf")); document.open(); document.add(new Paragraph(text)); System.out.println("Text is inserted into pdf file"); document.close(); } catch (Exception e) { } }
From source file:ro.ldir.chartpackage.GarbagePackageBuilder.java
License:Open Source License
public void writePDF(OutputStream out) throws DocumentException, MalformedURLException, XPathExpressionException, IOException { BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, "Cp1250", BaseFont.NOT_EMBEDDED); final Font hfFont = new Font(bf, 8, Font.NORMAL, BaseColor.GRAY); Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, out); writer.setBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.setPageEvent(new PdfPageEventHelper() { private int page = 0; @Override//w w w .j a v a2s . c o m public void onEndPage(PdfWriter writer, Document arg1) { page++; Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Pachet mormane - \u00a9 Let's Do It, Romania!", hfFont), (rect.getLeft() + rect.getRight()) / 2, rect.getTop() + 18, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("- " + page + " -", hfFont), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0); } }); document.open(); document.addAuthor("Let's Do It, Romania!"); document.addTitle("Pachet mormane"); document.addCreationDate(); Font titleFont = new Font(bf, 24, Font.BOLD); Font noteFont = new Font(bf, 12, Font.NORMAL, BaseColor.RED); Font headerFont = new Font(bf, 12, Font.BOLD); Font normalFont = new Font(bf, 11); Font defFont = new Font(bf, 11, Font.BOLD); Paragraph par; int page = 0; for (Garbage garbage : garbages) { par = new Paragraph(); par.setAlignment(Element.ALIGN_CENTER); par.add(new Chunk("Morman " + garbage.getGarbageId() + "\n", titleFont)); par.add(new Chunk("Citi\u0163i cu aten\u0163ie!", noteFont)); document.add(par); par = new Paragraph(); par.setSpacingBefore(20); par.add(new Chunk("1. Date generale\n", headerFont)); par.add(new Chunk("Jude\u0163ul: ", defFont)); par.add(new Chunk(garbage.getCounty().getName() + "\n", normalFont)); par.add(new Chunk("Comuna: ", defFont)); par.add(new Chunk(garbage.getTown().getName() + "\n", normalFont)); if (garbage.getChartedArea() != null) { par.add(new Chunk("Zona cartare: ", defFont)); par.add(new Chunk(garbage.getChartedArea().getName() + "\n", normalFont)); } par.add(new Chunk("Pozi\u0163ie: ", defFont)); par.add(new Chunk(garbage.getY() + ", " + garbage.getX() + "\n", normalFont)); par.add(new Chunk("Descriere:\n", defFont)); par.add(new Phrase(garbage.getDescription() + "\n", normalFont)); par.add(new Chunk("Componen\u0163\u0103 gunoi:\n", defFont)); List list = new List(); list.add(new ListItem( new Chunk("Procent plastic: " + garbage.getPercentagePlastic() + "%", normalFont))); list.add(new ListItem( new Chunk("Procent sticl\u0103: " + garbage.getPercentageGlass() + "%", normalFont))); list.add(new ListItem(new Chunk("Procent metale: " + garbage.getPercentageMetal() + "%", normalFont))); list.add(new ListItem( new Chunk("Procent nereciclabile: " + garbage.getPercentageWaste() + "%", normalFont))); par.add(list); document.add(par); par = new Paragraph(); par.setSpacingBefore(20); par.add(new Chunk("2. Indica\u0163ii rutiere\n", headerFont)); Image img = Image.getInstance(getImage(garbage)); img.scaleToFit((float) (PageSize.A4.getWidth() * .75), (float) (PageSize.A4.getHeight() * .75)); img.setAlignment(Element.ALIGN_CENTER); par.add(img); document.add(par); if (page < garbages.size() - 1) document.newPage(); page++; } document.close(); }
From source file:rs.marko.helper.Kreiranje.java
public static File createPdfStatistika(List<Stavkadnevneberbe> stavke, Date pocetak, Date kraj) { Document document = new Document(); File yourFile = null;/*ww w . j a v a 2s .c o m*/ try { yourFile = new File(System.getProperty("user.home") + "/Desktop/" + pocetak + "_" + kraj + ".pdf"); if (!yourFile.exists()) { yourFile.createNewFile(); } FileOutputStream oFile = new FileOutputStream(yourFile, false); document.setPageSize(PageSize.A4.rotate()); PdfWriter.getInstance(document, oFile); document.open(); // String text = ""; // for (int i = 0; i < 10000; i++) { // text += "test"; // , } // String jmbg = stavke.get(0).getDobavljac().getJmbg(); PdfPTable table = new PdfPTable( new float[] { 300f, 150f, 150f, 150f, 150f, 150f, 150f, 150f, 150f, 150f, 150f, 150f, 150f }); table.setWidthPercentage(100); table.setSpacingBefore(0f); table.setSpacingAfter(0f); Paragraph p = new Paragraph("Od: " + pocetak + " do: " + kraj); p.add(new Paragraph(" ")); document.add(p); PdfPCell c = new PdfPCell(new Phrase("")); // PdfPCell c1 = new PdfPCell(new Phrase("Sifra")); // c1.setHorizontalAlignment(Element.ALIGN_CENTER); // c1.setRowspan(2); // c1.setColspan(2); // table.addCell(c1); PdfPCell c1 = new PdfPCell(new Phrase("Dobavljac")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setVerticalAlignment(Element.ALIGN_MIDDLE); c1.setRowspan(2); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell(new Phrase("Tacne")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell(new Phrase("I Klasa")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell(new Phrase("II Klasa")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell(new Phrase("III Klasa")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell(new Phrase("Svega")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(3); table.addCell(c1); c1 = new PdfPCell(new Phrase("Kol")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Iznos")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Kol")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Iznos")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Kol")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Iznos")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Kol")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Iznos")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Kol")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Cena")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Iznos")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); Font font = new Font(BaseFont.createFont(), 10, Font.NORMAL); // table.setHeaderRows(3); List<String> jmbgovi = new ArrayList<>(); Map<Double, Double> kt = new HashMap<>(); Map<Double, Double> k1 = new HashMap<>(); Map<Double, Double> k2 = new HashMap<>(); Map<Double, Double> k3 = new HashMap<>(); Map<Double, Double> ukupnoTacneVrednost = new HashMap<>(); Map<Double, Double> ukupnoPrvaKlasaVrednost = new HashMap<>(); Map<Double, Double> ukupnoDrugaKlasaVrednost = new HashMap<>(); Map<Double, Double> ukupnoTrecaKlasaVrednost = new HashMap<>(); for (Stavkadnevneberbe stavkaDnevneBerbe : stavke) { if (!jmbgovi.contains(stavkaDnevneBerbe.getDnevnaberba().getDobavljac().getJmbg())) { jmbgovi.add(stavkaDnevneBerbe.getDnevnaberba().getDobavljac().getJmbg()); } } Double ukupnoKolicinaTacne = 0.0; Double ukupnoKolicinaPrvaKlasa = 0.0; Double ukupnoKolicinaDrugaKlasa = 0.0; Double ukupnoKolicinaTrecaKlasa = 0.0; Double ukupnoCenaTacne = 0.0; Double ukupnoCenaPrvaKlasa = 0.0; Double ukupnoCenaDrugaKlasa = 0.0; Double ukupnoCenaTrecaKlasa = 0.0; Double ukupanIznosSvih = 0.0; for (String j : jmbgovi) { String imeDobavljaca = null; for (Stavkadnevneberbe stavkaDnevneBerbe : stavke) { if (stavkaDnevneBerbe.getDnevnaberba().getDobavljac().getJmbg().equals(j)) { if (imeDobavljaca == null) { imeDobavljaca = stavkaDnevneBerbe.getDnevnaberba().getDobavljac().getIme() + " " + stavkaDnevneBerbe.getDnevnaberba().getDobavljac().getPrezime(); } if (!kt.containsKey(stavkaDnevneBerbe.getCenatacne()) && stavkaDnevneBerbe.getTacne() != 0) { kt.put(stavkaDnevneBerbe.getCenatacne(), new Double(0)); } if (!k1.containsKey(stavkaDnevneBerbe.getCenaprvaklasa()) && stavkaDnevneBerbe.getCenaprvaklasa() != 0) { k1.put(stavkaDnevneBerbe.getCenaprvaklasa(), new Double(0)); } if (!k2.containsKey(stavkaDnevneBerbe.getCenadrugaklasa()) && stavkaDnevneBerbe.getCenadrugaklasa() != 0) { k2.put(stavkaDnevneBerbe.getCenadrugaklasa(), new Double(0)); } if (!k3.containsKey(stavkaDnevneBerbe.getCenatrecaklasa()) && stavkaDnevneBerbe.getCenatrecaklasa() != 0) { k3.put(stavkaDnevneBerbe.getCenatrecaklasa(), new Double(0)); } } } for (Stavkadnevneberbe s : stavke) { if (s.getDnevnaberba().getDobavljac().getJmbg().equals(j)) { if (kt.containsKey(s.getCenatacne())) { kt.put(s.getCenatacne(), kt.get(s.getCenatacne()) + s.getTacne()); } if (k1.containsKey(s.getCenaprvaklasa())) { k1.put(s.getCenaprvaklasa(), k1.get(s.getCenaprvaklasa()) + s.getPrvaklasa()); } if (k2.containsKey(s.getCenadrugaklasa())) { k2.put(s.getCenadrugaklasa(), k2.get(s.getCenadrugaklasa()) + s.getDrugaklasa()); } if (k3.containsKey(s.getCenatrecaklasa())) { k3.put(s.getCenatrecaklasa(), k3.get(s.getCenatrecaklasa()) + s.getTrecaklasa()); } } } c1 = new PdfPCell(new Phrase(imeDobavljaca)); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); Iterator it = kt.entrySet().iterator(); Double ukupnoKolicinaT = 0.0; Double ukupnoCenaT = 0.0; Double ukupanIznos = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoKolicinaT += (Double) pair.getValue(); ukupnoCenaT += (Double) pair.getKey(); ukupanIznos += ((Double) pair.getValue() * (Double) pair.getKey()); //ukupno vrednost if (ukupnoTacneVrednost.containsKey((Double) pair.getKey())) { ukupnoTacneVrednost.put((Double) pair.getKey(), ukupnoTacneVrednost.get((Double) pair.getKey()) + ((Double) pair.getKey() * (Double) pair.getValue())); } else { ukupnoTacneVrednost.put((Double) pair.getKey(), (Double) pair.getKey() * (Double) pair.getValue()); } } c1 = new PdfPCell(new Phrase(round(ukupnoKolicinaT, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupanIznos, 2) + "", font)); table.addCell(c1); it = k1.entrySet().iterator(); Double ukupnoKolicinaP = 0.0; Double ukupnoCenaP = 0.0; Double ukupanIznosP = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoKolicinaP += (Double) pair.getValue(); ukupnoCenaP += (Double) pair.getKey(); ukupanIznosP += ((Double) pair.getValue() * (Double) pair.getKey()); if (ukupnoPrvaKlasaVrednost.containsKey((Double) pair.getKey())) { ukupnoPrvaKlasaVrednost.put((Double) pair.getKey(), ukupnoPrvaKlasaVrednost.get((Double) pair.getKey()) + ((Double) pair.getKey() * (Double) pair.getValue())); } else { ukupnoPrvaKlasaVrednost.put((Double) pair.getKey(), (Double) pair.getKey() * (Double) pair.getValue()); } } c1 = new PdfPCell(new Phrase(round(ukupnoKolicinaP, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupanIznosP, 2) + "", font)); table.addCell(c1); it = k2.entrySet().iterator(); Double ukupnoKolicinaD = 0.0; Double ukupnoCenaD = 0.0; Double ukupanIznosD = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoKolicinaD += (Double) pair.getValue(); ukupnoCenaD += (Double) pair.getKey(); ukupanIznosD += ((Double) pair.getValue() * (Double) pair.getKey()); if (ukupnoDrugaKlasaVrednost.containsKey((Double) pair.getKey())) { ukupnoDrugaKlasaVrednost.put((Double) pair.getKey(), ukupnoDrugaKlasaVrednost.get((Double) pair.getKey()) + ((Double) pair.getKey() * (Double) pair.getValue())); } else { ukupnoDrugaKlasaVrednost.put((Double) pair.getKey(), (Double) pair.getKey() * (Double) pair.getValue()); } } c1 = new PdfPCell(new Phrase(round(ukupnoKolicinaD, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupanIznosD, 2) + "", font)); table.addCell(c1); it = k3.entrySet().iterator(); Double ukupnoKolicinaTr = 0.0; Double ukupnoCenaTr = 0.0; Double ukupanIznosT = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoKolicinaTr += (Double) pair.getValue(); ukupnoCenaTr += (Double) pair.getKey(); ukupanIznosT += ((Double) pair.getValue() * (Double) pair.getKey()); if (ukupnoTrecaKlasaVrednost.containsKey((Double) pair.getKey())) { ukupnoTrecaKlasaVrednost.put((Double) pair.getKey(), ukupnoTrecaKlasaVrednost.get((Double) pair.getKey()) + ((Double) pair.getKey() * (Double) pair.getValue())); } else { ukupnoTrecaKlasaVrednost.put((Double) pair.getKey(), (Double) pair.getKey() * (Double) pair.getValue()); } } c1 = new PdfPCell(new Phrase(round(ukupnoKolicinaTr, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupanIznosT, 2) + "", font)); table.addCell(c1); Double ukupnoKolicina = ukupnoKolicinaT + ukupnoKolicinaP + ukupnoKolicinaD + ukupnoKolicinaTr; Double ukupnoVrednost = ukupanIznos + ukupanIznosP + ukupanIznosD + ukupanIznosT; Double ukupnoCena = ukupnoVrednost / ukupnoKolicina; c1 = new PdfPCell(new Phrase(round(ukupnoKolicina, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupnoCena, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupnoVrednost, 2) + "", font)); table.addCell(c1); ukupanIznosSvih += ukupnoVrednost; ukupnoKolicinaTacne += ukupnoKolicinaT; ukupnoKolicinaPrvaKlasa += ukupnoKolicinaP; ukupnoKolicinaDrugaKlasa += ukupnoKolicinaD; ukupnoKolicinaTrecaKlasa += ukupnoKolicinaTr; ukupnoCenaTacne += ukupanIznos; ukupnoCenaPrvaKlasa += ukupanIznosP; ukupnoCenaDrugaKlasa += ukupanIznosD; ukupnoCenaTrecaKlasa += ukupanIznosT; kt.clear(); k1.clear(); k2.clear(); k3.clear(); } c1 = new PdfPCell(new Phrase("UKUPNO")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoKolicinaTacne + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoCenaTacne + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoKolicinaPrvaKlasa + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoCenaPrvaKlasa + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoKolicinaDrugaKlasa + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoCenaDrugaKlasa + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoKolicinaTrecaKlasa + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(ukupnoCenaTrecaKlasa + "", font)); table.addCell(c1); Double ukupnoKolicinaSve = ukupnoKolicinaTacne + ukupnoKolicinaPrvaKlasa + ukupnoKolicinaDrugaKlasa + ukupnoKolicinaTrecaKlasa; Double prosecnaCena = ukupanIznosSvih / ukupnoKolicinaSve; c1 = new PdfPCell(new Phrase(round(ukupnoKolicinaSve, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(prosecnaCena, 2) + "", font)); table.addCell(c1); c1 = new PdfPCell(new Phrase(round(ukupanIznosSvih, 2) + "", font)); table.addCell(c1); //PDV c1 = new PdfPCell(new Phrase("PDV")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); table.addCell(c); Iterator it = ukupnoTacneVrednost.entrySet().iterator(); Double ukupnoTacnePdv = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if ((Double) pair.getKey() == 110) { ukupnoTacnePdv += (((Double) pair.getValue() / (Double) pair.getKey()) * 106); } else { ukupnoTacnePdv += (Double) pair.getValue(); } } c1 = new PdfPCell(new Phrase(round(ukupnoTacnePdv * (110.0f / 100.0f), 2) + "", font)); table.addCell(c1); table.addCell(c); it = ukupnoPrvaKlasaVrednost.entrySet().iterator(); Double ukupnoPrvaKlasaPdv = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoPrvaKlasaPdv += (Double) pair.getValue(); } c1 = new PdfPCell(new Phrase(round(ukupnoPrvaKlasaPdv * (110.0f / 100.0f), 2) + "", font)); table.addCell(c1); table.addCell(c); it = ukupnoDrugaKlasaVrednost.entrySet().iterator(); Double ukupnoDrugaKlasaPdv = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoDrugaKlasaPdv += (Double) pair.getValue(); } c1 = new PdfPCell(new Phrase(round(ukupnoDrugaKlasaPdv * (110.0f / 100.0f), 2) + "", font)); table.addCell(c1); table.addCell(c); it = ukupnoTrecaKlasaVrednost.entrySet().iterator(); Double ukupnoTrecaKlasaPdv = 0.0; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ukupnoTrecaKlasaPdv += (Double) pair.getValue(); } c1 = new PdfPCell(new Phrase(round(ukupnoTrecaKlasaPdv * (110.0f / 100.0f), 2) + "", font)); table.addCell(c1); c = new PdfPCell(new Phrase("")); c.setColspan(2); table.addCell(c); Double ukupnoSvePDV = ukupnoTacnePdv + ukupnoPrvaKlasaPdv + ukupnoDrugaKlasaPdv + ukupnoTrecaKlasaPdv; c1 = new PdfPCell(new Phrase(round(ukupnoSvePDV * (110.0f / 100.0f), 2) + "", font)); table.addCell(c1); c = new PdfPCell(new Phrase("")); c.setColspan(10); table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); // table.addCell(c); c1 = new PdfPCell(new Phrase("DOBITAK")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setColspan(2); table.addCell(c1); c1 = new PdfPCell( new Phrase(round((ukupnoSvePDV * (110.0f / 100.0f)) - ukupanIznosSvih, 2) + "", font)); table.addCell(c1); document.add(table); document.add(new Paragraph(" ")); } catch (DocumentException ex) { Logger.getLogger(Kreiranje.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(Kreiranje.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Kreiranje.class.getName()).log(Level.SEVERE, null, ex); } document.close(); return yourFile; }
From source file:ru.trett.cis.services.PDFBuilderImpl.java
License:Open Source License
@Override public String createPDF() throws IOException, DocumentException, ApplicationException { try {/* w w w .j av a2 s . c o m*/ String templatePath = servletContext.getRealPath("WEB-INF/resources/template-settings.xml"); Map<String, List<String>> data = TemplateParser.parse(new File(templatePath)); String regularFontPath = servletContext.getRealPath("WEB-INF/resources/fonts/OpenSans-Regular.ttf"); if (regularFontPath == null) throw new ApplicationException("Regular Font file was not found"); BaseFont bfr = BaseFont.createFont(regularFontPath, BaseFont.IDENTITY_H, true); String boldFontPath = servletContext.getRealPath("WEB-INF/resources/fonts/OpenSans-Bold.ttf"); if (boldFontPath == null) throw new ApplicationException("Bold Font file was not found"); BaseFont bfb = BaseFont.createFont(boldFontPath, BaseFont.IDENTITY_H, true); regularFont = new Font(bfr); regularFont.setSize(10); boldFont = new Font(bfb); boldFont.setSize(10); File file = File.createTempFile("order", ".pdf"); Document doc = new Document(PageSize.A4); Chunk glue = new Chunk(new VerticalPositionMark()); PdfWriter.getInstance(doc, new FileOutputStream(file)); doc.open(); doc.newPage(); //title Paragraph p = new Paragraph(data.get("header").get(0), boldFont); p.setAlignment(Element.ALIGN_CENTER); doc.add(p); doc.add(Chunk.NEWLINE); //body for (String text : data.get("text")) { p = new Paragraph(text, regularFont); doc.add(p); } //table doc.add(Chunk.NEWLINE); List<String> cols = data.get("cols"); PdfPTable table = new PdfPTable(cols.size()); table.setWidthPercentage(100); cols.forEach(x -> table.addCell(getCell(x, PdfPCell.ALIGN_CENTER, boldFont))); for (Asset asset : assets) { table.addCell(getCell(String.format("%s %s %s", asset.getDeviceModel().getDeviceType().getType(), asset.getDeviceModel().getDeviceBrand().getBrand(), asset.getDeviceModel().getModel()), PdfPCell.ALIGN_CENTER, regularFont)); table.addCell(getCell(asset.getSerialNumber(), PdfPCell.ALIGN_CENTER, regularFont)); table.addCell(getCell(asset.getInventoryNumber(), PdfPCell.ALIGN_CENTER, regularFont)); } table.getRows(); doc.add(table); doc.add(Chunk.NEWLINE); doc.add(Chunk.NEWLINE); //signers Phrase phrase = new Phrase(new Chunk(data.get("signers").get(0) + " ", regularFont)); phrase.add(Chunk.NEWLINE); phrase.add(new Chunk(issuer.getFirstName() + " " + issuer.getLastName() + " \\__________________", regularFont)); phrase.add(Chunk.NEWLINE); phrase.add(Chunk.NEWLINE); phrase.add(new Chunk(data.get("signers").get(1) + " ", regularFont)); phrase.add(Chunk.NEWLINE); phrase.add(new Chunk(employee.getFirstName() + " " + employee.getLastName() + " \\__________________", regularFont)); doc.add(phrase); //date doc.add(Chunk.NEWLINE); doc.add(Chunk.NEWLINE); p = new Paragraph(data.get("place").get(0), regularFont); p.add(new Chunk(glue)); p.add(date.format(dateFormat)); doc.add(p); doc.close(); return file.getPath(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:Sales.SalesController.java
@FXML private void PrintReciept(MouseEvent event) { try {// w w w . ja v a 2s. com Image im = Image.getInstance("khamals.png"); FileOutputStream sa = new FileOutputStream("Reciept.pdf"); im.scaleAbsolute(150f, 150f); // im.setAbsolutePosition(25,50); im.setBackgroundColor(BaseColor.PINK); Document doc = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(doc, sa); PdfPTable table = new PdfPTable(6); String sh = " Date and Time Of Sale : " + Calendar.getInstance().getTime().toGMTString() + "\n\n"; String header = " KHAMALS \n" + " DESIGNER AND SHOWROOM EXPERT \n " + " MOLYKO BUEA LAST FLOOR ECKO BANK BUILDING\n "; String metda = " INVOICE NUMBER :" + this.RecieptId.getText() + " \n " + " SALES PERSON ID :" + this.CashierName.getText() + " \n CUSTOMER NAME :" + this.CustomerName.getText() + "\n\n"; PdfPCell cell = new PdfPCell(new Phrase("\nRECIEPT")); cell.setColspan(6); cell.setHorizontalAlignment(2); doc.open(); doc.add(im); doc.add(cell); System.out.println(doc.leftMargin()); doc.add(new Paragraph(header)); doc.add(new Paragraph(sh)); doc.add(new Paragraph(metda)); table.addCell("S/N"); table.addCell("PRODUCT NAME"); table.addCell("DESCRIPTION"); table.addCell("QUANTITY"); table.addCell("UNIT PRICE"); table.addCell("TOTAL PRICE"); table.setTotalWidth(1000000); for (int i = 0; i < Cart.getItems().size(); i++) { table.addCell(this.idex.getCellData(i).toString()); table.addCell(this.p.getCellData(i).toString()); table.addCell(this.dsc.getCellData(i).toString()); table.addCell(this.qt.getCellData(i).toString()); table.addCell(this.p.getCellData(i).toString()); table.addCell(this.tp.getCellData(i).toString()); } String footer = " \n Total Amount: " + tot.getText() + "" + " SIGNATURES \n" + "\nCUSTOMER SALES PERSON "; doc.add(table); doc.add(new Paragraph(footer)); doc.addCreationDate(); doc.addAuthor(this.CashierName.getText()); doc.close(); Desktop.getDesktop().open(new File("Reciept.pdf")); } catch (Exception sd) { System.out.println("Error Message :" + sd.getMessage()); } finally { } }
From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java
License:Open Source License
@Override public byte[] export(List<SjukfallEnhet> sjukfallList, PrintSjukfallRequest printSjukfallRequest, RehabstodUser user, int total) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try {/*ww w . j a v a 2 s . c om*/ unicodeCapableFont = new Font( BaseFont.createFont(UNICODE_CAPABLE_FONT_PATH, BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9, Font.NORMAL); Document document = new Document(); document.setPageSize(PageSize.A4); document.setMargins(20, 20, 60, 20); PdfWriter writer = PdfWriter.getInstance(document, bos); // Add handlers for page events writer.setPageEvent(new HeaderEventHandler( Image.getInstance( IOUtils.toByteArray(resourcePatternResolver.getResource(LOGO_PATH).getInputStream())), user.getNamn(), user.getValdVardenhet().getNamn())); writer.setPageEvent(new PageNumberingEventHandler()); document.open(); // Add the front page with meta info document.add(createFrontPage(printSjukfallRequest, user, sjukfallList.size(), total)); // Switch to landscape mode document.setPageSize(PageSize.A4.rotate()); document.newPage(); // Add table with all sjukfall (could span several pages) document.add(createSjukfallTable(sjukfallList, user.getUrval(), printSjukfallRequest.isShowPatientId(), isSrsFeatureActive(user))); // Finish off by closing the document (will invoke the event handlers) document.close(); } catch (DocumentException | IOException | RuntimeException e) { throw new PdfExportServiceException("Failed to create PDF export!", e); } return bos.toByteArray(); }
From source file:server.kartu.tik.iText.java
public String createPDF(String tanggal, ArrayList kegiatan, String divisi) { ArrayList<Kegiatan> list = new ArrayList<>(kegiatan); String output = System.getProperty("user.dir") + "\\src\\data\\pdf\\" + tanggal + " " + getNamalengkap() + "-" + getTglnoktp() + ".pdf"; String namaDivisi = ""; switch (divisi) { case "1": namaDivisi = "Ekonomi"; break;/*from w w w.ja v a 2s . co m*/ case "2": namaDivisi = "Politik"; break; case "3": namaDivisi = "Sosial Budaya"; break; case "4": namaDivisi = "Keamanan"; break; } Document document = new Document(PageSize.A4); try { PdfWriter.getInstance(document, new FileOutputStream(output)); document.open(); //------------------------------------------------------------------------------------- TITLE PdfPTable title = new PdfPTable(1); title.setWidthPercentage(100); Font f = new Font(FontFamily.HELVETICA, 14, Font.NORMAL, GrayColor.GRAYWHITE); PdfPCell celltitle = new PdfPCell(new Phrase("KARTU TIK (" + namaDivisi + ")", f)); celltitle.setMinimumHeight(20); celltitle.setBackgroundColor(GrayColor.GRAYBLACK); celltitle.setHorizontalAlignment(Element.ALIGN_CENTER); celltitle.setColspan(3); title.addCell(celltitle); document.add(title); //-------------------------------------------------------------------------------------- END //------------------------------------------------------------------------------------- NAMA + ALIAS float[] columnWidths = { 8, 2 }; PdfPTable tabel1 = new PdfPTable(columnWidths); tabel1.setWidthPercentage(100); PdfPTable innerTable1 = new PdfPTable(1); innerTable1.setWidthPercentage(100); PdfPTable innerTable2 = new PdfPTable(1); innerTable2.setWidthPercentage(100); PdfPCell cell; innerTable1.addCell( "1. a. Nama Lengkap : " + getNamalengkap() + " \n\n b. Alias : " + getAlias() + " \n\n"); innerTable1.addCell("2. Kebangsaan \n a. Tgl. No. KTP : " + getTglnoktp() + " \n\n b. Tgl. No. Pasport : " + getTglnopasport() + "\n\n"); innerTable1.addCell("3. Agama : " + getAgama()); cell = new PdfPCell(innerTable1); cell.setMinimumHeight(135); tabel1.addCell(cell); if (getUrlfoto().equalsIgnoreCase("") || getUrlfoto().isEmpty() || getUrlfoto() == null) { } else { Image image = Image.getInstance(getUrlfoto()); cell = new PdfPCell(image, false); if (image.getWidth() < 90) { cell.setPaddingLeft(8); } else { cell.setPaddingLeft(3); } } cell.setMinimumHeight(135); tabel1.addCell(cell); cell = new PdfPCell(); cell.setColspan(14); tabel1.addCell(cell); document.add(tabel1); //------------------------------------------------------------------------------------- NAMA + ALIAS END //------------------------------------------------------------------------------------- TGL LAHIR + TEMPAT PdfPTable tabel4 = new PdfPTable(1); tabel4.setWidthPercentage(100); Paragraph pTglLahirnTempat = new Paragraph(); pTglLahirnTempat.add("4. a. Tgl. Lahir/ Umur : " + getTgllahir()); pTglLahirnTempat.add("\n\n b. Tempat Lahir : " + getTempatlahir()); pTglLahirnTempat.setLeading(0, 1); PdfPCell cTglLahirnTempat = new PdfPCell(); cTglLahirnTempat.setMinimumHeight(45); cTglLahirnTempat.addElement(pTglLahirnTempat); tabel4.addCell(cTglLahirnTempat); document.add(tabel4); //------------------------------------------------------------------------------------- TGL LAHIR + TEMPAT END //------------------------------------------------------------------------------------- ALAMAT + PINDAHAN PdfPTable tabel5 = new PdfPTable(1); tabel5.setWidthPercentage(100); Paragraph pAlamat = new Paragraph(); pAlamat.add("5. Alamat : "); pAlamat.add(alamat); pAlamat.setLeading(0, 1); PdfPCell cAlamat = new PdfPCell(); cAlamat.setMinimumHeight(18); cAlamat.addElement(pAlamat); tabel5.addCell(cAlamat); document.add(tabel5); PdfPTable tabel51 = new PdfPTable(1); tabel51.setWidthPercentage(100); Paragraph pAlamatUbah = new Paragraph(); pAlamatUbah.add("6. Perubahan Alamat :"); pAlamatUbah.add("\n\n 1. "); pAlamatUbah.add("\n\n 2. "); pAlamatUbah.add("\n\n 3. "); pAlamatUbah.add("\n\n"); pAlamatUbah.setLeading(0, 1); PdfPCell cAlamatUbah = new PdfPCell(); cAlamatUbah.addElement(pAlamatUbah); tabel51.addCell(cAlamatUbah); document.add(tabel51); //------------------------------------------------------------------------------------- ALAMAT + PINDAHAN END //------------------------------------------------------------------------------------- KEDUDUKAN KELUARGA PdfPTable tabel6 = new PdfPTable(1); tabel6.setWidthPercentage(100); Paragraph pKedudukanKeluarga = new Paragraph(); pKedudukanKeluarga.add("7. Kedudukan dalam Keluarga : "); pKedudukanKeluarga.setLeading(0, 1); PdfPCell cKedudukanKeluarga = new PdfPCell(); cKedudukanKeluarga.setMinimumHeight(20); cKedudukanKeluarga.addElement(pKedudukanKeluarga); tabel6.addCell(cKedudukanKeluarga); document.add(tabel6); PdfPTable tabel61 = new PdfPTable(1); tabel61.setWidthPercentage(100); Paragraph pNamaBapakIbu = new Paragraph(); pNamaBapakIbu.add("8. a. Nama Bapak : "); pNamaBapakIbu.add("\n\n Nama Ibu : "); pNamaBapakIbu.add("\n\n b. Alamat : "); pNamaBapakIbu.setLeading(0, 1); PdfPCell cNamaBapakIbu = new PdfPCell(); cNamaBapakIbu.setMinimumHeight(70); cNamaBapakIbu.addElement(pNamaBapakIbu); tabel61.addCell(cNamaBapakIbu); document.add(tabel61); //------------------------------------------------------------------------------------- KEDUDUKAN END //------------------------------------------------------------------------------------- PEKERJAAN PdfPTable tabel7 = new PdfPTable(2); tabel7.setWidthPercentage(100); Paragraph pPekerjaan = new Paragraph(); pPekerjaan.add("9. a. Pekerjaan : " + getPekerjaan()); pPekerjaan.setLeading(0, 1); PdfPCell cPekerjaan = new PdfPCell(); cPekerjaan.setMinimumHeight(20); cPekerjaan.addElement(pPekerjaan); tabel7.addCell(cPekerjaan); Paragraph pJabatan = new Paragraph(); pJabatan.add(" b. Jabatan : " + getJabatan()); pJabatan.setLeading(0, 1); PdfPCell cJabatan = new PdfPCell(); cJabatan.setMinimumHeight(20); cJabatan.addElement(pJabatan); tabel7.addCell(cJabatan); document.add(tabel7); //------------------------------------------------------------------------------------- PEKERJAAN END //------------------------------------------------------------------------------------- INSTANSI DLL PdfPTable tabel8 = new PdfPTable(1); tabel8.setWidthPercentage(100); Paragraph pInstansi = new Paragraph(); pInstansi.add(" c. Instansi/Lembaga/Kantor : " + getInstansilembagakantor()); pInstansi.setLeading(0, 1); PdfPCell cInstansi = new PdfPCell(); cInstansi.setMinimumHeight(20); cInstansi.addElement(pInstansi); tabel8.addCell(cInstansi); document.add(tabel8); //------------------------------------------------------------------------------------- INSTANSI DLL END //------------------------------------------------------------------------------------- NAMA ISTRI float[] colomn = { 7, 1, 2 }; PdfPTable tabel9 = new PdfPTable(colomn); tabel9.setWidthPercentage(100); Paragraph pNamaIstriBapakIbu = new Paragraph(); pNamaIstriBapakIbu.add("10."); pNamaIstriBapakIbu.add("\n a. Nama Istri : "); pNamaIstriBapakIbu.add("\n\n b. Nama Bapak Istri : "); pNamaIstriBapakIbu.add("\n\n c. Nama Ibu Istri : "); pNamaIstriBapakIbu.add("\n\n d. Alamat : "); pNamaIstriBapakIbu.setLeading(0, 1); PdfPCell cNamaIstriBapakIbu = new PdfPCell(); cNamaIstriBapakIbu.setMinimumHeight(110); cNamaIstriBapakIbu.addElement(pNamaIstriBapakIbu); tabel9.addCell(cNamaIstriBapakIbu); Paragraph pUmurIstriBapakIbu = new Paragraph(); pUmurIstriBapakIbu.add(" Umur :"); pUmurIstriBapakIbu.setLeading(0, 1); PdfPCell cUmurIstriBapakIbu = new PdfPCell(); cUmurIstriBapakIbu.setMinimumHeight(110); cUmurIstriBapakIbu.addElement(pUmurIstriBapakIbu); tabel9.addCell(cUmurIstriBapakIbu); Paragraph pPekerjaanIstriBapakIbu = new Paragraph(); pPekerjaanIstriBapakIbu.add(" Pekerjaan :"); pPekerjaanIstriBapakIbu.setLeading(0, 1); PdfPCell cPekerjaanIstriBapakIbu = new PdfPCell(); cPekerjaanIstriBapakIbu.setMinimumHeight(110); cPekerjaanIstriBapakIbu.addElement(pPekerjaanIstriBapakIbu); tabel9.addCell(cPekerjaanIstriBapakIbu); document.add(tabel9); //------------------------------------------------------------------------------------- NAMA ISTRI END //------------------------------------------------------------------------------------- SANAK SAUDARA PdfPTable tabel10 = new PdfPTable(colomn); tabel10.setWidthPercentage(100); Paragraph pSanakSaudara = new Paragraph(); pSanakSaudara.add("11. Nama Sanak/Saudara yang menjadi Tanggungan : \n 1.\n 2."); pSanakSaudara.setLeading(0, 1); PdfPCell cSanakSaudara = new PdfPCell(); cSanakSaudara.addElement(pSanakSaudara); tabel10.addCell(cSanakSaudara); Paragraph pSanakSaudara1 = new Paragraph(); pSanakSaudara1.add(""); pSanakSaudara1.setLeading(0, 1); PdfPCell cSanakSaudara1 = new PdfPCell(); cSanakSaudara1.addElement(pSanakSaudara1); tabel10.addCell(cSanakSaudara1); Paragraph pSanakSaudara2 = new Paragraph(); pSanakSaudara2.add(""); pSanakSaudara2.setLeading(0, 1); PdfPCell cSanakSaudara2 = new PdfPCell(); cSanakSaudara2.addElement(pSanakSaudara2); tabel10.addCell(cSanakSaudara2); document.add(tabel10); //------------------------------------------------------------------------------------- SANAK SAUDARA END //------------------------------------------------------------------------------------- ANAK2 PdfPTable tabel11 = new PdfPTable(colomn); tabel11.setWidthPercentage(100); Paragraph pAnak2 = new Paragraph(); pAnak2.add("12. Anak-anak : "); pAnak2.add("\n\n 1. "); pAnak2.add("\n\n 2. "); pAnak2.add("\n\n 3. "); pAnak2.add("\n\n 4. "); pAnak2.add("\n\n 5. "); pAnak2.add("\n\n 6. "); pAnak2.add("\n"); pAnak2.setLeading(0, 1); PdfPCell cAnak2 = new PdfPCell(); cAnak2.setMinimumHeight(165); cAnak2.addElement(pAnak2); tabel11.addCell(cAnak2); Paragraph pUmurAnak2 = new Paragraph(); pUmurAnak2.add(" Umur : "); pUmurAnak2.setLeading(0, 1); PdfPCell cUmurAnak2 = new PdfPCell(); cUmurAnak2.setMinimumHeight(165); cUmurAnak2.addElement(pUmurAnak2); tabel11.addCell(cUmurAnak2); Paragraph pPekarjaanAnak2 = new Paragraph(); pPekarjaanAnak2.add(" Pekerjaan : "); pPekarjaanAnak2.setLeading(0, 1); PdfPCell cPekerjaanAnak2 = new PdfPCell(); cPekerjaanAnak2.setMinimumHeight(165); cPekerjaanAnak2.addElement(pPekarjaanAnak2); tabel11.addCell(cPekerjaanAnak2); document.add(tabel11); //------------------------------------------------------------------------------------- ANAK2 END //------------------------------------------------------------------------------------- CIRI-CIRI PdfPTable tabel12 = new PdfPTable(1); tabel12.setWidthPercentage(100); Paragraph pCiri2 = new Paragraph(); pCiri2.add("13. Ciri-ciri badan : "); pCiri2.add("\n\n 1. Rambut : " + getRambut()); for (int i = 0; i < (35 - getRambut().length()); i++) { pCiri2.add(" "); } pCiri2.add("2. Muka : " + getMuka()); for (int i = 0; i < (35 - getMuka().length()); i++) { pCiri2.add(" "); } pCiri2.add("3. Kulit : " + getKulit()); pCiri2.setLeading(0, 1); PdfPCell cCiri2 = new PdfPCell(); cCiri2.setMinimumHeight(45); cCiri2.addElement(pCiri2); tabel12.addCell(cCiri2); document.add(tabel12); //------------------------------------------------------------------------------------- CIRI-CIRI END //------------------------------------------------------------------------------------- LANJUTAN CIRI2 PdfPTable tabel13 = new PdfPTable(1); tabel13.setWidthPercentage(100); Paragraph pCiri2Lanjutan = new Paragraph(); for (int i = 0; i < 20; i++) { pCiri2Lanjutan.add(" "); } pCiri2Lanjutan.add("4. Tinggi : " + getTinggi()); for (int i = 0; i < (35 - getTinggi().length()); i++) { pCiri2Lanjutan.add(" "); } pCiri2Lanjutan.add("5. Tanda Istimewa : " + getTandaistimewa()); pCiri2Lanjutan.setLeading(0, 1); PdfPCell cCiri2Lanjutan = new PdfPCell(); cCiri2Lanjutan.setMinimumHeight(20); cCiri2Lanjutan.addElement(pCiri2Lanjutan); tabel13.addCell(cCiri2Lanjutan); document.add(tabel13); //------------------------------------------------------------------------------------- LANJUTAN CIRI2 //------------------------------------------------------------------------------------- RUMUS SIDIK JARI PdfPTable tabel14 = new PdfPTable(1); tabel14.setWidthPercentage(100); Paragraph pSidikJari = new Paragraph(); pSidikJari.add("14. Rumus Sidik Jari : " + getRumussidikjari()); pSidikJari.setLeading(0, 1); PdfPCell cSidikJari = new PdfPCell(); cSidikJari.setMinimumHeight(20); cSidikJari.addElement(pSidikJari); tabel14.addCell(cSidikJari); document.add(tabel14); //------------------------------------------------------------------------------------- RUMUS SIDIK JARI END //------------------------------------------------------------------------------------- RIWAYAT SEKOLAH float[] colom = { 8, 2 }; PdfPTable tabel15 = new PdfPTable(colom); tabel15.setWidthPercentage(100); Paragraph pRiwayatSekolah = new Paragraph(); pRiwayatSekolah.add("15. Riwayat Sekolah : "); pRiwayatSekolah.add("\n\n 1. "); pRiwayatSekolah.add("\n\n 2. "); pRiwayatSekolah.add("\n\n 3. "); pRiwayatSekolah.add("\n\n 4. "); pRiwayatSekolah.add("\n\n 5. "); pRiwayatSekolah.add("\n\n 6. "); pRiwayatSekolah.setLeading(0, 1); PdfPCell cRiwayatSekolah = new PdfPCell(); cRiwayatSekolah.setMinimumHeight(165); cRiwayatSekolah.addElement(pRiwayatSekolah); tabel15.addCell(cRiwayatSekolah); Paragraph pTahunLulus = new Paragraph(); pTahunLulus.add("Tahun Lulus"); pTahunLulus.setLeading(0, 1); PdfPCell cTahunLulus = new PdfPCell(); cTahunLulus.setMinimumHeight(165); cTahunLulus.addElement(pTahunLulus); tabel15.addCell(cTahunLulus); document.add(tabel15); //------------------------------------------------------------------------------------- RIWAYAT SEKOLAH END //------------------------------------------------------------------------------------- KESENANGAN/KEGEMARAN/HOBI PdfPTable tabel16 = new PdfPTable(1); tabel16.setWidthPercentage(100); Paragraph pKesenenanganKegemaranHobi = new Paragraph(); pKesenenanganKegemaranHobi.add("16. Kesenangan/Kegemaran/Hobi : " + getHobi()); pKesenenanganKegemaranHobi.setLeading(0, 1); PdfPCell cKesenenanganKegemaranHobi = new PdfPCell(); cKesenenanganKegemaranHobi.setMinimumHeight(20); cKesenenanganKegemaranHobi.addElement(pKesenenanganKegemaranHobi); tabel16.addCell(cKesenenanganKegemaranHobi); document.add(tabel16); //------------------------------------------------------------------------------------- KESENANGAN/KEGEMARAN/HOBI END //------------------------------------------------------------------------------------- CATATAN KRIMINAL PdfPTable tabel17 = new PdfPTable(1); tabel17.setWidthPercentage(100); Paragraph pCatatanKriminal = new Paragraph(); pCatatanKriminal.add("17. Catatan kriminal yang ada : "); pCatatanKriminal.add("\n\n 1. " + getCatatankriminal1()); pCatatanKriminal.add("\n\n 2. " + getCatatankriminal2()); pCatatanKriminal.add("\n\n 3. " + getCatatankriminal3()); pCatatanKriminal.setLeading(0, 1); PdfPCell cCatatanKriminal = new PdfPCell(); cCatatanKriminal.setMinimumHeight(95); cCatatanKriminal.addElement(pCatatanKriminal); tabel17.addCell(cCatatanKriminal); document.add(tabel17); //------------------------------------------------------------------------------------- CATATAN KRIMINAL END //------------------------------------------------------------------------------------- KETERANGAN DLL PdfPTable tabel18 = new PdfPTable(1); tabel18.setWidthPercentage(100); Paragraph pDataKeteranganLain2 = new Paragraph(); pDataKeteranganLain2.add("18. Data Keterangan dan lain2 : "); pDataKeteranganLain2.add("\n\n\n"); pDataKeteranganLain2.setLeading(0, 1); PdfPCell cDataKeteranganLain2 = new PdfPCell(); cDataKeteranganLain2.addElement(pDataKeteranganLain2); if (list.size() > 0) { float[] kolomkegiatan = { 8, 2 }; PdfPTable nestedTable = new PdfPTable(kolomkegiatan); nestedTable.addCell(new Paragraph("Kegiatan")); nestedTable.addCell(new Paragraph("Tanggal")); for (int i = 0; i < list.size(); i++) { nestedTable.addCell(new Paragraph(list.get(i).getNamakegiatan())); nestedTable.addCell(new Paragraph(list.get(i).getTanggal())); } cDataKeteranganLain2.addElement(nestedTable); cDataKeteranganLain2.setPaddingBottom(20f); tabel18.addCell(cDataKeteranganLain2); } document.add(tabel18); //------------------------------------------------------------------------------------- KETERANGAN DLL END document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return output; }
From source file:servlet.AdministrarRestriccion.java
public void genDocTren(HttpServletRequest request, HttpServletResponse response) throws Exception { int linea = Integer.parseInt(request.getParameter("idLinea")); //PrintWriter salida = response.getWriter(); HttpSession session = request.getSession(); // PrintWriter out = response.getWriter(); Usuario usr = (Usuario) session.getAttribute("usuario"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/*from w w w . ja va 2 s . co m*/ String nota = new String(request.getParameter("nota").getBytes(), "UTF-8"); String nota2 = new String(request.getParameter("nota2").getBytes(), "UTF-8"); MaterialRodanteJpaController mrjc = new MaterialRodanteJpaController(Conex.getEmf()); MaterialRodante mr = mrjc .findMaterialRodante(Integer.parseInt(request.getParameter("materialRodante"))); String comunicaciones = new String(request.getParameter("comunicaciones").getBytes(), "UTF-8"); String instrucciones = new String(request.getParameter("instrucciones").getBytes(), "UTF-8"); String precauciones = new String(request.getParameter("precauciones").getBytes(), "UTF-8"); String nombre = new String(request.getParameter("nombre").getBytes(), "UTF-8"); String vigencia = request.getParameter("vigencia"); String[] fecha = vigencia.split("-"); LineaJpaController ljc = new LineaJpaController(Conex.getEmf()); Linea l = ljc.findLinea(linea); Document documento = new Document(PageSize.A4); com.itextpdf.text.Font arialNegrita = FontFactory.getFont("arial", 9, Font.BOLD); com.itextpdf.text.Font arial = FontFactory.getFont("arial", 9, Font.PLAIN); com.itextpdf.text.Font saltoDeLinea = FontFactory.getFont("arial", 5, Font.BOLD); Paragraph parrafo = new Paragraph(); int numResAs = 0; int numResDes = 0; RestriccionJpaController rjc = new RestriccionJpaController(Conex.getEmf()); List<Restriccion> restDes = rjc.buscarIdLineaDescendenteDocTren(linea, l.getVelocidadLinea()); List<Restriccion> restAsc = rjc.buscarIdLineaAscendenteDocTren(linea, l.getVelocidadLinea()); int restAscTotal = restAsc.size() - 1; int restDescTotal = restDes.size() - 1; System.out.println(restAscTotal); System.out.println(restDescTotal); PdfWriter.getInstance(documento, baos); documento.open(); do { try { URL url = getClass().getResource("/img/cintillo_s1.png"); Image foto = Image.getInstance(url); foto.scaleToFit(500, 70); foto.setAlignment(Chunk.ALIGN_MIDDLE); documento.add(foto); } catch (Exception e) { e.printStackTrace(); } documento.add(new Paragraph("DOCUMENTO DE TREN: " + nombre, arialNegrita)); documento.add(new Paragraph( "L?NEA: " + l.getNombreLinea() + " : Documento Vlido Para Todos Los Trenes", arialNegrita)); documento.add(new Paragraph(" ", saltoDeLinea)); PdfPTable tabla = new PdfPTable(1); tabla.setHorizontalAlignment(10); tabla.setWidthPercentage(100f); tabla.addCell(new Paragraph("Operaciones Del Tren: circular a una velocidad no mayor de " + l.getVelocidadLinea() + " Km/h", arial)); tabla.addCell(new Paragraph("Nota: " + nota, arial)); //tabla.getDefaultCell().setBorder(2); if (numResAs < restAscTotal) { tabla.getDefaultCell().setBorderWidthBottom(0); tabla.addCell(new Paragraph("Restricciones Ascendentes ", arialNegrita)); } tabla.getDefaultCell().setBorderColorBottom(BaseColor.WHITE); int c = 0; for (int i = numResAs; i <= restAscTotal; i++) { if (c > 30) { break; } // System.out.println("imrimiento asc: "+numResAs); int pkI = (int) (restAsc.get(numResAs).getProgInicio() / 1000); int pkI1 = (int) (((restAsc.get(numResAs).getProgInicio() / 1000) - pkI) * 1000); int pkF = (int) (restAsc.get(numResAs).getProgFinal() / 1000); int pkF1 = (int) (((restAsc.get(numResAs).getProgFinal() / 1000) - pkF) * 1000); tabla.getDefaultCell().setBorder(14); tabla.getDefaultCell().setBorderWidthBottom(0); tabla.getDefaultCell().setBorderWidthTop(0); tabla.addCell(new Paragraph("*PK " + pkI + "+" + pkI1 + " al " + pkF + "+" + pkF1 + " circular a una velocidad no mayor de " + restAsc.get(numResAs).getVelocidadMaxAscendente() + " " + restAsc.get(numResAs).getObservacion(), arial)); numResAs++; c++; } if (c < 30) { tabla.getDefaultCell().setBorderWidthBottom(1); tabla.getDefaultCell().setBorderWidthTop(1); tabla.getDefaultCell().setBorder(14); tabla.addCell(new Paragraph("Restricciones Descendentes ", arialNegrita)); } int d = c; if (c < 30) { for (int i = numResDes; i <= restDescTotal; i++) { if (d > 30) { break; } tabla.getDefaultCell().setBorder(14); tabla.getDefaultCell().setBorderWidthBottom(0); tabla.getDefaultCell().setBorderWidthTop(0); int pkI = (int) (restDes.get(numResDes).getProgFinal() / 1000); int pkI1 = (int) (((restDes.get(numResDes).getProgFinal() / 1000) - pkI) * 1000); int pkF = (int) (restDes.get(numResDes).getProgInicio() / 1000); int pkF1 = (int) (((restDes.get(numResDes).getProgInicio() / 1000) - pkF) * 1000); tabla.addCell(new Paragraph("*PK " + pkI + "+" + pkI1 + " al " + pkF + "+" + pkF1 + " circular a una velocidad no mayor de " + restDes.get(numResDes).getVelocidadMaxDescendente() + " " + restDes.get(numResDes).getObservacion(), arial)); numResDes++; d++; } } int espacios = d; while (espacios < 30) { tabla.getDefaultCell().setBorderWidthBottom(0); tabla.getDefaultCell().setBorderWidthTop(0); tabla.addCell(new Paragraph(" ", arial)); espacios++; } tabla.getDefaultCell().setBorder(15); tabla.getDefaultCell().setBorderWidthBottom(1); tabla.getDefaultCell().setBorderWidthTop(1); tabla.getDefaultCell().setMinimumHeight(50f); tabla.addCell(new Paragraph("Instrucciones: " + instrucciones, arial)); tabla.addCell(new Paragraph("Comunicaciones: " + comunicaciones, arial)); tabla.addCell(new Paragraph("Precauciones: " + precauciones, arial)); tabla.getDefaultCell().setMinimumHeight(10f); tabla.addCell(new Paragraph("Vigencia A Partir De: " + fecha[0] + "/" + fecha[1] + "/" + fecha[2], arial)); tabla.getDefaultCell().setBorder(1); Paragraph preface = new Paragraph(Paragraph.ALIGN_CENTER, "Realizado Por: " + usr.toString() + " - Gerencia de Gestin de Trfico", arialNegrita); preface.setAlignment(Element.ALIGN_CENTER); tabla.addCell(preface); tabla.getDefaultCell().setBorder(0); tabla.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER); preface = new Paragraph(Paragraph.ALIGN_CENTER, "EL NO CUMPLIR CON LAS LIMITACIONES PRESCRITAS EN ESTE" + " DOCUMENTO VA EN CONTRA DE LA SEGURIDAD EN LA CIRCULACIN, POR LO TANTO SER? MOTIVO DE SANCIN", FontFactory.getFont("arial", 8f)); tabla.addCell(preface); preface = new Paragraph(Paragraph.ALIGN_CENTER, "Nota: Informacin sustentada con el informe tcnico " + "de limitaciones de velocidad, emitido por el CCF (Centro de Control de Fallas)", FontFactory.getFont("arial", 8f)); tabla.addCell(preface); preface = new Paragraph(Paragraph.ALIGN_CENTER, "Sentido Ascendente: Sentido en el cual aumenta la progresiva ej: 0+0 -> 41+000 -- Sentido Descendente: Sentido en el cual disminuye la progresiva ej: 41+000 -> 0+0 ", FontFactory.getFont("arial", 6f)); tabla.addCell(preface); preface = new Paragraph(Paragraph.ALIGN_CENTER, "En la lnea Caracas-Cua el sentido ASCENDENTE corresponde a la V?A PAR y el DESCENDENTE a la V?A IMPAR", FontFactory.getFont("arial", 6f)); tabla.addCell(preface); documento.add(tabla); if (numResAs < restAscTotal || numResDes < restDescTotal) { documento.newPage(); } } while (numResAs < restAscTotal || numResDes < restDescTotal); System.out.println("Termine"); //CARACTER?STICAS DE MATERIAL RODANTE documento.newPage(); try { URL url = getClass().getResource("/img/cintillo_s1.png"); Image foto = Image.getInstance(url); foto.scaleToFit(500, 70); foto.setAlignment(Chunk.ALIGN_MIDDLE); documento.add(foto); } catch (Exception e) { e.printStackTrace(); } documento.add(new Paragraph("DOCUMENTO DE TREN: " + nombre, arialNegrita)); documento.add(new Paragraph( "L?NEA: " + l.getNombreLinea() + " : Documento Vlido Para Todos Los Trenes", arialNegrita)); documento.add(new Paragraph(" ", saltoDeLinea)); documento.add( new Paragraph("CARACTER?STICAS DE LA UNIDAD: " + mr.getNombreMaterialRodante(), arialNegrita)); documento.add(new Paragraph(" ", saltoDeLinea)); PdfPTable tablaMT = new PdfPTable(2); tablaMT.addCell(new Paragraph("ITEM", arialNegrita)); tablaMT.addCell(new Paragraph("DESCRIPCIN", arialNegrita)); tablaMT.addCell(new Paragraph("Nmero de Unidades Remolque", arial)); tablaMT.addCell(new Paragraph(mr.getNumeroRemolque() + " Unidades", arial)); tablaMT.addCell(new Paragraph("Nmero de Unidades Motriz", arial)); tablaMT.addCell(new Paragraph(mr.getNumeroMotriz() + " Unidades", arial)); tablaMT.addCell(new Paragraph("Longitud Total", arial)); tablaMT.addCell(new Paragraph(mr.getLongitudTotal() + " m", arial)); tablaMT.addCell(new Paragraph("Longitud Coche Remolque", arial)); tablaMT.addCell(new Paragraph(mr.getLongitudRemolque() + " m", arial)); tablaMT.addCell(new Paragraph("Longitud Coche Motriz", arial)); tablaMT.addCell(new Paragraph(mr.getLongitudMotriz() + " m", arial)); tablaMT.addCell(new Paragraph("Alto x Ancho Coche Motriz", arial)); tablaMT.addCell(new Paragraph(mr.getAltoXAnchoMotriz() + " m", arial)); tablaMT.addCell(new Paragraph("Alto x Ancho Coche Remolque", arial)); tablaMT.addCell(new Paragraph(mr.getAltoXAnchoRemolque() + " m", arial)); tablaMT.addCell(new Paragraph("Masa o Tara Total", arial)); tablaMT.addCell(new Paragraph(mr.getMasa() + " t", arial)); tablaMT.addCell(new Paragraph("Masa Coche Remolque", arial)); tablaMT.addCell(new Paragraph(mr.getMasaRemolque() + " t", arial)); tablaMT.addCell(new Paragraph("Masa Coche Motriz", arial)); tablaMT.addCell(new Paragraph(mr.getMasaMotriz() + " t", arial)); tablaMT.addCell(new Paragraph("Frenado", arial)); tablaMT.addCell(new Paragraph(mr.getFrenadoDescripcion() + "", arial)); tablaMT.addCell(new Paragraph("Trocha", arial)); tablaMT.addCell(new Paragraph(l.getTrocha() + " m", arial)); tablaMT.addCell(new Paragraph("Velocidad Comercial", arial)); tablaMT.addCell(new Paragraph(mr.getVelocidadOperativa() + " Km/h", arial)); tablaMT.addCell(new Paragraph("Aceleracin Mx.", arial)); tablaMT.addCell(new Paragraph(mr.getAceleracionMax() + " m/s^2", arial)); tablaMT.addCell(new Paragraph("Desaceleracin de Servicio", arial)); tablaMT.addCell(new Paragraph(mr.getDesaceleracionMax() + " m/s^2", arial)); tablaMT.addCell(new Paragraph("Desaceleracion de Emergencia", arial)); tablaMT.addCell(new Paragraph(mr.getDesaceleracionEmergencia() + " m/s^2", arial)); tablaMT.addCell(new Paragraph("Voltaje", arial)); tablaMT.addCell(new Paragraph(mr.getVoltaje() + " V", arial)); tablaMT.addCell(new Paragraph("Voltaje de Bateras", arial)); tablaMT.addCell(new Paragraph(mr.getVoltajeBateria() + " V", arial)); tablaMT.addCell(new Paragraph("Presin de Trabajo", arial)); tablaMT.addCell(new Paragraph(mr.getPresionTrabajo() + "", arial)); if (mr.getSubTipo().equals("Tren de Viajeros")) { tablaMT.addCell(new Paragraph("Capacidad Coche Remolque", arial)); tablaMT.addCell(new Paragraph(mr.getCapacidadRemolque() + " pasajeros", arial)); tablaMT.addCell(new Paragraph("Capacidad Coche Motriz", arial)); tablaMT.addCell(new Paragraph(mr.getCapacidadMotriz() + " pasajeros", arial)); tablaMT.addCell(new Paragraph("Capacidad Total", arial)); tablaMT.addCell(new Paragraph(mr.getCapacidadPasajeros() + " pasajeros", arial)); } else { tablaMT.addCell(new Paragraph("Capacidad Coche Remolque", arial)); tablaMT.addCell(new Paragraph(mr.getCapacidadRemolque() + " t", arial)); tablaMT.addCell(new Paragraph("Capacidad Coche Motriz", arial)); tablaMT.addCell(new Paragraph(mr.getCapacidadMotriz() + " t", arial)); tablaMT.addCell(new Paragraph("Capacidad Total", arial)); tablaMT.addCell(new Paragraph(mr.getCapacidadPasajeros() + " t", arial)); } documento.add(tablaMT); documento.add(new Paragraph(" ", saltoDeLinea)); documento.add(new Paragraph(" ", saltoDeLinea)); try { URL url = getClass().getResource("/img/" + request.getParameter("materialRodante") + ".jpg"); Image foto = Image.getInstance(url); foto.scaleToFit(300, 300); foto.setAlignment(Chunk.ALIGN_MIDDLE); documento.add(foto); } catch (Exception e) { e.printStackTrace(); } documento.add(new Paragraph(" ", saltoDeLinea)); documento.add(new Paragraph(" ", saltoDeLinea)); PdfPTable t = new PdfPTable(1); t.setWidthPercentage(100f); t.addCell("Nota: " + nota2); documento.add(t); documento.add(new Paragraph(" ", saltoDeLinea)); documento.add(new Paragraph(" ", saltoDeLinea)); Paragraph preface = new Paragraph(Paragraph.ALIGN_CENTER, "Realizado Por: " + usr.toString(), arialNegrita); documento.add(preface); documento.close(); response.addHeader("Content-Disposition", "attachment; filename=DocumentoDeTren.pdf"); response.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.addHeader("Pragma", "public"); response.setContentType("application/pdf"); DataOutput output = new DataOutputStream(response.getOutputStream()); byte[] bytes = baos.toByteArray(); response.setContentLength(bytes.length); for (int i = 0; i < bytes.length; i++) { output.writeByte(bytes[i]); } } catch (Exception e) { e.printStackTrace(); // salida.print("http://localhost:8084/MODULO2.3/img/error.png"); } }
From source file:Servlet.PDFServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from ww w .j a va2s . co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String strData = request.getParameter("hidden_pdfData"); //System.out.println("strData_new --> " + strData); String[] strSplitData = strData.split("###"); String strBerichtname; String strTable; strBerichtname = strSplitData[0]; strTable = strSplitData[1]; String strAusgabe = "Es ist ein unerwartetes Problem aufgetreten"; boolean boolLeerbericht = true; HttpSession userSession = request.getSession(); switch (strBerichtname) { case "Einsatzbericht leer": strAusgabe = generiereAusgabeEinsatzberichtLeer(strTable, strSplitData[2]); break; case "bungsbericht leer": strAusgabe = generiereAusgabeUebungsberichtLeer(strTable, strSplitData[2]); break; case "Ttigkeitsbericht leer": strAusgabe = generiereAusgabeTaetigkeitsberichtLeer(strTable, strSplitData[2]); break; case "Dynamisch": strAusgabe = "<h1>" + strBerichtname + "</h1>" + strTable; boolLeerbericht = false; break; case "Kursstatistik": if (strTable.split("<td>").length > 1 && strSplitData[2].split("<td>").length > 1) { strAusgabe = "<h1>" + strBerichtname + "</h1>" + strSplitData[2].replace("</br>", "") + "<p> </p>" + strTable; } else if (strTable.split("<td>").length < 2) { strAusgabe = "<h1>" + strBerichtname + "</h1>" + strSplitData[2].replace("</br>", ""); } else if (strSplitData[2].split("<td>").length < 2) { strAusgabe = "<h1>" + strBerichtname + "</h1>" + strTable; } boolLeerbericht = false; break; case "Digitales Fahrtenbuch": if (strSplitData.length > 2) { strAusgabe = "<h1>" + strBerichtname + "</h1>" + strSplitData[2] + "<p> </p>" + strTable; } else { strAusgabe = "<h1>" + strBerichtname + "</h1>" + strTable; } boolLeerbericht = false; break; case "Stundenauswertung je Mitglied je Instanz": strAusgabe = "<h1>" + strBerichtname + "</h1>" + generiereStundenauswertungJeMitgliedJeInstanz(strTable); boolLeerbericht = false; break; case "Geburtstagsliste": strAusgabe = "<h1>" + strBerichtname + " " + userSession.getAttribute("attJahr") + "</h1>" + strTable; boolLeerbericht = false; break; case "Dienstzeitliste": strAusgabe = "<h1>" + strBerichtname + " " + userSession.getAttribute("attJahrDienst") + "</h1>" + strTable; boolLeerbericht = false; break; default: strAusgabe = "<h1>" + strBerichtname + "</h1>" + strTable; boolLeerbericht = false; } String strContextPath = this.getServletContext().getRealPath("/"); String strCSSPath1 = strContextPath + File.separator + "css" + File.separator + "pdfSimpel.css"; String strFontPath = strContextPath + File.separator + "res" + File.separator + "Cambria.ttf"; //FAIL - just ignore //strAusgabe = strAusgabe.substring(0, pos+5) + ("<thead>" + strAusgabe.split("<thead>")[1].split("</thead>")[0] + "</thead>") + strAusgabe.substring(pos+5); //String strHead = "<thead>" + strAusgabe.split("<thead>")[1].split("</thead>")[0] + "</thead>"; //String strUeberschrift = "<h1>" + strAusgabe.split("<h1>")[1].split("</h1")[0] + "</h1>"; if (!strBerichtname.contains("leer")) { strAusgabe = strAusgabe.replace("<table", "<table style='repeat-header: yes;' "); } Rectangle rect; try { Document document; if (liBerHochformat.contains(strBerichtname)) { document = new Document(PageSize.A4, 36, 36, 100, 54); rect = new Rectangle(36, 54, 559, 788); } else { document = new Document(PageSize.A4.rotate(), 36, 36, 70, 54); rect = new Rectangle(36, 54, 805, 559); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); PDF_KopfFuzeile event = new PDF_KopfFuzeile(strFontPath, writer); writer.setBoxSize("pageRect", rect); writer.setPageEvent(event); document.open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(false); //hier werden die CSS files eingebunden cssResolver.addCssFile(strCSSPath1, true); if (liBerHochformat.contains(strBerichtname)) { cssResolver.addCssFile(strCSSPath1.replace("Simpel", "Hoch"), true); } else { cssResolver.addCssFile(strCSSPath1.replace("Simpel", "Quer"), true); } if (!boolLeerbericht) { cssResolver.addCssFile(strCSSPath1.replace("Simpel", "StandartBericht"), true); } else { cssResolver.addCssFile(strCSSPath1.replace("Simpel", "Leerbericht"), true); } Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(worker); XMLParser p2 = new XMLParser(worker); p.toString(); //ByteArrayInputStream bis = new ByteArrayInputStream(strAusgabe.toString().getBytes()); //ByteArrayInputStream cis = new ByteArrayInputStream(strCSSPath1.replace("Simple", "Hoch").toString().getBytes()); //XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis, cis); //p.selectState().selfClosing(); p.parse(new StringReader(strAusgabe)); document.close(); writer.close(); strBerichtname = strBerichtname.replaceAll(" ", "_"); response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "filename=" + strBerichtname + ".pdf"); response.setContentLength(baos.size()); ServletOutputStream os = response.getOutputStream(); baos.writeTo(os); os.flush(); os.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } catch (CssResolverException ex) { Logger.getLogger(PDFServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Servlets.PDF.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/pdf"); Document document = new Document(PageSize.A4, 50, 50, 50, 50); try {//from w w w . ja v a2 s. co m //obtengo datos de cliente, reserva y total String rreserva = request.getParameter("reserva"); String rcliente = request.getParameter("cliente"); String rtotal = request.getParameter("total"); //String rtipo = request.getParameter("esProv"); // Obtener datos de cliente e items de reserva DtUsuario dtu = getDtUsuario(rcliente); String nombre = dtu.getNombre(); String apellido = dtu.getApellido(); String servicios = ""; String promos = ""; java.util.List<DtItemReserva> dtItems = listarItems(Integer.parseInt(rreserva)).getItems(); Iterator<DtItemReserva> iter = dtItems.iterator(); DtItemReserva dtItem; // Crear y abrir documento String HomeDeUSuario = System.getProperty("user.home"); String ruta = HomeDeUSuario + "/Factura Reserva " + rreserva + ".pdf"; FileOutputStream archivo = new FileOutputStream(ruta); PdfWriter writer = PdfWriter.getInstance(document, archivo); document.open(); Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); String fecha = dateFormat.format(date); // Agregar marcador inicial // Crear y agregar prrafo simple Paragraph paragraph1 = new Paragraph(); Image imagen = Image.getInstance("http://localhost:8084/Help4TravelingWeb/img/logo-icon2.png"); imagen.scaleAbsolute(200f, 200f); imagen.setAbsolutePosition(10, 650); imagen.setSpacingAfter(20); paragraph1.add(imagen); document.add(paragraph1); //fecha Paragraph fecha1 = new Paragraph(fecha); //encabezado Paragraph futuros = new Paragraph("Futuros Tecnologos SRL"); Paragraph rut = new Paragraph("RUT 123456789012"); Paragraph direccion = new Paragraph(" Av. Gral. Rivera 3629"); Paragraph telefono = new Paragraph(" Tel: 555-5412"); Paragraph nombre_empresa = new Paragraph(" Help4Travelling"); //datos cliente String nombrecliente = nombre.toUpperCase() + " " + apellido.toUpperCase(); String direccioncliente = " "; String rutcliente = "consumidor final".toUpperCase(); Paragraph cliente = new Paragraph("Cliente: " + nombrecliente); Paragraph dircliente = new Paragraph("Direccion: " + direccioncliente); Paragraph rutcli = new Paragraph("RUT: " + rutcliente); //datos boleta String factura = rreserva; Paragraph tipodoc = new Paragraph("Contado"); Paragraph Nfac = new Paragraph(" N " + factura); //alineaciones //fecha fecha1.setAlignment(Element.ALIGN_RIGHT); //encabezado futuros.setAlignment(Element.ALIGN_CENTER); rut.setAlignment(Element.ALIGN_CENTER); direccion.setAlignment(Element.ALIGN_CENTER); telefono.setAlignment(Element.ALIGN_CENTER); //nombre empresa nombre_empresa.setAlignment(Element.ALIGN_LEFT); nombre_empresa.setSpacingBefore(10); nombre_empresa.setSpacingAfter(30); //datos de boleta tipodoc.setAlignment(Element.ALIGN_RIGHT); Nfac.setAlignment(Element.ALIGN_RIGHT); document.add(fecha1); document.add(futuros); document.add(rut); document.add(direccion); document.add(telefono); document.add(nombre_empresa); document.add(tipodoc); document.add(Nfac); document.add(cliente); document.add(dircliente); document.add(rutcli); PdfPTable tabla = new PdfPTable(4); tabla.setSpacingBefore(25); tabla.setSpacingAfter(25); //creo encabezado de tabla PdfPCell codigo = new PdfPCell(new Phrase("Proveedor".toUpperCase())); PdfPCell descripcion = new PdfPCell(new Phrase("descripcion".toUpperCase())); PdfPCell ecantidad = new PdfPCell(new Phrase("cantidad".toUpperCase())); PdfPCell eprecio = new PdfPCell(new Phrase("precio".toUpperCase())); tabla.setHeaderRows(1); tabla.setWidthPercentage(100f); //alineamos las frases del cabezal codigo.setHorizontalAlignment(Element.ALIGN_CENTER); descripcion.setHorizontalAlignment(Element.ALIGN_CENTER); ecantidad.setHorizontalAlignment(Element.ALIGN_CENTER); eprecio.setHorizontalAlignment(Element.ALIGN_CENTER); //agrego cabezal de tabla tabla.addCell(codigo); tabla.addCell(descripcion); tabla.addCell(ecantidad); tabla.addCell(eprecio); //obtengo datos de la reserva para imprimir las distintas rows while (iter.hasNext()) { dtItem = iter.next(); Integer cantidad = dtItem.getCantidad(); String oferta = dtItem.getOferta().getNombre(); String precio; String proveedor; if (existeServicio(oferta)) { proveedor = getNkProveedorServicio(oferta); DtServicio dts = getDtServicio(oferta, proveedor); precio = String.valueOf(dts.getPrecio()); } else { proveedor = getNkProveedorPromocion(oferta); DtPromocion dtp = getDTPromocion(oferta, proveedor); precio = dtp.getDescuento(); } /* String item = "<li>Nombre: <em>" + oferta + "</em>" + " - Cantidad: <em>" + cantidad + "</em>" + " - $:<em>" + precio + "</em>" + " - Proveedor: <em>" + proveedor + "</em></li>";*/ //creo encabezado de tabla PdfPCell iproveedor = new PdfPCell(new Phrase(proveedor.toUpperCase())); PdfPCell icantidad = new PdfPCell(new Phrase(cantidad.toString())); PdfPCell iprecio = new PdfPCell(new Phrase(precio.toUpperCase())); tabla.setHeaderRows(1); //alineamos las frases del cabezal iproveedor.setHorizontalAlignment(Element.ALIGN_CENTER); icantidad.setHorizontalAlignment(Element.ALIGN_CENTER); iprecio.setHorizontalAlignment(Element.ALIGN_CENTER); tabla.addCell(iproveedor); if (existeServicio(oferta)) { PdfPCell idescripcion = new PdfPCell(new Phrase("servicio: " + oferta)); idescripcion.setHorizontalAlignment(Element.ALIGN_CENTER); tabla.addCell(idescripcion); } else { PdfPCell idescripcion = new PdfPCell(new Phrase("Promo: " + oferta)); idescripcion.setHorizontalAlignment(Element.ALIGN_CENTER); tabla.addCell(idescripcion); } tabla.addCell(icantidad); tabla.addCell(iprecio); } /* // las distintas rows de los articulos tabla.addCell(proveedor); tabla.addCell(oferta); tabla.addCell(cantidad); tabla.addCell(precio); */ //el ulimo de la tabla que da el total PdfPCell celdaFinal = new PdfPCell(new Paragraph("")); PdfPCell celdaTotal = new PdfPCell(new Paragraph("total:")); PdfPCell celdaPrecioTotal = new PdfPCell(new Paragraph(rtotal)); // Indicamos cuantas columnas ocupa la celda celdaFinal.setColspan(2); celdaTotal.setHorizontalAlignment(Element.ALIGN_RIGHT); celdaPrecioTotal.setHorizontalAlignment(Element.ALIGN_RIGHT); tabla.addCell(celdaFinal); tabla.addCell(celdaTotal); tabla.addCell(celdaPrecioTotal); document.add(tabla); document.close(); if (request.getParameter("dispositivo").equals("true")) response.sendRedirect("Movil.Reservas.jsp"); else response.sendRedirect("Usuario.jsp"); } catch (DocumentException e) { e.printStackTrace(); } }