List of usage examples for com.lowagie.text Image getInstance
public static Image getInstance(Image image)
From source file:org.viafirma.util.QRCodeUtil.java
License:Apache License
/** * @param texto/*from w w w . j a v a2s .c o m*/ * Texto a colocar * @param textoQR * Imagen QR a colocar * @param codFirma * Cdigo de Firma a generar. * @param url Url del servicio de verificacin desde donde se puede descargar el documento. * @param document * Documeto destino * @param pageSize * Tamao de la pgina * @return * @throws BadElementException * @throws MalformedURLException * @throws IOException * @throws DocumentException * @throws ExcepcionErrorInterno */ private static float addContent(String texto, String url, String textoQR, String codFirma, Document document, Rectangle pageSize, boolean completo, boolean isSellado) throws BadElementException, MalformedURLException, IOException, DocumentException, ExcepcionErrorInterno { Image imagenCabezera = null; float widthCabecera = 0; float heightCabecera = 0; if (!isSellado) { // Recuperamos la imagen de cabecera imagenCabezera = Image.getInstance(QRCodeUtil.class.getResource(IMAGE_CABECERA)); // Colocamos la imagen en la zona superior de la pgina imagenCabezera.setAbsolutePosition(0, pageSize.getHeight() - imagenCabezera.getHeight()); heightCabecera = imagenCabezera.getHeight(); widthCabecera = imagenCabezera.getWidth(); } // Recuperamos el pie de firma Image imagenQR = Image.getInstance(QRCodeUtil.getInstance().generate(texto, url, textoQR, codFirma)); float rescalado = pageSize.getWidth() / (widthCabecera + document.leftMargin() + document.rightMargin()); float sizeCabecera = 0; if (rescalado < 1f && !isSellado) { // Requiere rescalado, la imagen es mayor que la pgina. imagenCabezera.scalePercent(rescalado * 100); sizeCabecera = rescalado * imagenCabezera.getHeight(); } float sizeCabecerayPie = HEIGHT_QR_CODE_PDF + sizeCabecera + document.bottomMargin() + document.topMargin() + SPACE_SEPARACION; // float escaleQR = HEIGHT_QR_CODE_PDF / (imagenQR.getHeight() + 5); float escaleQR = (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) / (imagenQR.getWidth() + 6); // imagen.setSpacingAfter(120); if (!isSellado) { document.add(imagenCabezera); } // Aadimos una caja de texto si estamos mostrando el contenido del // fichero firmado. if (completo) { // Aadimos el espacio ocupado por la imagen Paragraph p = new Paragraph(""); p.setSpacingAfter(heightCabecera * rescalado); document.add(p); // Aadimos una tabla con borde donde colocar el documento. PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); table.getDefaultCell().setBorderWidth(10); PdfPCell celda = new PdfPCell(); celda.setFixedHeight(pageSize.getHeight() - sizeCabecerayPie); table.addCell(celda); table.setSpacingAfter(SPACE_SEPARACION); document.add(table); } if (completo) { // La imagen la colocamos justo debajo imagenQR.setAbsolutePosition(document.leftMargin(), escaleQR * HEIGHT_QR_CODE_PDF - SPACE_SEPARACION * 2); } else { imagenQR.setAbsolutePosition(document.leftMargin(), pageSize.getHeight() - sizeCabecerayPie); } imagenQR.scalePercent(escaleQR * 100); document.add(imagenQR); return sizeCabecerayPie; }
From source file:org.webguitoolkit.ui.util.export.PDFEvent.java
License:Apache License
public void onEndPage(PdfWriter writer, Document document) { TableExportOptions exportOptions = wgtTable.getExportOptions(); try {// w w w. j ava 2 s .co m Rectangle page = document.getPageSize(); if (exportOptions.isShowDefaultHeader() || StringUtils.isNotEmpty(exportOptions.getHeaderImage())) { PdfPTable head = new PdfPTable(3); head.getDefaultCell().setBorder(Rectangle.NO_BORDER); Paragraph title = new Paragraph(wgtTable.getTitle()); title.setAlignment(Element.ALIGN_LEFT); head.addCell(title); Paragraph empty = new Paragraph(""); head.addCell(empty); if (StringUtils.isNotEmpty(exportOptions.getHeaderImage())) { try { URL absoluteFileUrl = wgtTable.getPage().getClass() .getResource("/" + exportOptions.getHeaderImage()); if (absoluteFileUrl != null) { String path = absoluteFileUrl.getPath(); Image jpg = Image.getInstance(path); jpg.scaleAbsoluteHeight(40); jpg.scaleAbsoluteWidth(200); head.addCell(jpg); } } catch (Exception e) { logger.error(e.getMessage()); Paragraph noImage = new Paragraph("Image not found!"); head.addCell(noImage); } } else { head.addCell(empty); } head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent()); } if (exportOptions.isShowDefaultFooter() || StringUtils.isNotEmpty(exportOptions.getFooterText()) || exportOptions.isShowPageNumber()) { PdfPTable foot = new PdfPTable(3); String footerText = exportOptions.getFooterText() != null ? exportOptions.getFooterText() : ""; if (!exportOptions.isShowDefaultFooter()) { foot.addCell(new Paragraph(footerText)); foot.addCell(new Paragraph("")); } else { foot.getDefaultCell().setBorder(Rectangle.NO_BORDER); String leftText = ""; if (StringUtils.isNotEmpty(exportOptions.getFooterText())) { leftText = exportOptions.getFooterText(); } Paragraph left = new Paragraph(leftText); left.setAlignment(Element.ALIGN_LEFT); foot.addCell(left); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, TextService.getLocale()); Date today = new Date(); String date = df.format(today); Paragraph center = new Paragraph(date); center.setAlignment(Element.ALIGN_CENTER); foot.addCell(center); } if (exportOptions.isShowPageNumber()) { Paragraph right = new Paragraph( TextService.getString("pdf.page@Page:") + " " + writer.getPageNumber()); right.setAlignment(Element.ALIGN_LEFT); foot.addCell(right); foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); } else { foot.addCell(new Paragraph("")); } } } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:org.xhtmlrenderer.pdf.ITextFSImage.java
License:Open Source License
public Object clone() { return new ITextFSImage(Image.getInstance(_image)); }
From source file:org.xhtmlrenderer.pdf.ITextReplacedElementFactory.java
License:Open Source License
protected FSImage buildImage(String srcAttr, UserAgentCallback uac) throws IOException, BadElementException { FSImage fsImage;// w ww. jav a2 s . c o m if (srcAttr.startsWith("data:image/")) { String b64encoded = srcAttr.substring(srcAttr.indexOf("base64,") + "base64,".length(), srcAttr.length()); // BASE64Decoder decoder = new BASE64Decoder(); // byte[] decodedBytes = decoder.decodeBuffer(b64encoded); // byte[] decodedBytes = B64Decoder.decode(b64encoded); byte[] decodedBytes = Base64.decode(b64encoded); fsImage = new ITextFSImage(Image.getInstance(decodedBytes)); } else { fsImage = uac.getImageResource(srcAttr).getImage(); } return fsImage; }
From source file:org.xhtmlrenderer.pdf.ITextUserAgent.java
License:Open Source License
public ImageResource getImageResource(String uriStr) { ImageResource resource = null;/*w w w .j av a 2 s.c o m*/ if (ImageUtil.isEmbeddedBase64Image(uriStr)) { resource = loadEmbeddedBase64ImageResource(uriStr); } else { uriStr = resolveURI(uriStr); resource = (ImageResource) _imageCache.get(uriStr); if (resource == null) { InputStream is = resolveAndOpenStream(uriStr); if (is != null) { try { URI uri = new URI(uriStr); if (uri.getPath() != null && uri.getPath().toLowerCase().endsWith(".pdf")) { PdfReader reader = _outputDevice.getReader(uri); PDFAsImage image = new PDFAsImage(uri); Rectangle rect = reader.getPageSizeWithRotation(1); image.setInitialWidth(rect.getWidth() * _outputDevice.getDotsPerPoint()); image.setInitialHeight(rect.getHeight() * _outputDevice.getDotsPerPoint()); resource = new ImageResource(uriStr, image); } else { Image image = Image.getInstance(readStream(is)); scaleToOutputResolution(image); resource = new ImageResource(uriStr, new ITextFSImage(image)); } _imageCache.put(uriStr, resource); } catch (Exception e) { XRLog.exception("Can't read image file; unexpected problem for URI '" + uriStr + "'", e); } finally { try { is.close(); } catch (IOException e) { // ignore } } } } if (resource != null) { FSImage image = resource.getImage(); if (image instanceof ITextFSImage) { image = (FSImage) ((ITextFSImage) resource.getImage()).clone(); } resource = new ImageResource(resource.getImageUri(), image); } else { resource = new ImageResource(uriStr, null); } } return resource; }
From source file:org.xhtmlrenderer.pdf.ITextUserAgent.java
License:Open Source License
private ImageResource loadEmbeddedBase64ImageResource(final String uri) { try {//from w w w. j a v a 2s .c o m byte[] buffer = ImageUtil.getEmbeddedBase64Image(uri); Image image = Image.getInstance(buffer); scaleToOutputResolution(image); return new ImageResource(null, new ITextFSImage(image)); } catch (Exception e) { XRLog.exception("Can't read XHTML embedded image.", e); } return new ImageResource(null, null); }
From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java
License:Open Source License
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx) throws DocumentException { logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); // added by vic, hsfo Enumeration<String> em = req.getParameterNames(); while (em.hasMoreElements()) { logger.debug("para=" + em.nextElement()); }//from ww w . j a v a2s . c om em = req.getAttributeNames(); while (em.hasMoreElements()) logger.debug("attr: " + em.nextElement()); if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) { return generateHsfoRxPDF(req); } String newline = System.getProperty("line.separator"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null; String method = req.getParameter("__method"); String origPrintDate = null; String numPrint = null; if (method != null && method.equalsIgnoreCase("rePrint")) { origPrintDate = req.getParameter("origPrintDate"); numPrint = req.getParameter("numPrints"); } logger.debug("method in generatePDFDocumentBytes " + method); String clinicName; String clinicTel; String clinicFax; // check if satellite clinic is used String useSatelliteClinic = req.getParameter("useSC"); logger.debug(useSatelliteClinic); if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) { String scAddress = req.getParameter("scAddress"); logger.debug("clinic detail" + "=" + scAddress); HashMap<String, String> hm = parseSCAddress(scAddress); clinicName = hm.get("clinicName"); clinicTel = hm.get("clinicTel"); clinicFax = hm.get("clinicFax"); } else { // parameters need to be passed to header and footer clinicName = req.getParameter("clinicName"); logger.debug("clinicName" + "=" + clinicName); clinicTel = req.getParameter("clinicPhone"); clinicFax = req.getParameter("clinicFax"); } String patientPhone = req.getParameter("patientPhone"); String patientCityPostal = req.getParameter("patientCityPostal"); String patientAddress = req.getParameter("patientAddress"); String patientName = req.getParameter("patientName"); String sigDoctorName = req.getParameter("sigDoctorName"); String rxDate = req.getParameter("rxDate"); String rx = req.getParameter("rx"); String patientDOB = req.getParameter("patientDOB"); String showPatientDOB = req.getParameter("showPatientDOB"); String imgFile = req.getParameter("imgFile"); String patientHIN = req.getParameter("patientHIN"); String patientChartNo = req.getParameter("patientChartNo"); String pracNo = req.getParameter("pracNo"); Locale locale = req.getLocale(); boolean isShowDemoDOB = false; if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) { isShowDemoDOB = true; } if (!isShowDemoDOB) patientDOB = ""; if (rx == null) { rx = ""; } String additNotes = req.getParameter("additNotes"); String[] rxA = rx.split(newline); List<String> listRx = new ArrayList<String>(); String listElem = ""; // parse rx and put into a list of rx; for (String s : rxA) { if (s.equals("") || s.equals(newline) || s.length() == 1) { listRx.add(listElem); listElem = ""; } else { listElem = listElem + s; listElem += newline; } } // get the print prop values Properties props = new Properties(); StringBuilder temp = new StringBuilder(); for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getParameter(temp.toString())); } for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString()); } Document document = new Document(); try { String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown"; // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages // however the same graphic will be applied to all pages // ie. __graphicPage=2&__graphicPage=3 String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile"); int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length; if (cfgGraphicFile != null) { // for (String s : cfgGraphicFile) { // p("cfgGraphicFile", s); // } } String[] graphicPage = req.getParameterValues("__graphicPage"); ArrayList<String> graphicPageArray = new ArrayList<String>(); if (graphicPage != null) { // for (String s : graphicPage) { // p("graphicPage", s); // } graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage)); } // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size Rectangle pageSize = PageSize.LETTER; String pageSizeParameter = req.getParameter("rxPageSize"); if (pageSizeParameter != null) { if ("PageSize.HALFLETTER".equals(pageSizeParameter)) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(pageSizeParameter)) { pageSize = PageSize.A6; } else if ("PageSize.A4".equals(pageSizeParameter)) { pageSize = PageSize.A4; } } /* * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; } */ // p("size of page ", props.getProperty(PAGESIZE)); document.setPageSize(pageSize); // 285=left margin+width of box, 5f is space for looking nice document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom writer = PdfWriter.getInstance(document, baosPDF); writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal, patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint, imgFile, patientHIN, patientChartNo, pracNo, locale)); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); document.open(); document.newPage(); PdfContentByte cb = writer.getDirectContent(); BaseFont bf; // = normFont; cb.setRGBColorStroke(0, 0, 255); // render prescriptions for (String rxStr : listRx) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(5f); document.add(p); } // render additional notes if (additNotes != null && !additNotes.equals("")) { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(10f); document.add(p); } // render optometristEyeParam if (req.getAttribute("optometristEyeParam") != null) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph( new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(15f); document.add(p); } // render QrCode if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) { Integer scriptId = Integer.parseInt(req.getParameter("scriptId")); byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId); Image qrCode = Image.getInstance(qrCodeImage); document.add(qrCode); } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { logger.error("Error", e); } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } } logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); return baosPDF; }
From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ConsultationPDFCreator.java
License:Open Source License
private PdfPTable createLogoHeader() { float[] tableWidths; PdfPCell cell = new PdfPCell(); //tableWidths = new float[]{ 1.5f, 2.5f }; //PdfPTable infoTable = new PdfPTable(tableWidths); PdfPTable infoTable = new PdfPTable(1); try {//from w w w. j a v a 2 s . c o m String filename = ""; if (props.getProperty("multisites") != null && "on".equalsIgnoreCase(props.getProperty("multisites"))) { DocumentDAO documentDao = (DocumentDAO) SpringUtils.getBean("documentDAO"); SiteDao siteDao = (SiteDao) SpringUtils.getBean("siteDao"); Site site = siteDao.getByLocation(reqFrm.siteName); if (site != null) { if (site.getSiteLogoId() != null) { org.oscarehr.document.model.Document d = documentDao .getDocument(String.valueOf(site.getSiteLogoId())); String dir = props.getProperty("DOCUMENT_DIR"); filename = dir.concat(d.getDocfilename()); } else { //If no logo file uploaded for this site, use the default one defined in oscar properties file. filename = props.getProperty("faxLogoInConsultation"); } } } else { filename = props.getProperty("faxLogoInConsultation"); } FileInputStream fileInputStream = new FileInputStream(filename); byte[] faxLogImage = new byte[1024 * 256]; fileInputStream.read(faxLogImage); Image image = Image.getInstance(faxLogImage); image.scalePercent(80f); image.setBorder(0); cell = new PdfPCell(image); cell.setBorder(0); infoTable.addCell(cell); } catch (Exception e) { logger.error("Unexpected error.", e); } // The last cell in the table is extended to the maximum available height; // inserting a blank cell here prevents the last border used to underline text from // being displaced to the bottom of this table. cell.setPhrase(new Phrase(" ", font)); cell.setBorder(0); cell.setColspan(2); infoTable.addCell(cell); return infoTable; }
From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ConsultationPDFCreator.java
License:Open Source License
private void addSignature(PdfPTable infoTable) { float[] tableWidths; PdfPCell cell;//from ww w.j a v a 2 s . c om tableWidths = new float[] { 0.55f, 2.75f }; PdfPTable table = new PdfPTable(tableWidths); cell = new PdfPCell(new Phrase(getResource("msgSignature") + ":", infoFont)); cell.setBorder(0); cell.setHorizontalAlignment(PdfPCell.ALIGN_BOTTOM); table.addCell(cell); try { DigitalSignatureDao digitalSignatureDao = (DigitalSignatureDao) SpringUtils .getBean("digitalSignatureDao"); DigitalSignature digitalSignature = digitalSignatureDao.find(Integer.parseInt(reqFrm.signatureImg)); if (digitalSignature != null) { Image image = Image.getInstance(digitalSignature.getSignatureImage()); image.scalePercent(80f); image.setBorder(0); cell = new PdfPCell(image); cell.setBorder(0); table.addCell(cell); cell = new PdfPCell(table); cell.setBorder(0); cell.setPadding(0); cell.setColspan(1); infoTable.addCell(cell); return; } } catch (Exception e) { logger.error("Unexpected error.", e); } }
From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ImagePDFCreator.java
License:Open Source License
/** * Prints the consultation request.//w w w . j a v a2 s . c o m * @throws IOException when an error with the output stream occurs * @throws DocumentException when an error in document construction occurs */ public void printPdf() throws IOException, DocumentException { Image image; try { image = Image.getInstance((String) request.getAttribute("imagePath")); } catch (Exception e) { logger.error("Unexpected error:", e); throw new DocumentException(e); } // Create the document we are going to write to document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, os); document.setPageSize(PageSize.LETTER); ResourceBundle.getBundle("oscarResources", request.getLocale()) .getString("oscarEncounter.oscarConsultationRequest.consultationFormPrint.msgImage"); document.addCreator("OSCAR"); document.open(); int type = image.getOriginalType(); if (type == Image.ORIGINAL_TIFF) { // The following is composed of code from com.lowagie.tools.plugins.Tiff2Pdf modified to create the // PDF in memory instead of on disk RandomAccessFileOrArray ra = new RandomAccessFileOrArray((String) request.getAttribute("imagePath")); int comps = TiffImage.getNumberOfPages(ra); boolean adjustSize = false; PdfContentByte cb = writer.getDirectContent(); for (int c = 0; c < comps; ++c) { Image img = TiffImage.getTiffImage(ra, c + 1); if (img != null) { if (adjustSize) { document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight())); document.newPage(); img.setAbsolutePosition(0, 0); } else { if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) { img.scaleToFit(500, 700); } img.setAbsolutePosition(20, 20); document.newPage(); document.add( new Paragraph((String) request.getAttribute("imageTitle") + " - page " + (c + 1))); } cb.addImage(img); } } ra.close(); } else { PdfContentByte cb = writer.getDirectContent(); if (image.getScaledWidth() > 500 || image.getScaledHeight() > 700) { image.scaleToFit(500, 700); } image.setAbsolutePosition(20, 20); cb.addImage(image); } document.close(); }