Example usage for com.itextpdf.text Image getPlainWidth

List of usage examples for com.itextpdf.text Image getPlainWidth

Introduction

In this page you can find the example usage for com.itextpdf.text Image getPlainWidth.

Prototype

public float getPlainWidth() 

Source Link

Document

Gets the plain width of the image.

Usage

From source file:com.github.ukase.toolkit.WrappedUserAgentCallback.java

License:Open Source License

private void scaleToOutputResolution(Image image) {
    float factor = context.getDotsPerPixel();
    if (factor != 1.0f) {
        image.scaleAbsolute(image.getPlainWidth() * factor, image.getPlainHeight() * factor);
    }/*from  w  ww  . j  a  va  2  s. co m*/
}

From source file:com.semfapp.adamdilger.semf.Pdf.java

License:Open Source License

private void createPDFNew(String filePath, String htmlString, @Nullable ArrayList<ImageFile> images) {

    File file = null;//from  w  w w . ja  v  a 2 s.  c  o m
    try {
        file = new File(filePath);

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        // step 4

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssFile cssFile = XMLWorkerHelper.getCSS(activity.getAssets().open("styles.css"));
        cssResolver.addCss(cssFile);

        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // Pipelines

        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        Drawable d = activity.getResources().getDrawable(R.drawable.logo_icon);
        Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapData = stream.toByteArray();

        Image image = Image.getInstance(bitmapData);
        image.setAbsolutePosition(35, 763);
        image.scalePercent(12);
        document.add(image);

        p.parse(new ByteArrayInputStream(htmlString.getBytes(StandardCharsets.UTF_8)));

        if (images != null) {
            System.out.println("Adding IMage");

            for (int x = 0; x < images.size(); x++) {
                Image cursor = images.get(x).getImage();

                float ratio = cursor.getPlainHeight() / cursor.getPlainWidth();

                float imgWidth = document.getPageSize().getWidth() - 100;
                float imgHeight = document.getPageSize().getHeight() - 100;

                cursor.scaleToFit(new Rectangle(imgWidth, imgHeight));

                document.add(cursor);
            }
        }

        // step 5
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.tommontom.pdfsplitter.PdfMerge.java

public static void doMerge(java.util.List<InputStream> list, String[] imageList, String[] listWordExcels,
        OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    writer.setFullCompression();/*from   ww w . jav a  2s. co  m*/
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Image img;
    for (InputStream in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            document.newPage();
            //import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            //add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
        }

    }
    for (int i = 0; i < imageList.length; i++) {
        document.newPage();
        if (imageList[i] != null) {
            img = Image.getInstance(String.format("%s", imageList[i]));
            Rectangle one = new Rectangle(img.getPlainWidth(), img.getPlainHeight());
            document.setPageSize(one);
            if (img.getScaledWidth() > img.getScaledHeight()) {
                img.rotate();
            }
            if (img.getScaledWidth() > 792 || img.getScaledHeight() > 792) {
                img.scaleToFit(792, 792);

            }
            img.setDpi(150, 150);
            document.add(img);
        }
    }
    for (int i = 0; i < listWordExcels.length; i++) {
        if (imageList[i] != null) {
            File input = new File(listWordExcels[i]);
            File output = new File(listWordExcels[i] + ".pdf");
            String outputS = listWordExcels[i] + ".pdf";
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(input, output);
            PdfReader readerWord = new PdfReader(outputS);
            PdfImportedPage page = writer.getImportedPage(readerWord, readerWord.getNumberOfPages());
            cb.addTemplate(page, 0, 0);
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:Controller.ControllerCompra.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w  w .  j av a 2s .c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        //int estado = 0;
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String facturaProveedor = (request.getParameter("txtNumeroFactura"));
            String nombreProveedor = (request.getParameter("txtNombre"));
            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalCompra"));
            listObjDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listObjDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objCompra.setFacturaProveedor(facturaProveedor);
            _objCompra.setNombreProveedor(nombreProveedor);
            _objCompra.setTotalCompra(totalCompra);
            daoModelCompra = new ModelCompra();
            String salida = Mensaje(daoModelCompra.Add(_objCompra, _objUsuario, listObjDetalleMovimientos),
                    "La compra ha sido registrada", "Ha ocurrido un error");
            daoModelCompra.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableCompra());
            break;
        }
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iText">
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> compra = (Map) material.get("Compra");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra                        
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Nombre del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("nombreProveedor") + "\n"));
                headerDerecha.add(new Chunk("Factura del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("facturaProveedor") + "\n"));
                headerDerecha.add(new Chunk("Fecha Compra: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("fechaCompra") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Compra", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(compra.get("totalCompra")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        //</editor-fold>
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iReports">
        case "Imprimir2": {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String source = url + "/reports/newReport1.jrxml";
                JasperPrint jasperPrint = null;
                JasperReport jasperReport = null;
                JasperDesign jasperDesign = null;
                System.out.println(source);
                String reportPath = request.getServletContext().getRealPath("reports") + "\\newReport1.jrxml";
                jasperDesign = JRXmlLoader.load(reportPath);
                jasperReport = JasperCompileManager.compileReport(jasperDesign);
                jasperPrint = JasperFillManager.fillReport(jasperReport, reporte(id),
                        daoModelCompra.getConnection());
                JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
            } catch (Exception ex) {
                for (StackTraceElement ruta : ex.getStackTrace()) {
                    System.err.println(ruta);
                }
            }
        }
            break;
        //</editor-fold>

        }
    }

}

From source file:Controller.ControllerVenta.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www . j  av  a 2 s .c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String documentoCliente = null;
            String nombreCliente = null;
            int numeroVenta = 0;
            if (Validador.validarDocumento(request.getParameter("documentoCliente"))
                    & Validador.validarNombresCompletos(request.getParameter("txtNombreCliente"))
                    & Validador.validarNumero(request.getParameter("txtNumeroVenta"))) {
                documentoCliente = (request.getParameter("documentoCliente"));
                nombreCliente = (request.getParameter("txtNombreCliente"));
                numeroVenta = Integer.parseInt(request.getParameter("txtNumeroVenta"));
            } else {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(Mensaje(false, null, "Ha ingresado datos incorrectos"));
                break;
            }

            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalVenta"));
            listOjbDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listOjbDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objVenta.setIdVenta(numeroVenta);
            _objVenta.setDocumentoCliente(documentoCliente);
            _objVenta.setNombreCliente(nombreCliente);
            _objVenta.setTotalVenta(totalCompra);
            daoModelVenta = new ModelVenta();
            String salida = Mensaje(daoModelVenta.Add(_objVenta, _objUsuario, listOjbDetalleMovimientos),
                    "La venta ha sido registrada", "Ha ocurrido un error");
            daoModelVenta.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableVenta());
            break;
        }
        case "Contador": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getContador());
            break;
        }
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> venta = (Map) material.get("Venta");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra         
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Id. de la Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("numeroVenta") + "\n"));
                headerDerecha.add(new Chunk("Nombre del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("nombreCliente") + "\n"));
                headerDerecha.add(new Chunk("Documento del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("documentoCliente") + "\n"));
                headerDerecha.add(new Chunk("Fecha Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("fechaVenta") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Venta", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(venta.get("totalVenta")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        }
    }
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String insertStamp(String loc, float x, float y, int width, int height, int set, String date,
        int pageNum, int masterHeight, int masterWidth, String projNo)
        throws BadElementException, MalformedURLException, IOException, DocumentException {
    Image image = Image.getInstance(loc);
    float[] scalar = scale(x, y, width, height, masterHeight, masterWidth, pageNum);
    float[] trans = translate(x, y, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight,
            masterWidth, pageNum);/* w w  w.  ja  va2  s. c  o  m*/
    float[] f = commentTrans(x, y, masterHeight, masterWidth, pageNum);

    float shift = 0;

    /* Addition. ftorres - 7/22/2015 - Added to account for rotated pages 
     *   with the origin (0,0) not set to the bottom-left of the page. [1400] */
    trans = translateRotation(trans[0], trans[1], pageNum);

    if (set == 1) {
        float m = image.getPlainHeight();
        float pageChunk = r[pageNum - 1].getHeight() / 10;
        shift = r[pageNum - 1].getHeight() / 100;
        scalar[1] = (int) (pageChunk);
        scalar[0] = (int) (image.getPlainWidth() * pageChunk) / image.getPlainHeight();
        trans[0] = (int) (0 + (pageChunk * widthScalar));
        trans[1] = (int) (r[pageNum - 1].getHeight() - (pageChunk * heightScalar)
                - (shift * (heightScalar + 2)));
        heightScalar = heightScalar + 1;
        if (heightScalar == 8) {
            heightScalar = 0;
            widthScalar = widthScalar + 2;
        }
    }

    if (set == 1) {
        image.setAbsolutePosition(trans[0] + shift, trans[1] - scalar[1]);
        image.scaleAbsoluteHeight(scalar[1]);
        image.scaleAbsoluteWidth(scalar[0]);
        image.setRotationDegrees(rot);
    } else {
        //swap stamp dimensions for rotated drawings
        if (rot > 0) {
            image.setAbsolutePosition(trans[0] - 2 * scalar[1], trans[1] - 2 * scalar[0]);
        } else {
            image.setAbsolutePosition(trans[0], trans[1] - 2 * scalar[1]);
        }
        image.scaleAbsoluteHeight(scalar[1] * 2);
        image.scaleAbsoluteWidth(scalar[0] * 2);
        image.setRotationDegrees(rot);
    }

    PdfContentByte fg = pds.getOverContent(pageNum);
    fg.addImage(image);

    //Added by tmittelstadt on 09/21/2012 for ticket #698
    //draws a box around the date
    fg.setColorFill(BaseColor.WHITE);
    fg.setLineWidth(0f);

    //dmoody removed box.  ticket 900
    /*fg.moveTo(trans[0], trans[1] - scalar[1] * 2);
       fg.lineTo(trans[0], trans[1] - scalar[1] * 2 - 10);
       fg.lineTo(trans[0] + scalar[0] * 2, trans[1] - scalar[1] * 2 - 10);
       fg.lineTo(trans[0] + scalar[0] * 2, trans[1] - scalar[1] * 2);
       fg.lineTo(trans[0], trans[1] - scalar[1] * 2);*/

    fg.closePathFillStroke();
    fg.fill();

    //adds the date the stamp was added to the document to the pdf
    Phrase p = new Phrase(date);
    p.getFont().setColor(BaseColor.BLACK);
    //Modification zreeve 10/11/2012.  set font size to 11.
    p.getFont().setSize(9f);
    //p.getChunks().get(0).setAnnotation(PdfAnnotation.createText(pds.getWriter(), new Rectangle(trans[0],trans[1], trans[0]+5f, trans[1]+5f), id, comment, true, id));
    ColumnText.showTextAligned(fg, Element.ALIGN_CENTER, p, (float) (trans[0]),
            (float) (trans[1] - scalar[1] * 2 - 12), 0);
    Phrase pn = new Phrase("#[" + projNo + "]");
    pn.getFont().setColor(BaseColor.BLACK);
    pn.getFont().setSize(10f);
    pn.getFont().setStyle("bold");
    ColumnText.showTextAligned(fg, Element.ALIGN_CENTER, pn, (float) (trans[0]),
            (float) (trans[1] - scalar[1] * 2 - 22), 0);

    return "";
}

From source file:eu.aniketos.wp1.ststool.report.pdfgenerator.AbstractContentFactory.java

License:Open Source License

/**
 * //w  w  w .  jav a2  s  .c o m
 * @param img
 *           The Image to resize
 * @param maxWidht
 *           maximum imageWitdh
 * @param maxHeight
 *           maximum imageHeight
 * @param enlarge
 *           true if the image should be enlarged if is smaller than maxWidth && maxHeigt
 * @return the percentual reduction scale factor (100 means no reduction)
 */
protected float fitImageInArea(Image img, float maxWidht, float maxHeight, boolean enlarge) {

    if (maxHeight <= 0 && maxWidht <= 0)
        throw new RuntimeException("Invalid value");

    float imgWidth = img.getPlainWidth();
    float imgHeight = img.getPlainHeight();

    float reductionScale = 100;

    if (maxHeight <= 0) {
        reductionScale = (maxWidht / imgWidth) * 100;
    } else if (maxWidht <= 0) {
        reductionScale = (maxHeight / imgHeight) * 100;
    } else {
        float widthScale = maxWidht / imgWidth;
        float heightScale = maxHeight / imgHeight;

        reductionScale = (Math.min(widthScale, heightScale)) * 100;
    }
    if (reductionScale > 100 && !enlarge)
        reductionScale = 100;

    if (reductionScale != 100) {
        img.scalePercent(reductionScale);
    }
    return reductionScale;
}

From source file:eu.aniketos.wp1.ststool.report.pdfgenerator.ReportContentFactory.java

License:Open Source License

/******************************************************************************************/

private void buildAppendixAChapter(Chapter c, Document d) {

    c.setTitle(getChapterTitleParagraph("Appendix A"));
    c.setNumberDepth(0);// w w w .  j  av a  2 s  .  c o m
    c.setTriggerNewPage(true);

    float width = d.getPageSize().getWidth() - d.leftMargin() - d.rightMargin();
    float height = d.getPageSize().getHeight() - d.topMargin() - d.bottomMargin() - 70;

    if (needSocialDiagramInAppendixA()) {
        Image socialImage = rsp.generateScrenshot(ViewsManager.SOCIAL_VIEW);
        socialImage.setAlignment(Element.ALIGN_CENTER);
        if (socialImage.getPlainWidth() > socialImage.getPlainHeight()) {
            fitImageInArea(socialImage, height, width, true);
            socialImage.setRotationDegrees(90);
        } else {
            fitImageInArea(socialImage, width, height, true);
        }

        c.add(decorateImage(socialImage, ftc.getFigure(FigureConstant.SOCIAL_DIAGRAM)
                + " - Social View for the " + getProjectName() + " project"));
    }
    if (needInformationDiagramInAppendixA()) {
        Image informationImage = rsp.generateScrenshot(ViewsManager.RESOURCE_VIEW);
        informationImage.setAlignment(Element.ALIGN_CENTER);
        if (informationImage.getPlainWidth() > informationImage.getPlainHeight()) {
            fitImageInArea(informationImage, height, width, true);
            informationImage.setRotationDegrees(90);
        } else {
            fitImageInArea(informationImage, width, height, true);
        }
        // c.add(informationImage);
        c.add(decorateImage(informationImage, ftc.getFigure(FigureConstant.INFORMATION_DIAGRAM)
                + " - Information View for the " + getProjectName() + " project"));

    }
    if (needInformationDiagramInAppendixA()) {
        Image authorisationImage = rsp.generateScrenshot(ViewsManager.AUTHORIZATION_VIEW);
        authorisationImage.setAlignment(Element.ALIGN_CENTER);
        if (authorisationImage.getPlainWidth() > authorisationImage.getPlainHeight()) {
            fitImageInArea(authorisationImage, height, width, true);
            authorisationImage.setRotationDegrees(90);
        } else {
            fitImageInArea(authorisationImage, width, height, true);
        }
        // c.add(authorisationImage);
        c.add(decorateImage(authorisationImage, ftc.getFigure(FigureConstant.AUTH_DIAGRAM)
                + " - Authorisation View for the " + getProjectName() + " project"));

    }

    c.setComplete(true);
}

From source file:org.fao.geonet.api.records.formatters.ImageReplacedElementFactory.java

License:Open Source License

private ReplacedElement loadImage(LayoutContext layoutContext, BlockBox box,
        UserAgentCallback userAgentCallback, int cssWidth, int cssHeight, String url, float scaleFactor) {
    InputStream input = null;//from  www.j  av  a  2  s .  c  om
    try {
        Log.error(Geonet.GEONETWORK, "URL -> " + url.toString());

        input = new URL(url).openStream();
        byte[] bytes = IOUtils.toByteArray(input);
        Image image = Image.getInstance(bytes);

        image.scaleAbsolute(image.getPlainWidth() * scaleFactor, image.getPlainHeight() * scaleFactor);
        FSImage fsImage = new ITextFSImage(image);

        if (cssHeight > -1 && cssWidth > -1) {
            fsImage.scale(cssWidth, cssHeight);
        }
        int maxWidth = (int) (900 * scaleFactor);
        if (fsImage.getWidth() > maxWidth) {
            int ratio = fsImage.getWidth() / maxWidth;
            fsImage.scale(maxWidth, fsImage.getHeight() / ratio);
        }

        return new ITextImageElement(fsImage);
    } catch (Exception e) {
        Log.error(Geonet.GEONETWORK, "Error writing metadata to PDF", e);

        try {
            return superFactory.createReplacedElement(layoutContext, box, userAgentCallback, cssWidth,
                    cssHeight);
        } catch (Throwable e2) {
            return new EmptyReplacedElement(cssWidth, cssHeight);
        }
    } finally {
        if (input != null) {
            IOUtils.closeQuietly(input);
        }
    }
}