List of usage examples for com.lowagie.text Document add
public boolean add(Element element) throws DocumentException
Element
to the Document
. From source file:br.edu.ifrs.restinga.sgru.bean.RelatorioBean.java
/** * Cria um cabealho para o documento PDF * @param document/*w w w .j a va 2 s . c o m*/ */ public void preProcessPDF(Object document) { try { Document pdf = (Document) document; pdf.setPageSize(PageSize.A4); pdf.open(); Paragraph preface = new Paragraph(); // Titulo String titulo; if (this.relatorioCompras) { titulo = "Compras realizadas no perodo de " + this.getDataInicialFormatada() + " a " + this.getDataFinalFormatada(); } else { titulo = "Recargas realizadas no perodo de " + this.getDataInicialFormatada() + " a " + this.getDataFinalFormatada(); } // Titulo centralizado preface.setAlignment(Element.ALIGN_CENTER); // We add one empty line addEmptyLine(preface, 1); // Lets write a big header preface.add(new Paragraph(titulo, CAT_FONT)); addEmptyLine(preface, 1); // O restante serah alinhado a a esquerda preface.setAlignment(Element.ALIGN_LEFT); // Nome de quem requisitou o relatorio SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy 's' HH'h'mm"); String dataSolicitacao = fmt.format(Calendar.getInstance().getTime()); preface.add(new Paragraph("Relatrio gerado por " + this.controlador.getUsuarioLogado().getNome() + " em " + dataSolicitacao, SMALL_BOLD)); // Forma de pagamento, Tipo de Cliente e Nome do Cliente if (this.controlador.isUsuarioLogadoGerente()) { // Opcao para relatorio de compras apenas if (this.relatorioCompras) { String formaPgto; if (this.controlador.getFormaPgto() == FORMA_PGTO_CARTAO) { formaPgto = "Carto"; } else { formaPgto = "Ticket"; } preface.add(new Paragraph("Forma de Pagamento: " + formaPgto, SMALL_BOLD)); } // Tipo de cliente //String tipoUsuario = this.controlador.getDescricaoCodigoCliente(); String tipoCliente = "Todos"; if (this.controlador.getTipoCliente() != null) { tipoCliente = this.controlador.getTipoCliente().getDescricao(); } // Tipo de usuario e cliente nao serah impresso para ticket if ((this.controlador.getFormaPgto() != FORMA_PGTO_TICKET)) { // Tipo de usuario preface.add(new Paragraph("Tipo de Usurio: " + tipoCliente, SMALL_BOLD)); // Cliente String nomeCliente = "Todos"; if (this.controlador.getCliente() != null) { nomeCliente = this.controlador.getCliente().getNome(); } preface.add(new Paragraph("Nome do Cliente: " + nomeCliente, SMALL_BOLD)); } } addEmptyLine(preface, 1); pdf.add(preface); } catch (DocumentException e) { enviarMensagem(FacesMessage.SEVERITY_ERROR, e.getMessage()); } }
From source file:br.edu.ifrs.restinga.sgru.modelo.ControladorVenda.java
/** * Realiza a venda de um ticket para um cliente * * @param documento// w ww . j a v a2 s .c o m * @throws br.edu.ifrs.restinga.sgru.excessao.TicketInvalidoException */ //public void realizarVendaTicket(Object documento) throws TicketInvalidoException { public void realizarVendaTicket() throws TicketInvalidoException { if (this.quantidade <= 0) { throw new TicketInvalidoException("Venda de Quantidade invalida!"); } Document pdfTicket = new Document(); File temp; try { temp = File.createTempFile("imp_ticket", ".pdf"); PdfWriter.getInstance(pdfTicket, new FileOutputStream(temp)); pdfTicket.open(); pdfTicket.setPageSize(PageSize.A4); Table tabela = new Table(1); tabela.setWidth(100); for (int i = 0; i < this.quantidade; i++) { VendaTicketsRecargas vendaTicketsRecarga = new VendaTicketsRecargas(); vendaTicketsRecarga.setCaixaRU(this.caixaRU); vendaTicketsRecarga.realizarVendaTicket(); Cell celula = new Cell(); celula.setHorizontalAlignment(Element.ALIGN_CENTER); celula.add(new Paragraph("SISTEMA DE GERENCIAMENTO DE RESTAURANTE UNIVERSIT?RIO")); Paragraph parag = new Paragraph(); parag.getFont().setSize(18); parag.add("TICKET"); celula.add(parag); // Gerando o codigo convetido do ticket String conversor = ""; for (char con : String.format("%07d", vendaTicketsRecarga.getTicket().getId()).toCharArray()) { conversor = con + conversor; } parag = new Paragraph(); parag.getFont().setSize(20); parag.add(String.valueOf(Integer.valueOf(conversor, 16))); celula.add(parag); NumberFormat format = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); format.setMaximumFractionDigits(2); celula.add(new Paragraph("VALOR " + format.format(vendaTicketsRecarga.getTicket().getValor()))); celula.add(new Paragraph(vendaTicketsRecarga.getTicket().getDataCriado().getTime().toString())); celula.add(new Paragraph(" _ ")); tabela.addCell(celula); this.caixaRU.atualizarLstVendaTicketsRecargas(vendaTicketsRecarga); } pdfTicket.add(tabela); } catch (DocumentException | IOException de) { throw new TicketInvalidoException(de.getMessage()); } finally { pdfTicket.close(); } // Abrindo o pdf no pc try { Desktop.getDesktop().open(temp); temp.deleteOnExit(); } catch (IOException ex) { throw new TicketInvalidoException(ex.getMessage()); } }
From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java
License:Open Source License
public static boolean geraRelatorio(File file) { TradGeraRelatorioPDF.carregaTexto(TokenLang.LANG); Document document = new Document(PageSize.A4); try {// ww w . ja v a 2 s .co m PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setPageEvent(new HeaderAndFooter()); document.open(); int linha = 0, j, tot_pg = ResumoDoRelatorio.getTotPage(); //calcula o total de htmls float tot_link = 0.0f; for (j = 1; j <= tot_pg; j++) { String conteudo = ResumoDoRelatorio.getPage(j); String arr[] = conteudo.split("\n"); tot_link += arr.length; } PainelStatusBar.showProgTarReq(); //loop por todas as pginas da paginacao for (j = 1; j <= tot_pg; j++) { String conteudo = ResumoDoRelatorio.getPage(j); String arr[] = conteudo.split("\n"); int tot = arr.length; int i; //loop por todos os links for (i = 0; i < tot; i++) { progresso = (linha++ / tot_link) * 100.0f; PainelStatusBar.setValueProgress((int) progresso); String arr2[] = arr[i].split("\t"); if (arr2.length == 8) { String strUrl = arr2[7];// URL /* int ap1 = Integer.parseInt(arr2[4]);// Aviso1 int ep1 = Integer.parseInt(arr2[1]);// Erro1 int ap2 = Integer.parseInt(arr2[5]);// Aviso2 int ep2 = Integer.parseInt(arr2[2]);// Erro2 int ap3 = Integer.parseInt(arr2[6]);// Aviso3 int ep3 = Integer.parseInt(arr2[3]);// Erro3 */ String myHash = arr2[0]; RelatorioDaUrl relatorio = new RelatorioDaUrl(); relatorio.recarregaArquivoRelatorioEmXml2(myHash); document.add(new Phrase("\n")); Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD); Chunk url = new Chunk(strUrl, font); Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL); p1.add(url); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p1); document.add(new Phrase("\n\n")); if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0 && relatorio.getErrosPrioridade3() <= 0) { Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS); p2.setAlignment(Paragraph.ALIGN_CENTER); document.add(p2); } else { if (relatorio.getErrosPrioridade1() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP1()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade2() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP2()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade3() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP3()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } document.newPage(); } } } } writer.flush(); document.close(); } catch (DocumentException de) { log.error(de.getMessage(), de); PainelStatusBar.hideProgTarReq(); return false; } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); PainelStatusBar.hideProgTarReq(); return false; } PainelStatusBar.hideProgTarReq(); return true; }
From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java
License:Open Source License
public static boolean geraRelatorio_bkp(File file, ResumoDoRelatorio resumo) { Document document = new Document(PageSize.A4); try {/*from ww w . ja v a2s.c om*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setPageEvent(new HeaderAndFooter()); document.open(); ArrayList<RelatorioDaUrl> relatorios = resumo.getRelatorios(); loop: for (RelatorioDaUrl relatorio : relatorios) { document.add(new Phrase("\n")); Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD); Chunk url = new Chunk(relatorio.getUrl(), font); Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL); p1.add(url); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p1); document.add(new Phrase("\n\n")); if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0 && relatorio.getErrosPrioridade3() <= 0) { Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS); p2.setAlignment(Paragraph.ALIGN_CENTER); document.add(p2); continue loop; } if (relatorio.getErrosPrioridade1() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1_SEM_TAB, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP1()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade2() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2_SEM_TAB, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP2()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade3() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3_SEM_TAB, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP3()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } document.newPage(); } writer.flush(); document.close(); } catch (DocumentException de) { log.error(de.getMessage(), de); return false; } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); return false; } return true; }
From source file:bs.global.web.CustomizeDocument.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.open();//from w ww . j a v a 2 s . co m pdf.setPageSize(PageSize.A4); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "image" + File.separator + "logo.png"; pdf.add(Image.getInstance(logo)); }
From source file:bucks.AuditSheet.java
License:Open Source License
void generateSheet(HttpServletResponse res, List<Batch> batches) { ///*from ww w. ja v a 2s. co m*/ // paper size legal (A4) 8.5 x 11 // page 1-inch = 72 points // String spacer = " \n"; ServletOutputStream out = null; String filename = "marketbucks_audit_sheet.pdf"; try { // space // Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11" Document document = new Document(pageSize, 36, 36, 18, 18);// 18,18,54,35 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); URL imgUrl = new URL(imageUrl); Image image = Image.getInstance(imgUrl); image.scalePercent(20f); // image.scaleAbsolute(100f, 100f);// width, height // image.setRotation(3.1f); // in radians // image.setRotationDegrees(90f); // degrees // image.setSpacingBefore(10f); // image.setSpacingAfter(10f); // image.setWidthPercentage(25.0f); Font fnt = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL); Font fntb = new Font(Font.TIMES_ROMAN, 12, Font.BOLD); Font fntb2 = new Font(Font.TIMES_ROMAN, 14, Font.BOLD); Phrase spacePhrase = new Phrase(); Chunk ch = new Chunk(spacer, fnt); spacePhrase.add(ch); float[] widths = { 25f, 75f }; // percentages PdfPTable headTable = new PdfPTable(widths); headTable.setWidthPercentage(100); headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell cell = new PdfPCell(image); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); headTable.addCell(cell); Phrase phrase = new Phrase(); ch = new Chunk("Printed Market Bucks Audit Sheet\n ", fntb2); phrase.add(ch); Paragraph pp = new Paragraph(); pp.setIndentationLeft(20); pp.setAlignment(Element.ALIGN_LEFT); pp.add(phrase); cell = new PdfPCell(pp); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); headTable.addCell(cell); document.add(headTable); // document.add(spacePhrase); document.add(spacePhrase); // float[] widths3 = { 50f, 50f }; // percentages PdfPTable table = new PdfPTable(widths3); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); phrase = new Phrase(); ch = new Chunk(" Date: ", fntb); phrase.add(ch); ch = new Chunk(Helper.getToday() + "\n\n\n", fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk(" ", fntb); // empty cell phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // document.add(table); // phrase = new Phrase(new Chunk("\n", fnt)); document.add(phrase); // float[] widths2 = { 15f, 10f, 15f, 15f, 15f, 15f, 15f }; // percentages table = new PdfPTable(widths2); table.setWidthPercentage(90); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); // table.getDefaultCell().setPadding(5); phrase = new Phrase(); ch = new Chunk("Count of MB/GC", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Value", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Total Dollars", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Printed By", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Start Number", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("End Number", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("Printed Date", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // // next rows // for (Batch one : batches) { phrase = new Phrase(); ch = new Chunk(one.getBatch_size(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("$" + one.getValue() + ".00", fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk(moneyFormat.format(one.getTotal()), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk(one.getUser().toString(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk(one.getStart_seq(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk(one.getEnd_seq(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk(one.getDate(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(1f); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); } document.add(table); // document.add(spacePhrase); document.add(spacePhrase); // ch = new Chunk("Audit By:____________________________________________________________________\n\n", fnt); phrase = new Phrase(); phrase.add(ch); document.add(phrase); ch = new Chunk(" :_______________________________________)_____________________________\n\n", fnt); phrase = new Phrase(); phrase.add(ch); document.add(phrase); ch = new Chunk(" :_____________________________________________________________________\n\n", fnt); phrase = new Phrase(); phrase.add(ch); document.add(phrase); // document.add(spacePhrase); document.add(spacePhrase); // document.close(); writer.close(); res.setHeader("Expires", "0"); res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "public"); // // setting the content type res.setHeader("Content-Disposition", " attachment; filename=" + filename); res.setContentType("application/pdf"); // // the contentlength is needed for MSIE!!! res.setContentLength(baos.size()); // out = res.getOutputStream(); if (out != null) { baos.writeTo(out); } } catch (Exception ex) { System.err.println(ex); } }
From source file:bucks.GenerateChecks.java
License:Open Source License
void generate_mb(Document document, int seq, String value, Image image, PdfWriter writer) { try {/* ww w. j a v a 2 s .co m*/ float[] widths = { 15f, 40f, 45f }; // percentages PdfPTable table = new PdfPTable(widths); table.setWidthPercentage(100); table.setSpacingAfter(0f); table.setSpacingBefore(0f); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); PdfPCell cell = new PdfPCell(image); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_TOP); // cell.setFixedHeight(46f); table.addCell(cell); Phrase phrase = new Phrase(); Chunk ch = new Chunk("FARMERS' MARKET BUCKS\n", fntb2); phrase.add(ch); ch = new Chunk("Parks & Recreation\nBloomington, IN", fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Issue Date___________ ", fnt10); phrase.add(ch); ch = new Chunk("No. " + seq, fnt10); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); table.addCell(cell); // // document.add(table); // phrase = new Phrase(); ch = new Chunk("\nThis certificate is good for ", fnt); phrase.add(ch); ch = new Chunk("$" + value + ".00 ", fntb2); phrase.add(ch); ch = new Chunk("towards the purchase of ", fnt); phrase.add(ch); ch = new Chunk("eligible food items ", fntb); phrase.add(ch); ch = new Chunk("at the Bloomington Community Farmers' Market. ", fnt); phrase.add(ch); ch = new Chunk("No change allowed. \n", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setFixedHeight(48f); cell.setColspan(3); table.addCell(cell); document.add(table); // float[] widths2 = { 60f, 25f, 10f, 5f }; table = new PdfPTable(widths2); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); //table.getDefaultCell().setPadding(0); table.setSpacingAfter(0f); table.setSpacingBefore(0f); // phrase = new Phrase(); ch = new Chunk( "Customers shall redeem this certificate at Farmers' Market\nby December 1st of the year issued.", fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setColspan(2); cell.setFixedHeight(81f); table.addCell(cell); // Barcode barcode = BarcodeFactory.createCode39("" + seq, false); // barcode text has problem, so we turned off // and decided to add it ourselves. barcode.setDrawingText(false); // barcode.setFont(new java.awt.Font("Arial", java.awt.Font.PLAIN, 16)); // barcode.setLabel(""+seq); BufferedImage bi = BarcodeImageHandler.getImage(barcode); /* int width = bi.getWidth(); int height = bi.getHeight(); Graphics2D g2 = bi.createGraphics(); g2.setColor(Color.BLACK); g2.drawString(""+seq, 60, 70); g2.dispose(); */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // added this hack to get rid of underline in the barcode // this worked on windows, but the text did not show up on linux // that is why we decided to abandon the text all the way // and add it ourselves /* BarcodeImageHandler.writePNG(barcode, baos); File bcImg = File.createTempFile("bc-", ".png"); bcImg.deleteOnExit(); byte[] imageBytes = baos.toByteArray(); FileOutputStream fos = new FileOutputStream(bcImg); BarcodeImageHandler.writePNG(barcode, fos); */ // // old ImageIO.write(bi, "png", baos); byte[] imageBytes = baos.toByteArray(); // Image barCodeImage = Image.getInstance(imageBytes); barCodeImage.setRotationDegrees(90f); // barCodeImage.scalePercent(35f); barCodeImage.scalePercent(35f, 50f); // float widthf = barCodeImage.getWidth(); // float heightf = barCodeImage.getHeight(); cell = new PdfPCell(barCodeImage); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(0); cell.setLeading(0f, 0f); // cell.setFixedHeight(81f); table.addCell(cell); // // the barcode text that we added underneath the barcode // int textWidth = 53, textHeight = 50; BufferedImage bi2 = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g = bi2.createGraphics(); g.setFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 10)); g.setColor(Color.WHITE); g.fillRect(0, 0, textWidth, textHeight); g.setColor(Color.BLACK); g.drawString("" + seq, 5, 10); g.dispose(); baos = new ByteArrayOutputStream(); ImageIO.write(bi2, "png", baos); imageBytes = baos.toByteArray(); Image barCodeTextImage = Image.getInstance(imageBytes); barCodeTextImage.setRotationDegrees(90f); cell = new PdfPCell(barCodeTextImage); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(0); cell.setLeading(0f, 0f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("\nThis certificate is not refundable and cannot be replaced if lost or stolen.\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setFixedHeight(34f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("\nMust have official stamp to be valid.\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setColspan(3); table.addCell(cell); document.add(table); // float[] widths4 = { 40f, 60f }; // percentages table = new PdfPTable(widths4); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); table.setSpacingBefore(0f); table.setSpacingAfter(0f); phrase = new Phrase(); ch = new Chunk("APPROVED BY THE STATE BOARD OF ACCOUNTS\nFOR THE CITY OF BLOOMINGTON, IN 2007\n\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setFixedHeight(40f); // 40 table.addCell(cell); phrase = new Phrase(); ch = new Chunk( "VENDERS SHALL REDEEM THIS CERTIFICATE THROUGH BLOOMINGTON'S\nPARKS & REC DEPT. BY DECEMBER 15TH OF THE YEAR ISSUED\n\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); document.add(table); } catch (Exception ex) { System.err.println(ex); } }
From source file:bucks.GenerateChecks.java
License:Open Source License
void generate_gc(Document document, int seq, String value, Image image, PdfWriter writer) { try {//from ww w . j ava 2s . c om float[] widths = { 13f, 54f, 33f }; // percents PdfPTable table = new PdfPTable(widths); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.setSpacingAfter(0f); table.setSpacingBefore(0f); PdfPCell cell = new PdfPCell(image); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setFixedHeight(46f); table.addCell(cell); Phrase phrase = new Phrase(); Chunk ch = new Chunk("FARMERS' MARKET GIFT CERTIFICATE\n", fntb2); phrase.add(ch); ch = new Chunk("Parks & Recreation\nBloomington, IN", fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Issue Date__________ ", fnt10); phrase.add(ch); ch = new Chunk("No. " + seq, fnt10); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("\nThis certificate is good for ", fnt); phrase.add(ch); ch = new Chunk("$" + value + ".00 ", fntb2); phrase.add(ch); ch = new Chunk("towards the purchase of ", fnt); phrase.add(ch); ch = new Chunk("products from ", fnt); phrase.add(ch); ch = new Chunk("the Bloomington Community Farmers' Market and A Fair of The Arts Vendors. ", fnt); phrase.add(ch); ch = new Chunk("Change may be given. \n", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setColspan(3); cell.setFixedHeight(48f); table.addCell(cell); document.add(table); // float[] widths2 = { 60f, 25f, 10f, 5f }; table = new PdfPTable(widths2); table.setWidthPercentage(100); table.setSpacingBefore(0f); table.setSpacingAfter(0f); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); // phrase = new Phrase(); ch = new Chunk("Customers shall redeem this certificate at Market\nwithin one year of date issued. ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setColspan(2); cell.setFixedHeight(81f); table.addCell(cell); Barcode barcode = BarcodeFactory.createCode39("" + seq, true); barcode.setDrawingText(false); BufferedImage bi = BarcodeImageHandler.getImage(barcode); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ImageIO.write(bi, "png", baos); byte[] imageBytes = baos.toByteArray(); // Image barCodeImage = Image.getInstance(imageBytes); barCodeImage.setRotationDegrees(90); // barCodeImage.scalePercent(35f); barCodeImage.scalePercent(35f, 50f); cell = new PdfPCell(barCodeImage); // cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(0); cell.setLeading(0f, 0f); table.addCell(cell); // // adding text underneath the barcode // int textWidth = 53, textHeight = 50; BufferedImage bi2 = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g = bi2.createGraphics(); g.setFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 10)); g.setColor(Color.WHITE); g.fillRect(0, 0, textWidth, textHeight); g.setColor(Color.BLACK); g.drawString("" + seq, 5, 10); g.dispose(); baos = new ByteArrayOutputStream(); ImageIO.write(bi2, "png", baos); imageBytes = baos.toByteArray(); Image barCodeTextImage = Image.getInstance(imageBytes); barCodeTextImage.setRotationDegrees(90f); cell = new PdfPCell(barCodeTextImage); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(0); cell.setLeading(0f, 0f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("\nThis certificate is not refundable and cannot be replaced if lost or stolen.\n\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setFixedHeight(30f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("\nMust have official stamp to be valid.\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setColspan(3); table.addCell(cell); document.add(table); // float[] widths3 = { 40f, 60f }; // percentages table = new PdfPTable(widths3); table.setWidthPercentage(100); table.setSpacingBefore(0f); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); phrase = new Phrase(); ch = new Chunk("APPROVED BY THE STATE BOARD OF ACCOUNTS\nFOR THE CITY OF BLOOMINGTON, IN 2007\n\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); // cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setFixedHeight(44f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk( "VENDERS SHALL REDEEM THIS CERTIFICATE THROUGH BLOOMINGTON'S\nPARKS & REC DEPT. BY DECEMBER 15TH OF THE YEAR RECEIVED\n\n\n", fnts); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); document.add(table); // document.add( Chunk.NEWLINE ); } catch (Exception ex) { System.err.println(ex); } }
From source file:bucks.RedeemInvoice.java
License:Open Source License
void generateInvoice(HttpServletResponse res, Redeem redeem) { ////w ww .jav a 2 s . co m // paper size legal (A4) 8.5 x 11 // page 1-inch = 72 points // String spacer = " \n"; User user = redeem.getUser(); Vendor vendor = redeem.getVendor(); List<Buck> bk_bucks = redeem.getBk_bucks(); List<Buck> gc5_bucks = redeem.getGc5_bucks(); List<Buck> gc20_bucks = redeem.getGc20_bucks(); List<Buck> gc_bucks = redeem.getGc_bucks(); List<Dispute> disputes = redeem.getDisputes(); int bk_total = 0, gc5_total = 0, gc20_total = 0, total = 0; if (bk_bucks.size() > 0) { bk_total = bk_bucks.size() * 3; } if (gc5_bucks.size() > 0) { gc5_total = gc5_bucks.size() * 5; } if (gc20_bucks.size() > 0) { gc20_total = gc20_bucks.size() * 20; } total = bk_total + gc5_total + gc20_total; String vendor_name = ""; if (vendor != null) { vendor_name = vendor.getCleanName(); } ServletOutputStream out = null; String filename = "invoice_" + vendor_name + "_" + redeem.getId() + ".pdf"; try { // space // Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11" Document document = new Document(pageSize, 36, 36, 18, 18);// 18,18,54,35 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); Image image = Image.getInstance(imageUrl); // image = Image.getInstance(byte bytes[]);// generated image image.scalePercent(20f); Font fnt = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL); Font fntb = new Font(Font.TIMES_ROMAN, 12, Font.BOLD); Font fntb2 = new Font(Font.TIMES_ROMAN, 14, Font.BOLD); // Phrase spacePhrase = new Phrase(); Chunk ch = new Chunk(spacer, fnt); spacePhrase.add(ch); float[] widths = { 15f, 85f }; // percentages PdfPTable headTable = new PdfPTable(widths); headTable.setWidthPercentage(100); headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // image.setWidthPercentage(15.0f); PdfPCell cell = new PdfPCell(image); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setFixedHeight(46f); headTable.addCell(cell); Phrase phrase = new Phrase(); ch = new Chunk( "City of Bloomington Community Farmers Market\n Gift Certificates/Market Bucks Invoice\n ", fntb2); phrase.add(ch); Paragraph pp = new Paragraph(); pp.setIndentationLeft(20); pp.setAlignment(Element.ALIGN_LEFT); pp.add(phrase); cell = new PdfPCell(pp); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); headTable.addCell(cell); document.add(headTable); // float[] widths3 = { 50f, 50f }; // percentages PdfPTable table = new PdfPTable(widths3); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); phrase = new Phrase(); ch = new Chunk(" Vendor Name: ", fntb); phrase.add(ch); ch = new Chunk(vendor.getFullName(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Date: ", fntb); phrase.add(ch); ch = new Chunk(redeem.getDate(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); phrase = new Phrase(); ch = new Chunk(" Vendor Number: ", fntb); phrase.add(ch); ch = new Chunk(vendor.getId(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); phrase = new Phrase(); // empty cell ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); table.addCell(cell); // extra space table.addCell(cell); document.add(table); // phrase = new Phrase(new Chunk("\n", fnt)); document.add(phrase); // float[] widths2 = { 30f, 25f, 15f, 15f, 15f }; // percentages table = new PdfPTable(widths2); table.setWidthPercentage(90); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); // table.getDefaultCell().setPadding(5); phrase = new Phrase(); ch = new Chunk("Type of Voucher", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("City Account Number", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("Quantity", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("Multiply", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("Value", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setBorderWidth(2f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // // second row phrase = new Phrase(); ch = new Chunk("Market Bucks", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("201-18-1865003-47240", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); String str = " "; if (bk_bucks.size() > 0) { str = "" + bk_bucks.size(); } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("x $3.00 = ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); phrase = new Phrase(); str = " "; if (bk_total > 0) { str = "$" + bk_total + ".00"; } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); // // 3rd row phrase = new Phrase(); ch = new Chunk("$5 Gift Cerificates", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("201-18-1865003-47230", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); str = " "; if (gc5_bucks.size() > 0) { str = "" + gc5_bucks.size(); } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("x $5.00 = ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); phrase = new Phrase(); str = " "; if (gc5_total > 0) { str = "$" + gc5_total + ".00"; } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); // // 4th row phrase = new Phrase(); ch = new Chunk("$20 Gift Certificates", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("201-18-1865003-47230", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); // phrase = new Phrase(); str = " "; if (gc20_bucks.size() > 0) { str = "" + gc20_bucks.size(); } ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); phrase = new Phrase(); ch = new Chunk("x $20.00 = ", fnt); phrase.add(ch); cell = new PdfPCell(phrase); table.addCell(cell); str = " "; if (gc20_total > 0) { str = "$" + gc20_total + ".00"; } phrase = new Phrase(); ch = new Chunk(str, fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setPadding(4); table.addCell(cell); // // 5th row total phrase = new Phrase(); ch = new Chunk(" Total Value: ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setColspan(4); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk("$" + total + ".00", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); cell.setPadding(4); cell.setLeading(2f, 1.2f); table.addCell(cell); document.add(table); // // float[] withs5 = { 100f }; table = new PdfPTable(withs5); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase(" ")); cell.setBorder(Rectangle.BOTTOM); // cell.setBorderColorBottom(Color.BLACK); cell.setBorderWidthBottom(2f); table.addCell(cell); document.add(table); // ch = new Chunk("\n", fnt); phrase = new Phrase(); phrase.add(ch); document.add(phrase); // // float[] widths3 = {50f, 50f}; // percentages table = new PdfPTable(widths3); table.setWidthPercentage(100); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); phrase = new Phrase(); ch = new Chunk(" Data Entry Completed by: ", fntb); phrase.add(ch); ch = new Chunk(user.getFullName(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); // phrase = new Phrase(); ch = new Chunk(" Invoice Number: ", fntb); phrase.add(ch); ch = new Chunk(redeem.getId(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); document.add(table); document.add(spacePhrase); document.add(spacePhrase); // // adding bucks and GC // float[] widths4 = { 100f }; // percentages table = new PdfPTable(widths4); table.setWidthPercentage(100); // table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); int row = 1, col = 1; if (bk_bucks.size() > 0) { phrase = new Phrase(); ch = new Chunk(" Market Bucks ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); table.addCell(cell); phrase = new Phrase(); for (Buck one : bk_bucks) { ch = new Chunk("" + one.getId() + " ", fntb); phrase.add(ch); col++; if (col > 15) { row++; col = 1; cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); phrase = new Phrase(); } } if (col > 1) { cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } if (row < 10) { for (int j = 0; j < 2; j++) { phrase = new Phrase(); ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } } } col = 1; if (gc_bucks.size() > 0) { phrase = new Phrase(); ch = new Chunk(" Gift Certificates ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); table.addCell(cell); phrase = new Phrase(); for (Buck one : gc_bucks) { ch = new Chunk("" + one.getId() + " ", fntb); phrase.add(ch); col++; if (col > 15) { row++; col = 1; cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); phrase = new Phrase(); } } if (col > 1) { cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } if (row < 15) { for (int j = 0; j < 2; j++) { phrase = new Phrase(); ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } } } if (disputes != null && disputes.size() > 0) { phrase = new Phrase(); ch = new Chunk(" Disputed Market Bucks and/or Gift Certificates (number: reason)", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidth(2f); table.addCell(cell); row++; for (Dispute one : disputes) { phrase = new Phrase(); ch = new Chunk(one.getBuck_id() + ": " + one.getReason(), fnt); phrase.add(ch); if (one.hasNotes()) { ch = new Chunk("\nNotice: " + one.getNotes(), fnt); phrase.add(ch); row++; } cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } } if (redeem.hasNotes()) { phrase = new Phrase(); ch = new Chunk("\nNotice: " + redeem.getNotes(), fnt); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); row++; } if (row < 18) { for (int j = row; j < 18; j++) { phrase = new Phrase(); ch = new Chunk(" ", fntb); phrase.add(ch); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } } document.add(table); document.close(); writer.close(); res.setHeader("Expires", "0"); res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "public"); // // setting the content type res.setHeader("Content-Disposition", " attachment; filename=" + filename); res.setContentType("application/pdf"); // // the contentlength is needed for MSIE!!! res.setContentLength(baos.size()); // out = res.getOutputStream(); if (out != null) { baos.writeTo(out); } } catch (Exception ex) { System.err.println(ex); } }
From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java
License:Open Source License
/** * Outputs a PDF file report of the data in drs to the given * output stream./*w w w. j a v a2 s . c om*/ * @throws SQLObjectException * @throws IllegalAccessException * @throws InstantiationException */ public void format(OutputStream out, List<ProfileResult> profileResults) throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException, IllegalAccessException, ClassNotFoundException { final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow final int mtop = 50; // margin at top of page (in points) final int mbot = 50; // margin at bottom of page (page numbers are below this) // final int pbot = 20; // padding between bottom margin and bottom of body text final int mlft = 50; // margin at left side of page final int mrgt = 50; // margin at right side of page final Rectangle pagesize = PageSize.LETTER.rotate(); final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot); final PdfWriter writer = PdfWriter.getInstance(document, out); final float fsize = 6f; // the font size to use in the table body final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); document.addTitle("Table Profiling Report"); document.addSubject("Tables: " + profileResults); document.addAuthor(System.getProperty("user.name")); document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION); document.open(); // vertical position where next element should start // (bottom is 0; top is pagesize.height()) float pos = pagesize.height() - mtop; final PdfContentByte cb = writer.getDirectContent(); final PdfTemplate nptemplate = cb.createTemplate(50, 50); writer.setPageEvent(new PdfPageEventHelper() { // prints the "page N of <template>" footer public void onEndPage(PdfWriter writer, Document document) { int pageN = writer.getPageNumber(); String text = "Page " + pageN + " of "; float len = bf.getWidthPoint(text, fsize - 2); cb.beginText(); cb.setFontAndSize(bf, fsize - 2); cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2); cb.showText(text); cb.endText(); cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2); } public void onCloseDocument(PdfWriter writer, Document document) { nptemplate.beginText(); nptemplate.setFontAndSize(bf, fsize - 2); nptemplate.showText(String.valueOf(writer.getPageNumber() - 1)); nptemplate.endText(); } }); document.add(new Paragraph("SQL Power Architect Profiling Report")); document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name"))); float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result Font f = new Font(bf, fsize); // This ddl generator is set to the appropriate ddl generator for the source database // every time we encounter a table profile result in the list. DDLGenerator ddlg = null; PdfPTable pdfTable = null; for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } double allowedTableSize = pagesize.width() - mrgt - mlft; double totalWidths = 0; for (int i = 0; i < headings.length; i++) { if (!columnsToTruncate.contains(headings[i])) { widths[i] += PIXELS_PER_BORDER; totalWidths += widths[i]; } } truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size()))) / columnsToTruncate.size(); logger.debug("Truncate length is " + truncateLength); widths = new float[totalColumn]; profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } for (int i = 0; i < headings.length; i++) { widths[i] += PIXELS_PER_BORDER; } // add the PdfPTables to the document; try to avoid orphan and widow rows pos = writer.getVerticalPosition(true) - fsize; logger.debug("Starting at pos=" + pos); boolean newPageInd = true; for (ProfileTableStructure profile : profiles) { pdfTable = profile.getMainTable(); pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft); pdfTable.setWidths(widths); resetHeaderWidths(profile, widths); int startrow = pdfTable.getHeaderRows(); int endrow = startrow; // current page will contain header+startrow..endrow /* no other rows in the table, just the header, and the header may * contain error message */ if (endrow == pdfTable.size()) { pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); continue; } while (endrow < pdfTable.size()) { // figure out how many body rows fit nicely on the page float endpos = pos - calcHeaderHeight(pdfTable); // y position of page number# = (mbot/2+fsize) while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2) && endrow < pdfTable.size()) { endpos -= pdfTable.getRowHeight(endrow); endrow++; } // adjust for orphan rows. Might create widows or make // endrow < startrow, which is handled later by deferring the table if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) { // page # maybe fall into table area, but usually that's column of // min value, usually that's enough space for both, or we should // disable page # on this page if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) { // short by 1 row.. just squeeze it in endrow = pdfTable.size(); } else { // more than 1 row remains: shorten this page so orphans aren't lonely endrow = pdfTable.size() - minRowsTogether; } } if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) { // this is the end of the table, or we have enough rows to bother printing pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb); startrow = endrow; newPageInd = false; } else { // not the end of the table and not enough rows to print out if (newPageInd) throw new IllegalStateException( "PDF Page is not large engouh to display " + minRowsTogether + " row(s)"); endrow = startrow; } // new page if necessary (that is, when we aren't finished the table yet) if (endrow != pdfTable.size()) { document.newPage(); pos = pagesize.height() - mtop; newPageInd = true; } } } document.close(); }