List of usage examples for com.itextpdf.text Image getInstance
public static Image getInstance(final Image image)
From source file:org.sistemafinanciero.rest.impl.SocioRESTService.java
License:Apache License
@Override public Response getCartillaInformacion(BigInteger id) { OutputStream file;//from www . j av a 2s .c o m // CuentaBancariaView cuentaBancaria = // cuentaBancariaServiceNT.findById(id); SocioView socio = socioServiceNT.findById(id); CuentaAporte cuentaAporte = socioServiceNT.getCuentaAporte(id); Moneda moneda = cuentaAporte.getMoneda(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy"); BaseColor baseColor = BaseColor.LIGHT_GRAY; Font font = FontFactory.getFont("Arial", 10f); Font fontBold = FontFactory.getFont("Arial", 10f, Font.BOLD); try { file = new FileOutputStream(new File(cartillaURL + "\\" + id + ".pdf")); Document document = new Document(PageSize.A4);// *4 PdfWriter writer = PdfWriter.getInstance(document, file); document.open(); /******************* TITULO ******************/ //Image img = Image.getInstance("/images/logo_coop_contrato.png"); Image img = Image.getInstance("//usr//share//jboss//archivos//logoCartilla//logo_coop_contrato.png"); img.setAlignment(Image.LEFT | Image.UNDERLYING); document.add(img); Paragraph parrafoPrincipal = new Paragraph(); parrafoPrincipal.setSpacingAfter(40); parrafoPrincipal.setSpacingBefore(50); parrafoPrincipal.setAlignment(Element.ALIGN_CENTER); parrafoPrincipal.setIndentationLeft(100); parrafoPrincipal.setIndentationRight(50); Chunk titulo = new Chunk("CARTILLA DE INFORMACIN\n"); Font fuenteTitulo = new Font(); fuenteTitulo.setSize(18); fuenteTitulo.setFamily("Arial"); fuenteTitulo.setStyle(Font.BOLD | Font.UNDERLINE); titulo.setFont(fuenteTitulo); parrafoPrincipal.add(titulo); Chunk subTitulo = new Chunk("APERTURA CUENTA DE APORTE\n"); Font fuenteSubtitulo = new Font(); fuenteSubtitulo.setSize(13); fuenteSubtitulo.setFamily("Arial"); fuenteSubtitulo.setStyle(Font.BOLD | Font.UNDERLINE); subTitulo.setFont(fuenteSubtitulo); parrafoPrincipal.add(subTitulo); document.add(parrafoPrincipal); /******************* DATOS BASICOS DEL SOCIO **********************/ PdfPTable table1 = new PdfPTable(4); table1.setWidthPercentage(100); PdfPCell cabecera1 = new PdfPCell(new Paragraph("DATOS BASICOS DEL SOCIO", fontBold)); cabecera1.setColspan(4); cabecera1.setBackgroundColor(baseColor); PdfPCell cellCodigoSocio = new PdfPCell(new Paragraph("Codigo Socio:", fontBold)); cellCodigoSocio.setColspan(1); cellCodigoSocio.setBorder(Rectangle.NO_BORDER); PdfPCell cellCodigoSocioValue = new PdfPCell(new Paragraph(socio.getIdsocio().toString(), font)); cellCodigoSocioValue.setColspan(3); cellCodigoSocioValue.setBorder(Rectangle.NO_BORDER); PdfPCell cellApellidosNombres = new PdfPCell(new Paragraph( socio.getTipoPersona().equals(TipoPersona.NATURAL) ? "Apellidos y Nombres:" : "Razn Social:", fontBold)); cellApellidosNombres.setColspan(1); cellApellidosNombres.setBorder(Rectangle.NO_BORDER); PdfPCell cellApellidosNombresValue = new PdfPCell(new Paragraph(socio.getSocio(), font)); cellApellidosNombresValue.setColspan(3); cellApellidosNombresValue.setBorder(Rectangle.NO_BORDER); table1.addCell(cabecera1); table1.addCell(cellCodigoSocio); table1.addCell(cellCodigoSocioValue); table1.addCell(cellApellidosNombres); table1.addCell(cellApellidosNombresValue); PdfPCell cellDNI = new PdfPCell(new Paragraph(socio.getTipoDocumento() + ":", fontBold)); cellDNI.setColspan(1); cellDNI.setBorder(Rectangle.NO_BORDER); PdfPCell cellDNIValue = new PdfPCell(new Paragraph(socio.getNumeroDocumento(), font)); cellDNIValue.setColspan(1); cellDNIValue.setBorder(Rectangle.NO_BORDER); PdfPCell cellFechaNaciemiento = new PdfPCell( new Paragraph(socio.getTipoPersona().equals(TipoPersona.NATURAL) ? "Fecha de Nacimiento:" : "Fecha de Constitucin", fontBold)); cellFechaNaciemiento.setColspan(1); cellFechaNaciemiento.setBorder(Rectangle.NO_BORDER); PdfPCell cellFechaNacimientoValue = new PdfPCell( new Paragraph(DATE_FORMAT.format(socio.getFechaNacimiento()), font)); cellFechaNacimientoValue.setColspan(1); cellFechaNacimientoValue.setBorder(Rectangle.NO_BORDER); table1.addCell(cellDNI); table1.addCell(cellDNIValue); table1.addCell(cellFechaNaciemiento); table1.addCell(cellFechaNacimientoValue); document.add(table1); document.add(new Paragraph("\n")); /******************* PRODUCTOS Y SERVICIOS **********************/ PdfPTable table3 = new PdfPTable(4); table3.setWidthPercentage(100); PdfPCell cabecera3 = new PdfPCell(new Paragraph("PRODUCTOS Y SERVICIOS", fontBold)); cabecera3.setColspan(4); cabecera3.setBackgroundColor(baseColor); table3.addCell(cabecera3); PdfPCell cellProductoCab = new PdfPCell(new Paragraph("Producto", fontBold)); PdfPCell cellMonedaCab = new PdfPCell(new Paragraph("Moneda", fontBold)); PdfPCell cellNumeroCuentaCab = new PdfPCell(new Paragraph("Nmero Cuenta", fontBold)); PdfPCell cellFechaAperturaCab = new PdfPCell(new Paragraph("Fecha Apertura", fontBold)); cellProductoCab.setBorder(Rectangle.NO_BORDER); cellMonedaCab.setBorder(Rectangle.NO_BORDER); cellNumeroCuentaCab.setBorder(Rectangle.NO_BORDER); cellFechaAperturaCab.setBorder(Rectangle.NO_BORDER); table3.addCell(cellProductoCab); table3.addCell(cellMonedaCab); table3.addCell(cellNumeroCuentaCab); table3.addCell(cellFechaAperturaCab); PdfPCell cellProducto = new PdfPCell(new Paragraph("CUENTA DE APORTE", font)); PdfPCell cellMoneda = new PdfPCell(new Paragraph(moneda.getDenominacion(), font)); PdfPCell cellNumeroCuenta = new PdfPCell(new Paragraph(cuentaAporte.getNumeroCuenta(), font)); PdfPCell cellFechaApertura = new PdfPCell( new Paragraph(DATE_FORMAT.format(socio.getFechaAsociado()), font)); cellProducto.setBorder(Rectangle.NO_BORDER); cellMoneda.setBorder(Rectangle.NO_BORDER); cellNumeroCuenta.setBorder(Rectangle.NO_BORDER); cellFechaApertura.setBorder(Rectangle.NO_BORDER); table3.addCell(cellProducto); table3.addCell(cellMoneda); table3.addCell(cellNumeroCuenta); table3.addCell(cellFechaApertura); document.add(table3); document.add(new Paragraph("\n")); /******************* DECLARACIONES Y FIRMAS **********************/ PdfPTable table4 = new PdfPTable(1); table4.setWidthPercentage(100); PdfPCell cabecera4 = new PdfPCell(new Paragraph("DECLARACIONES Y FIRMAS", fontBold)); cabecera4.setBackgroundColor(baseColor); table4.addCell(cabecera4); Paragraph parrafoDeclaraciones = new Paragraph(); Chunk parrafo1 = new Chunk( "Los aportes individuales sern pagados por los Asociados en forma peridica de conformidad con lo establecido en el Estatuto y el Reglamento de Aportes Sociales de la Cooperativa. El aporte social ordinario de cada Asociado ser mnimo de S/. 10.00 Nuevos Soles si es mayor de edad y S/. 5.00 Nuevos Soles si es menor de edad.\n\n", font); parrafo1.setLineHeight(13); parrafoDeclaraciones.add(parrafo1); Chunk parrafoDeclaracionesFinalesCab = new Chunk("DECLARACIN FINAL DEL CLIENTE: ", fontBold); Paragraph parrafoDeclaracionesFinalesValue = new Paragraph(); Chunk parrafo2 = new Chunk( "Declaro haber leido previamente las condiciones establecidas en el Contrato de Depsito y la Cartilla de Informacin, asi como haber sido instruido acerca de los alcances y significados de los trminos y condiciones establecidos en dicho documento habiendo sido absueltas y aclaradas a mi satisfaccin todas las consultas efectuadas y/o dudas, suscribe el presente documento en duplicado y con pleno y exacto conocimiento de los mismos.\n", font); parrafo2.setLineHeight(13); parrafoDeclaracionesFinalesValue.add(parrafo2); parrafoDeclaraciones.add(parrafoDeclaracionesFinalesCab); parrafoDeclaraciones.add(parrafoDeclaracionesFinalesValue); PdfPCell declaraciones = new PdfPCell(parrafoDeclaraciones); declaraciones.setBorder(Rectangle.NO_BORDER); declaraciones.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); table4.addCell(declaraciones); document.add(table4); // firmas Chunk firmaP01 = new Chunk(".........................................."); Chunk firmaP02 = new Chunk("..........................................\n"); Chunk firma01 = new Chunk("Caja Ventura"); Chunk firma02 = new Chunk("El Socio "); Paragraph firmas = new Paragraph("\n\n\n\n\n\n"); firmas.setAlignment(Element.ALIGN_CENTER); firmas.add(firmaP01); firmas.add(Chunk.SPACETABBING); firmas.add(Chunk.SPACETABBING); firmas.add(firmaP02); firmas.add(firma01); firmas.add(Chunk.SPACETABBING); firmas.add(Chunk.SPACETABBING); firmas.add(Chunk.SPACETABBING); firmas.add(Chunk.SPACETABBING); firmas.add(firma02); document.add(firmas); document.close(); file.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PdfReader reader; try { reader = new PdfReader(cartillaURL + "\\" + id + ".pdf"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper pdfStamper = new PdfStamper(reader, out); AcroFields acroFields = pdfStamper.getAcroFields(); acroFields.setField("field_title", "test"); pdfStamper.close(); reader.close(); return Response.ok(out.toByteArray()).type("application/pdf").build(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Jsend.getErrorJSend("No encontrado")) .build(); }
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
private static void fillTemplateUserDetails(AcroFields pdfForm, User user, String basePath) throws IOException, DocumentException { try {/* www.j av a 2s . c om*/ pdfForm.setField("user_name", user.name); pdfForm.setField("user_company", user.company_name); /* * User configurable data TODO This should be an array of key value pairs * As interim use a hard coded class to hold the data */ String settings = user.settings; Type type = new TypeToken<UserSettings>() { }.getType(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); UserSettings us = gson.fromJson(settings, type); if (us != null) { pdfForm.setField("user_title", us.title); pdfForm.setField("user_license", us.license); PushbuttonField ad = pdfForm.getNewPushbuttonFromField("user_signature"); if (ad != null) { ad.setLayout(PushbuttonField.LAYOUT_ICON_ONLY); ad.setProportionalIcon(true); String filename = null; try { filename = basePath + "/media/users/" + user.id + "/sig/" + user.signature; ad.setImage(Image.getInstance(filename)); } catch (Exception e) { log.info("Error: Failed to add signature " + filename + " to pdf"); } pdfForm.replacePushbuttonField("user_signature", ad.getField()); } else { //log.info("Picture field: user_signature not found"); } } } catch (Exception e) { log.log(Level.SEVERE, "Error filling template", e); } }
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
private void updateValueCell(Parser parser, String remoteUser, PdfPCell valueCell, DisplayItem di, boolean generateBlank, String basePath, String serverRoot, GlobalVariables gv, int oId) throws Exception { // Questions that append their values to this question ArrayList<String> deps = gv.addToList.get(di.fIdx + "_" + di.rec_number + "_" + di.name); if (di.type.startsWith("select")) { processSelect(parser, remoteUser, valueCell, di, generateBlank, gv, oId); } else if (di.type.equals("image")) { if (di.value != null && !di.value.trim().equals("") && !di.value.trim().equals("Unknown")) { if (di.isHyperlink) { Anchor anchor = new Anchor(serverRoot + di.value); anchor.setReference(serverRoot + di.value); valueCell.addElement(getPara("", di, gv, deps, anchor)); } else { try { Image img = Image.getInstance(basePath + "/" + di.value); valueCell.addElement(img); } catch (Exception e) { log.info("Error: image " + basePath + "/" + di.value + " not added: " + e.getMessage()); log.log(Level.SEVERE, "Adding image to pdf", e); }/* w ww. j a v a2 s . c om*/ } } else { // TODO add empty image } } else if (di.type.equals("video") || di.type.equals("audio")) { if (di.value != null && !di.value.trim().equals("") && !di.value.trim().equals("Unknown")) { Anchor anchor = new Anchor(serverRoot + di.value); anchor.setReference(serverRoot + di.value); valueCell.addElement(getPara("", di, gv, deps, anchor)); } else { // TODO add empty image } } else if (di.type.equals("geopoint") || di.type.equals("geoshape") || di.type.equals("geotrace") || di.type.startsWith("geopolygon_") || di.type.startsWith("geolinestring_")) { Image img = PdfUtilities.getMapImage(sd, di.map, di.value, di.location, di.zoom, gv.mapbox_key, survey.id, user, di.markerColor); if (img != null) { valueCell.addElement(img); } else { valueCell.addElement(getPara(" ", di, gv, deps, null)); } } else if (di.isBarcode) { BarcodeQRCode qrcode = new BarcodeQRCode(di.value.trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(200); valueCell.addElement((qrcodeImage)); } else { // Todo process other question types String value = null; if (di.value == null || di.value.trim().length() == 0) { value = " "; // Need a space to show a blank row } else { if (di.value != null && di.value.length() > 0) { if (GeneralUtilityMethods.isRtlLanguage(di.value)) { valueCell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL); } } if (di.type.equals("dateTime") || di.type.equals("timestamp")) { // Set date time to local time DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = df.parse(di.value); df.setTimeZone(TimeZone.getTimeZone(tz)); value = df.format(date); log.info("Convert date to local time: " + di.name + " : " + di.value + " : " + " : " + value + " : " + di.type + " : " + tz); } else { value = di.value; } } valueCell.addElement(getPara(value, di, gv, deps, null)); } }
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
private void fillNonTemplateUserDetails(Document document, User user, String basePath) throws IOException, DocumentException { String settings = user.settings; Type type = new TypeToken<UserSettings>() { }.getType();//w ww.j a va 2 s . c o m Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); UserSettings us = gson.fromJson(settings, type); float indent = (float) 20.0; addValue(document, "Completed by:", (float) 0.0); if (user.signature != null && user.signature.trim().length() > 0) { String fileName = null; try { //fileName = basePath + user.signature; fileName = basePath + "/media/users/" + user.id + "/sig/" + user.signature; Image img = Image.getInstance(fileName); img.scaleToFit(200, 50); img.setIndentationLeft(indent); document.add(img); } catch (Exception e) { log.info( "Error: Failed to add signature (non template) " + fileName + " to pdf: " + e.getMessage()); } } addValue(document, user.name, indent); addValue(document, user.company_name, indent); if (us != null) { addValue(document, us.title, indent); addValue(document, us.license, indent); } }
From source file:org.smap.sdal.managers.PDFTableManager.java
License:Open Source License
private PdfPCell addDisplayItem(Parser parser, KeyValue kv, String basePath, boolean barcode, String type) throws BadElementException, MalformedURLException, IOException { PdfPCell valueCell = new PdfPCell(); valueCell.setBorderColor(BaseColor.LIGHT_GRAY); // Set the content of the value cell try {/* w w w . ja v a 2s. com*/ if (type != null && type.equals("image")) { Image img = Image.getInstance(kv.v); valueCell.addElement(img); } else if (barcode && kv.v.trim().length() > 0) { BarcodeQRCode qrcode = new BarcodeQRCode(kv.v.trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(200); valueCell.addElement((qrcodeImage)); } else { valueCell.addElement(getPara(kv.v)); } } catch (Exception e) { log.info("Error updating value cell, continuing: " + basePath + " : " + kv.v); log.log(Level.SEVERE, "Exception", e); } return valueCell; }
From source file:org.smap.sdal.managers.PDFTableManager.java
License:Open Source License
private void fillNonTemplateUserDetails(Document document, User user, String basePath) throws IOException, DocumentException { String settings = user.settings; Type type = new TypeToken<UserSettings>() { }.getType();/*www . jav a 2 s . c om*/ Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); UserSettings us = gson.fromJson(settings, type); float indent = (float) 20.0; addValue(document, "Completed by:", (float) 0.0); if (user.signature != null && user.signature.trim().length() > 0) { String fileName = null; try { fileName = basePath + File.separator + user.signature; Image img = Image.getInstance(fileName); img.scaleToFit(200, 50); img.setIndentationLeft(indent); document.add(img); } catch (Exception e) { log.info("Error: Failed to add image " + fileName + " to pdf"); } } addValue(document, user.name, indent); addValue(document, user.company_name, indent); if (us != null) { addValue(document, us.title, indent); addValue(document, us.license, indent); } }
From source file:org.yale.cs.graphics.gephi.imagepreview.ImageItem.java
License:Open Source License
/** * Prepares this ImageItem to be rendered by the PDF target. Loading * from the cache, if available. If the method is forced to load a image * from the hard drive, it stores it in the cache. * * @param location_name The name of the folder to load images from. * @return A iText PDF Image corresponding to this item. *///from w w w . ja va2 s . co m public com.itextpdf.text.Image renderPDF(File location_name) { com.itextpdf.text.Image image = (com.itextpdf.text.Image) data.get(PDF_DATA); if (image == null) { if (source instanceof String) { File full_file = new File(location_name, (String) source); try { image = Image.getInstance(full_file.getCanonicalPath()); } catch (BadElementException ex) { logger.log(Level.SEVERE, "Unable to load image: " + full_file, ex); } catch (MalformedURLException ex) { logger.log(Level.SEVERE, "Unable to load image: " + full_file, ex); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to load image: " + full_file, ex); } } //If we can't render the image, fallback to the defult render if (image == null) { logger.log(Level.WARNING, "Unable to load image: {0}", source); return null; } data.put(PDF_DATA, image); } return image; }
From source file:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java
License:Apache License
public boolean exportAlert(java.util.List<java.util.List<Alert>> alerts, String fileName, ExtensionAlertReportExport extensionExport) { Document document = new Document(PageSize.A4); try {/* w w w .j a v a 2 s . c o m*/ // Document documentAdd = null; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); boolean attach = false; // add attach document is exist if (!extensionExport.getParams().getDocumentAttach().isEmpty()) { PdfReader reader = new PdfReader(extensionExport.getParams().getDocumentAttach()); int n = reader.getNumberOfPages(); PdfImportedPage page; // Go through all pages for (int i = 1; i <= n; i++) { page = writer.getImportedPage(reader, i); Image instance = Image.getInstance(page); instance.scalePercent(95f); document.add(instance); } attach = true; } if (!attach) { addMetaData(document, extensionExport); addTitlePage(document, extensionExport); } for (int i = 0; i < alerts.size(); i++) { java.util.List<Alert> alertAux = alerts.get(i); addContent(document, alertAux, extensionExport); } document.close(); return true; } catch (Exception e) { logger.error(e.getMessage(), e); document.close(); return false; } }
From source file:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java
License:Apache License
/** * Add image a Paragraph//w w w .j av a 2 s .c o m * * @param paragraph * @param image * @param path * @throws BadElementException */ private static void addImage(Paragraph paragraph, String imagePath, float scalePercent) throws BadElementException { Image image1; try { if (!imagePath.isEmpty()) { image1 = Image.getInstance(imagePath); if (scalePercent != 0) image1.scalePercent(40f); image1.setAlignment(Image.ALIGN_CENTER); paragraph.add(image1); } } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:Output.QuotePDf.java
private Image headerImage() throws BadElementException, IOException { Image image = Image.getInstance(getClass().getClassLoader().getResource("resources/header.jpg")); image.setAlignment(Element.ALIGN_CENTER); image.scalePercent(35f);/*www. j a va2 s . c o m*/ return image; }