List of usage examples for com.itextpdf.text Image setAbsolutePosition
public void setAbsolutePosition(final float absoluteX, final float absoluteY)
Image
. 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 {// w w w. j av a 2 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(); } }
From source file:servlets.POPDF.java
private void buildpdf(PurchaseOrderDTO dto, HttpServletResponse response) { Font catFont = new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD); Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD); Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); String IMG = getServletContext().getRealPath("/img/logo.png"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); VendorDTO venDTO = venModel.getVendor(dto.getVendorno(), ds); DecimalFormat decimal = new DecimalFormat("#0.00"); ArrayList<ProductDTO> products = prodModel.getProdsForVendor(dto.getVendorno(), ds); ArrayList<POLineItemDTO> poLineItems = dto.getItems(); try {//from w w w . j a va 2s. co m PdfWriter.getInstance(document, baos); document.open(); Paragraph preface = new Paragraph(); // We add one empty line Image image1 = Image.getInstance(IMG); image1.setAbsolutePosition(55f, 760f); preface.add(image1); preface.setAlignment(Element.ALIGN_RIGHT); // Lets write a big header Paragraph mainHead = new Paragraph(String.format("%55s", "Purchase Order"), catFont); preface.add(mainHead); preface.setAlignment(Element.ALIGN_LEFT); preface.add(new Paragraph(String.format("%82s", "PO#: " + dto.getPONumber()), subFont)); addEmptyLine(preface, 3); preface.add(new Paragraph(String.format("%10s", "Vendor: ", smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getName(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getAddress1(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getCity(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getProvince(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getPostalCode(), smallBold))); addEmptyLine(preface, 1); // 3 column table PdfPTable table = new PdfPTable(5); PdfPCell cell = new PdfPCell(new Paragraph("Product Code", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Product Description", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Quantity Sold", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Price", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Ext Price", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); for (POLineItemDTO item : poLineItems) { cell = new PdfPCell(new Phrase(item.getproductcode())); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); for (ProductDTO prod : products) { if (prod.getProductcode().equals(item.getproductcode())) { cell = new PdfPCell(new Phrase(prod.getProductname())); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } } cell = new PdfPCell(new Phrase(Integer.toString(item.getQuantity()))); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); double extPrice = 0.0; for (ProductDTO prod : products) { if (prod.getProductcode().equals(item.getproductcode())) { cell = new PdfPCell(new Phrase(Double.toString(prod.getCostprice()))); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); extPrice = prod.getCostprice() * item.getQuantity(); } } String extPriceStr = decimal.format(extPrice); cell = new PdfPCell(new Phrase(extPriceStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } //end for double sub = dto.getAmount(); double tax = dto.getAmount() * 0.13; double total = dto.getAmount() * 1.13; String taxStr = decimal.format(tax); String totalStr = decimal.format(total); String subStr = decimal.format(sub); cell = new PdfPCell(new Phrase("Total:")); cell.setColspan(4); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase(subStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase("Tax:")); cell.setColspan(4); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase(taxStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell = new PdfPCell(new Phrase("Order Total:")); cell.setColspan(4); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase(totalStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBackgroundColor(BaseColor.YELLOW); table.addCell(cell); preface.add(table); addEmptyLine(preface, 3); preface.setAlignment(Element.ALIGN_CENTER); preface.add(new Paragraph(String.format("%60s", "Generated on: " + dto.getPODate()), subFont)); document.add(preface); document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); // the contentlength response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream OutputStream os = response.getOutputStream(); baos.writeTo(os); os.flush(); os.close(); } catch (Exception e) { System.out.println("Error " + e.getMessage()); } }
From source file:servlets.POServlet.java
private void buildpdf(HttpServletResponse response, int ponumber) { Font catFont = new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD); Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD); Font titleFont = new Font(Font.FontFamily.COURIER, 16, Font.BOLD); Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); String IMG = getServletContext().getRealPath("/img/logo.png"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); //Get the Purchase Order Items - That way we can access the vendor PurchaseOrderModel poModel = new PurchaseOrderModel(); PurchaseOrderDTO poDTO = poModel.getPurchaseOrder(ponumber, ds); ArrayList<PurchaseOrderLineItemDTO> lineitems = poModel.getLineItemsForPoNumber(ponumber, ds); //Have items, now need to get vendor VendorModel vModel = new VendorModel(); VendorDTO vendor = vModel.getVendor(poDTO.getVendorno(), ds); //Product Model - For looking up product names ProductModel prodMod = new ProductModel(); try {// w w w . j a va 2s . c om PdfWriter.getInstance(document, baos); document.open(); Paragraph preface = new Paragraph(); // We add one empty line Image image1 = Image.getInstance(IMG); image1.setAbsolutePosition(55f, 650f); image1.scaleAbsolute(200f, 200f); preface.add(image1); preface.add(new Paragraph("Guardians Light Equipment\nBest Exotics in the Cosmos", titleFont)); preface.setAlignment(Element.ALIGN_RIGHT); // Lets write a big header Paragraph mainHead = new Paragraph(String.format("%55s", "Purchase Order"), catFont); preface.add(mainHead); preface.add(new Paragraph(String.format("%82s", "PO#:" + ponumber), subFont)); addEmptyLine(preface, 1); //2 Column Vendor Table PdfPTable vendorTable = new PdfPTable(1); PdfPCell vCell = new PdfPCell(new Phrase("Vendor:", smallBold)); vCell.setHorizontalAlignment(Element.ALIGN_RIGHT); vCell.setBorder(0); vendorTable.addCell(vCell); vendorTable.addCell(GenerateBorderlessCell(vendor.getName(), 0, Element.ALIGN_RIGHT)); vendorTable.addCell(GenerateBorderlessCell(vendor.getAddress1(), 0, Element.ALIGN_RIGHT)); vendorTable.addCell( GenerateBorderlessCell(vendor.getCity() + "," + vendor.getProvince(), 0, Element.ALIGN_RIGHT)); vendorTable.addCell(GenerateBorderlessCell(vendor.getPostalcode(), 0, Element.ALIGN_RIGHT)); preface.add(vendorTable); addEmptyLine(preface, 2); //Generate Headers PdfPTable table = new PdfPTable(5); //Generate the Headers table.addCell(GenerateCellData("Product Code")); table.addCell(GenerateCellData("Product Description")); table.addCell(GenerateCellData("Quantity Sold")); table.addCell(GenerateCellData("Price")); table.addCell(GenerateCellData("Extended Price")); double subTotal = 0.0; for (PurchaseOrderLineItemDTO item : lineitems) { ProductDTO product = prodMod.getProduct(item.getProductcode(), ds); table.addCell(GenerateCellData(product.getProductcode())); table.addCell(GenerateCellData(product.getProductname())); table.addCell(GenerateCellData(String.valueOf(item.getQty()))); double ext = product.getCostprice() * item.getQty(); table.addCell(GenerateCellData("$" + String.format("%.2f", product.getCostprice()))); table.addCell(GenerateCellData("$" + String.format("%.2f", ext))); subTotal += ext; } //Generate Total, Tax, Order Total table.addCell(GenerateBorderlessCell("Subtotal:", 4, Element.ALIGN_RIGHT)); table.addCell(GenerateFinalValue("$" + String.format("%.2f", subTotal))); table.addCell(GenerateBorderlessCell("Tax:", 4, Element.ALIGN_RIGHT)); table.addCell(GenerateFinalValue("$" + String.format("%.2f", subTotal * 0.13))); table.addCell(GenerateBorderlessCell("Order Total:", 4, Element.ALIGN_RIGHT)); PdfPCell totalCell = GenerateFinalValue("$" + String.format("%.2f", poDTO.getTotal())); totalCell.setBackgroundColor(BaseColor.YELLOW); table.addCell(totalCell); preface.add(table); addEmptyLine(preface, 3); preface.setAlignment(Element.ALIGN_CENTER); preface.add(new Paragraph(String.format("%60s", "PO Generated on: " + poDTO.getPodate()), subFont)); document.add(preface); document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "inline; filename=\"sample.PDF\""); response.setContentType("application/octet-stream"); try ( // write ByteArrayOutputStream to the ServletOutputStream OutputStream os = response.getOutputStream()) { baos.writeTo(os); os.flush(); } } catch (Exception e) { System.out.println("Error " + e.getMessage()); } }
From source file:smile.ImprimirReporte.java
public void ImprimirReporte() throws DocumentException, FileNotFoundException, BadElementException, IOException { Document document = new Document(PageSize.LETTER.rotate()); Image imagen = Image.getInstance("src/Imagen/dental.jpg"); imagen.setAbsolutePosition(250f, 250f); imagen.setAlignment(Element.ALIGN_CENTER); String p1 = "Paciente: " + getNombre(); String p2 = "Edad: " + getEdad() + "Sexo: " + getSexo(); String p3 = "Fecha: " + getFecha(); String p4 = "Motivo Consulta: " + getMotivo(); String p5 = "Descrpcion: " + getDescripcion(); PdfWriter.getInstance(document, new FileOutputStream("recibo.pdf")); document.open();// w w w . ja va 2s . c o m document.add(imagen); document.add(new Paragraph(p1)); document.add(new Paragraph(p2)); document.add(new Paragraph(p3)); document.add(new Paragraph(p4)); document.add(new Paragraph(p5)); PdfPTable table = new PdfPTable(3); table.addCell("Clase Esqueletal"); table.addCell("Norma"); table.addCell("Inicial"); table.addCell("Convexidad Facial"); table.addCell("+2+-2mm"); table.addCell(""); table.addCell("Maxilar Inferior"); table.addCell(""); table.addCell(""); table.addCell("Eje Facial"); table.addCell("90+-3"); table.addCell(""); table.addCell("Prof. Facial"); table.addCell("87+-3"); table.addCell(""); table.addCell("Ang.Plano mandibular"); table.addCell("26+-4"); table.addCell(""); table.addCell("Altura Facial Inferior"); table.addCell("47+-4"); table.addCell(""); table.addCell("Arco Mandibular"); table.addCell("26+-4"); table.addCell(""); table.addCell("Maxilar Superior"); table.addCell(""); table.addCell(""); table.addCell("Profundidad Maxilar"); table.addCell("90+-3"); table.addCell(""); table.addCell("Dientes"); table.addCell(""); table.addCell(""); table.addCell("A-Pg"); table.addCell("+1+-2mm"); table.addCell(""); table.addCell("Plano Oclusal"); table.addCell("+1+-1mm"); table.addCell(""); table.addCell("Plano Mandibular"); table.addCell("90+-5"); table.addCell(""); table.addCell("Plano Bana"); table.addCell("E.Fac -5"); table.addCell(""); table.addCell("Estetica"); table.addCell(""); table.addCell(""); table.addCell("Exposicion del l"); table.addCell("+2.5 a 3mm"); table.addCell(""); table.addCell("Lab. Inf. Plano E"); table.addCell("-2+-2mm"); table.addCell(""); table.addCell("Angulo masofacial inferior"); table.addCell("85+-5"); table.addCell(""); document.add(table); document.close(); System.out.println("Entre"); }
From source file:Software_Jframes.chart.java
void print_pdf_report(JTable jTable5) { Access ac = new Access(); try {// ww w .ja v a 2s .co m String filename = ac.chooseFile(); com.itextpdf.text.Document document = new com.itextpdf.text.Document(); PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf")); document.open(); document.add(new Paragraph("")); Image image1 = Image.getInstance("src/images/ROPA_Logo_without_claim.jpg"); document.add(new Paragraph("")); image1.scaleAbsolute(80, 50); image1.setAbsolutePosition(50, 800); document.add(image1); PdfPTable table = new PdfPTable(3); // 3 columns. DefaultTableModel dtm = (DefaultTableModel) jTable5.getModel(); Vector v = new Vector(); int count_row = dtm.getRowCount(); int count_col = dtm.getColumnCount(); for (int i = 0; i < count_row; i++) { for (int j = 0; j < count_col; j++) { table.addCell(new PdfPCell(new Paragraph(dtm.getValueAt(i, j) + ""))); } } table.setWidthPercentage(100); float[] columnWidths = { 2f, 1f, 1f }; table.setWidths(columnWidths); document.add(table); document.close(); JOptionPane.showMessageDialog(null, "Successfully Created."); } catch (Exception e) { e.printStackTrace(); } }
From source file:Tables.PrinterClass.java
public void footer(Document doc) throws DocumentException { Paragraph paragraph = new Paragraph("@" + this.companyName); doc.add(paragraph);//from ww w . j ava 2 s. c om dNow = new Date(); String prodDate; prodDate = "Created on the " + dateOnly.format(dNow) + " at " + timeOnly.format(dNow); ////////////////// PdfPTable timeOfProduction = new PdfPTable(1); PdfPCell cell = new PdfPCell(new Phrase(prodDate.trim(), smallFooter)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setColspan(3); cell.setBorder(0); if (prodDate.trim().equalsIgnoreCase("")) { cell.setMinimumHeight(10f); } timeOfProduction.addCell(cell); doc.add(timeOfProduction); try { Image img = Image.getInstance(this.companyLogo); img.scaleAbsolute(20f, 20f); img.setAbsolutePosition((PageSize.A4.getWidth() - img.getScaledWidth()), (PageSize.A4.getHeight() - img.getScaledHeight())); //place the image at the bottom right position img.setAlt("Unity Systems"); } catch (Exception ex) { } }
From source file:tn.esprit.twin1.brogrammers.eventify.Eventify.util.TicketGenerator.java
public static void GenerateTicket(Ticket ticket) { Document document = new Document(); try {/* w w w . java 2 s .com*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE)); Rectangle pagesize = new Rectangle(700, 300); document.open(); Paragraph emptyline = new Paragraph(); emptyline.add(new Paragraph(" ")); document.setPageSize(pagesize); document.newPage(); //PIC PdfContentByte canvas = writer.getDirectContentUnder(); Image image = Image.getInstance(IMAGE); //image.scaleAbsolute(pagesize.rotate()); image.setAbsolutePosition(0, 0); canvas.addImage(image); //PIC document.addTitle("Your Access To" + ticket.getEvent().getTitle()); document.addSubject(ticket.getEvent().getTheme()); document.addKeywords(ticket.getEvent().getTitle() + "Ticket"); document.addAuthor("Mohamed Firas Ouertani"); document.addCreator("Mohamed Firas Ouertani"); Paragraph prefacetitle = new Paragraph(); prefacetitle.add(new Paragraph("Your Ticket For " + ticket.getEvent().getTitle(), bigFont)); document.add(prefacetitle); document.add(emptyline); Paragraph prefacetime = new Paragraph(); prefacetime.add(new Paragraph(ticket.getEvent().getStartTime().toString(), greyFont)); document.add(prefacetime); document.add(emptyline); document.add(emptyline); Paragraph prefacetype = new Paragraph(); prefacetype.add(new Paragraph("You Reserved For: " + ticket.getTypeTicket(), catFont)); document.add(prefacetype); //QR BarcodeQRCode qrcode = new BarcodeQRCode( "REF:#" + ticket.getEvent().getId() + "" + ticket.getEvent().getTitle().trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(520, 70); qrcodeImage.scalePercent(400); document.add(qrcodeImage); //QR //Bar PdfContentByte cb = writer.getDirectContent(); Barcode128 code128 = new Barcode128(); BarcodeEAN codeEAN = new BarcodeEAN(); codeEAN.setCode("REF:#" + ticket.getEvent().getId() + "" + ticket.getEvent().getTitle().trim()); codeEAN.setCodeType(BarcodeEAN.EAN13); Image codeEANImage = code128.createImageWithBarcode(cb, null, null); codeEANImage.setAbsolutePosition(10, 10); codeEANImage.scalePercent(125); document.add(codeEANImage); //Bar document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:tn.esprit.twin1.brogrammers.eventify.Eventify.util.TicketGenerator.java
public static void qr(Document document) { BarcodeQRCode qrcode = new BarcodeQRCode("fdf".trim(), 30, 30, null); Image qrcodeImage = null; try {// www . jav a 2 s . com qrcodeImage = qrcode.getImage(); } catch (BadElementException e) { // TODO Auto-generated catch block e.printStackTrace(); } qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(800); try { document.add(qrcodeImage); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:util.ImageExample.java
public ImageExample(Calendar date, int settings, ArrayList<String> courses, String time, String eventAddress, int totalPrice, String comments, boolean kunde) throws Exception { this.date = date; this.settings = settings; this.courses = courses; this.time = time; this.eventAddress = eventAddress; this.totalPrice = totalPrice; this.comments = comments; this.fileName = ""; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.getAllFonts();//from ww w .j ava 2s . c om FontFactory.register("C:/Windows/Fonts/ARLRDBD.TTF", "Arial Rounded"); Font font = FontFactory.getFont("Arial Rounded", 22, Font.NORMAL, new BaseColor(51, 102, 102)); Document document = new Document(); System.out.println("Pdf creation startet"); try { if (kunde) { fileName = "grill" + new SimpleDateFormat("dd. MMMMM yyyy hhmm").format(date.getTime()) + ".pdf"; } else { fileName = "grill" + new SimpleDateFormat("dd. MMMMM yyyy hhmm").format(date.getTime()) + "Prisliste.pdf"; } FileOutputStream file = new FileOutputStream(new File("C:/Users/Mark/Desktop", fileName)); PdfWriter writer = PdfWriter.getInstance(document, file); document.open(); Image img = Image.getInstance("src/pictures/cirkles.png"); img.scaleToFit(277, 277); img.setAbsolutePosition(40, PageSize.A4.getHeight() - img.getHeight()); document.add(img); Chunk chunk = new Chunk("Grillmester 'Frankie'", font); chunk.setCharacterSpacing(3); Paragraph header = new Paragraph(chunk); header.setAlignment(Element.ALIGN_RIGHT); header.setSpacingBefore(15); document.add(header); Paragraph title = new Paragraph( "Tilbud angende d. " + new SimpleDateFormat("dd. MMMMM yyyy").format(date.getTime()) + ".", new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD)); title.setAlignment(Element.ALIGN_LEFT); title.setIndentationLeft(235); title.setSpacingBefore(100); title.setLeading(17); document.add(title); Paragraph subtitle = new Paragraph("(Arrangement til " + settings + " personer).", new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.ITALIC)); subtitle.setAlignment(Element.ALIGN_LEFT); subtitle.setIndentationLeft(235); subtitle.setLeading(17); document.add(subtitle); Paragraph body = new Paragraph("\n\nDer er aftalt:\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 18)); body.setAlignment(Element.ALIGN_LEFT); body.setIndentationLeft(235); body.setLeading(17); for (String course : courses) { body.add(course + "\n\n"); } body.add("\nServeres klokken " + time + " i " + eventAddress + "."); document.add(body); Paragraph ending = new Paragraph("\n\n\nPris: " + totalPrice + ",-kr.", new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)); ending.setAlignment(Element.ALIGN_LEFT); ending.setIndentationLeft(235); ending.setLeading(17); document.add(ending); if (!comments.equals("null")) { if (!comments.equals("")) { Paragraph comment = new Paragraph("\n\nKommentarer\n" + comments, new Font(Font.FontFamily.TIMES_ROMAN, 18)); comment.setAlignment(Element.ALIGN_LEFT); comment.setIndentationLeft(235); comment.setLeading(17); document.add(comment); } } Image footerImg = Image.getInstance("src/pictures/grillmester.png"); footerImg.scaleToFit(210, 210); footerImg.setAbsolutePosition(40, 40); document.add(footerImg); Image img2 = Image.getInstance("src/pictures/Contact.png"); img2.scaleToFit(250, 250); img2.setAbsolutePosition(20, PageSize.A4.getHeight() - img.getHeight() - 250); document.add(img2); document.close(); System.out.println("Pdf finish"); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getLocalizedMessage()); } }
From source file:utility.pdfRead.java
public void readPdfFromUrl(String url) throws MalformedURLException, Exception { URL urlnya = new URL(url); String namafile;//w w w .ja v a 2 s . c o m Date d = new Date(); // kode String dataAkun = "Surat Keterangan Domisili Usaha dari Kelurahan dan Kecamatan yang masih berlaku atau Fotocopy dilegalisir Kecamatan"; pdfRead myEncryptor = new pdfRead(); String dataAkunEnkripsi = myEncryptor.encrypt(dataAkun); String dataAkunDekripsi = myEncryptor.decrypt( "AYxJhAMLk4fftR5XcqYDoUO4GaMY7sNX19k5SRxWWedGj6RB3tSUUmtdx1KHYf19EE1rLonm/3XikRnNoG/Q0rXkbiXO3QXHnmn2douw6SSwrirgYGoHmR3U4wmGUCxXqAERQFd5rdCZcK0CII7sPsb2uiTYqA97"); System.out.println("Text Asli: " + dataAkun); System.out.println("Text Terenkripsi :" + dataAkunEnkripsi); System.out.println("Text Terdekripsi :" + dataAkunDekripsi); // kode byte[] ba1 = new byte[5 * 1024]; // byte[] ba1 = new byte[10*1024]; int baLength; InputStream is1 = null; ByteArrayOutputStream bios = new ByteArrayOutputStream(); ByteArrayOutputStream biosPlusWatermark = new ByteArrayOutputStream(); ByteArrayOutputStream biosPlusWatermarkQr = new ByteArrayOutputStream(); AMedia amedia = null; try { // report.setSrc(url); // ssl disable // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URLConnection urlConn = urlnya.openConnection(); try { // Read the PDF from the URL and save to a local file is1 = urlnya.openStream(); while ((baLength = is1.read(ba1)) != -1) { bios.write(ba1, 0, baLength); } } catch (Exception e) { } finally { is1.close(); bios.close(); } // add watermark try { PdfReader reader = new PdfReader(bios.toByteArray()); int n = reader.getNumberOfPages(); // create a stamper that will copy the document to a new file try { // Read the PDF from the URL and save to a local file is1 = urlnya.openStream(); while ((baLength = is1.read(ba1)) != -1) { biosPlusWatermark.write(ba1, 0, baLength); } } catch (Exception e) { } finally { is1.close(); biosPlusWatermark.close(); } PdfStamper stamp = new PdfStamper(reader, biosPlusWatermark, '\0', true); int i = 0; PdfContentByte under; Image img = Image.getInstance("img/watermark.png"); img.setTransparency(new int[] { 0x00, 0x10 }); img.setAbsolutePosition(0, 0); while (i < n) { i++; under = stamp.getOverContent(i); under.addImage(img); } stamp.close(); } catch (Exception e) { System.out.println("err watermark:" + e); amedia = new AMedia("Dokumen", "pdf", "application/pdf", bios.toByteArray()); } // add QRcode try { PdfReader reader = new PdfReader(biosPlusWatermark.toByteArray()); int n = reader.getNumberOfPages(); BarcodeQRCode qrcode = new BarcodeQRCode(dataAkunEnkripsi, 50, 50, null); Image image = qrcode.getImage(); Image mask = qrcode.getImage(); mask.makeMask(); image.setImageMask(mask); // create a stamper that will copy the document to a new file try { // Read the PDF from the URL and save to a local file is1 = urlnya.openStream(); while ((baLength = is1.read(ba1)) != -1) { biosPlusWatermarkQr.write(ba1, 0, baLength); } } catch (Exception e) { } finally { is1.close(); biosPlusWatermarkQr.close(); } PdfStamper stamp = new PdfStamper(reader, biosPlusWatermarkQr, '\0', false); int i = 0; PdfContentByte under; Image img = Image.getInstance(image); img.setTransparency(new int[] { 0x00, 0x10 }); img.setAbsolutePosition(0, 0); while (i < n) { i++; under = stamp.getOverContent(i); under.addImage(img); } stamp.close(); amedia = new AMedia("Dokumen", "pdf", "application/pdf", biosPlusWatermarkQr.toByteArray()); } catch (Exception e) { System.out.println("err qrcode:" + e); amedia = new AMedia("Dokumen", "pdf", "application/pdf", bios.toByteArray()); } report.setContent(amedia); } catch (Exception e) { System.out.println("url tidak dapat diakses"); } }