Example usage for com.itextpdf.text Image scaleAbsolute

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

Introduction

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

Prototype

public void scaleAbsolute(final float newWidth, final float newHeight) 

Source Link

Document

Scale the image to an absolute width and an absolute height.

Usage

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 {// ww w . java2 s.  c o 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.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 {/*from  w  w w. ja  v a2 s  .c  o m*/
        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:SessionBean.ReportMgt.ReportMgtBean.java

License:Open Source License

public void createMonthlyReport(Integer startYear, Integer startMonth, Integer endYear, Integer endMonth) {
    try {//from  www  .  ja v  a 2s. co m
        String RESULT;
        System.out.print("start");
        if (startYear.equals(endYear) && startMonth.equals(endMonth)) {
            RESULT = "d:/GeneralReport-" + startYear + "." + startMonth + ".pdf";
        } else {
            RESULT = "d:/GeneralReport-" + startYear + "." + startMonth + "-" + endYear + "." + endMonth
                    + ".pdf";
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Document document = new Document();
        PdfWriter.getInstance(document, baos);
        document.open();
        Image image = Image.getInstance("d:/logo-4227.png");
        image.scaleAbsolute(150, 50);
        document.add(new Paragraph(""));
        document.add(image);
        Calendar targetPeriod = Calendar.getInstance();
        int month = targetPeriod.get(Calendar.MONTH) + 1;
        int year = targetPeriod.get(Calendar.YEAR);
        String reportTile;
        document.add(new Paragraph("WineXpress General Sales Report",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.BLACK)));

        if (startYear.equals(endYear) && startMonth.equals(endMonth)) {
            reportTile = startYear + "." + startMonth;
            document.add(new Paragraph(reportTile,
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.RED)));
        } else {
            reportTile = startYear + "." + startMonth + "-" + endYear + "." + endMonth;
            document.add(new Paragraph(reportTile,
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.RED)));
        }

        document.add(new Paragraph("Generated Time: " + new Date().toString(),
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.PLAIN, BaseColor.BLACK)));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        PdfPTable table = new PdfPTable(6);
        table.getDefaultCell().setBorder(0);
        //            PdfPCell cell= new PdfPCell(new Paragraph("Wine Name"));
        //           cell.setColspan(4);
        //            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //            cell.setBackgroundColor(BaseColor.BLACK);
        //           table.addCell(cell);
        table.addCell("Item ID");
        table.addCell("Item Name");
        table.addCell("Sales   (bottle)");
        table.addCell("Revenue (SGD)");
        table.addCell("Cost    (SGD)");
        table.addCell("Profit  (SGD)");

        Integer totalSales = 0;
        Double totalRevenue = 0D;
        Double totalCost = 0D;
        Double totalProfit = 0D;

        Query q1;
        q1 = em.createQuery("select i from PurchaseEntity i");
        Query q2;
        q2 = em.createQuery("select i from ItemEntity i");
        System.out.print("2");
        List<ItemEntity> itemList = q2.getResultList();
        List<PurchaseEntity> purchaseList = q1.getResultList();
        System.out.print("3");
        startMonth -= 1;
        endMonth -= 1;
        for (ItemEntity i : itemList) {
            Integer sales = 0;
            Double revenue = 0D;
            Double cost = 0D;

            for (PurchaseEntity p : purchaseList) {

                if ((p.getPurchasedDate().get(Calendar.YEAR) >= startYear)
                        && (p.getPurchasedDate().get(Calendar.YEAR) <= endYear)
                        && (p.getPurchasedDate().get(Calendar.MONTH) >= startMonth)
                        && (p.getPurchasedDate().get(Calendar.MONTH) <= endMonth)) {
                    System.out.print("looploop1");
                    Long orderId = p.getOrderId();
                    OrderEntity order = em.find(OrderEntity.class, orderId);
                    ItemEntity item = em.find(ItemEntity.class, order.getItemId());
                    System.out.print("looploop2");
                    if (item.getId().equals(i.getId())) {
                        sales += p.getQuantity();
                        revenue += p.getTotalPrice();
                        cost += p.getQuantity() * item.getCost();
                        System.out.print("looploop3");
                    }
                }
            }
            Double profit = revenue - cost;
            totalSales += sales;
            totalRevenue += revenue;
            totalCost += cost;
            totalProfit += profit;
            table.addCell(i.getId().toString());
            table.addCell(i.getItemName());
            table.addCell(sales.toString());
            table.addCell(revenue.toString());
            table.addCell(cost.toString());
            table.addCell(profit.toString());
        }

        document.add(table);

        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        PdfPTable table2 = new PdfPTable(6);
        table2.getDefaultCell().setBorder(0);

        table2.addCell(" ");
        table2.addCell(" ");
        table2.addCell(totalSales.toString());
        table2.addCell(totalRevenue.toString());
        table2.addCell(totalCost.toString());
        table2.addCell(totalProfit.toString());

        document.add(table2);
        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));

        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("Copyright  2015 All rights reserved | WineXpress",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, BaseColor.BLACK)));
        document.close();
        FileOutputStream fos = new FileOutputStream(RESULT);
        fos.write(baos.toByteArray());
        fos.close();
        System.out.println("created");

        Calendar generatedTime = Calendar.getInstance();

        ReportEntity report = new ReportEntity("GeneralReport-" + reportTile, "G", RESULT, generatedTime);
        em.persist(report);
        em.flush();

    } catch (Exception e) {
    }
}

From source file:SessionBean.ReportMgt.ReportMgtBean.java

License:Open Source License

public void createProductReport(Long productId, Integer startYear, Integer startMonth, Integer endYear,
        Integer endMonth) {/*from www . j av  a 2s .c  o m*/
    try {
        System.out.print("start");
        ItemEntity item = em.find(ItemEntity.class, productId);
        String RESULT;
        String reportTitle;

        if (startYear.equals(endYear) && startMonth.equals(endMonth)) {
            RESULT = "d:/ProductReport-" + item.getId() + "-" + startYear + "." + startMonth + ".pdf";
            reportTitle = startYear + "." + startMonth;
        } else {
            RESULT = "d:/ProductReport-" + item.getId() + "-" + startYear + "." + startMonth + "-" + endYear
                    + "." + endMonth + ".pdf";
            reportTitle = startYear + "." + startMonth + "-" + endYear + "." + endMonth;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        PdfWriter.getInstance(document, baos);
        document.open();
        Image image = Image.getInstance("d:/logo-4227.png");
        image.scaleAbsolute(150, 50);
        document.add(image);

        document.add(new Paragraph("WineXpress Product Sales Report",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.BLACK)));
        document.add(new Paragraph("Item " + item.getId() + ": " + item.getItemName() + ", " + item.getVitage(),
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.RED)));
        document.add(new Paragraph("Generated Time: " + new Date().toString(),
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.PLAIN, BaseColor.BLACK)));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        PdfPTable table = new PdfPTable(5);
        table.getDefaultCell().setBorder(0);
        //            PdfPCell cell= new PdfPCell(new Paragraph("Wine Name"));
        //           cell.setColspan(4);
        //            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //            cell.setBackgroundColor(BaseColor.BLACK);
        //           table.addCell(cell);
        table.addCell("Period");
        table.addCell("Sales");
        table.addCell("Revenue");
        table.addCell("Cost");
        table.addCell("Profit");
        table.addCell(" ");
        table.addCell("(bottle)");
        table.addCell("(SGD)");
        table.addCell("(SGD)");
        table.addCell("(SGD)");

        Integer totalSales = 0;
        Double totalRevenue = 0D;
        Double totalCost = 0D;
        Double totalProfit = 0D;

        Query q1;
        q1 = em.createQuery("select i from PurchaseEntity i");
        Query q2;
        q2 = em.createQuery("select i from ItemEntity i");
        System.out.print("2");
        List<ItemEntity> itemList = q2.getResultList();
        List<PurchaseEntity> purchaseList = q1.getResultList();
        System.out.print("3");

        for (int y = startYear; y <= endYear; y++) {

            for (int m = startMonth - 1; m <= endMonth - 1; m++) {
                Integer sales = 0;
                Double revenue = 0D;
                Double cost = 0D;
                System.out.print("loop");
                for (PurchaseEntity p : purchaseList) {
                    System.out.print("looploop1");
                    Long orderId = p.getOrderId();
                    OrderEntity order = em.find(OrderEntity.class, orderId);
                    ItemEntity item1 = em.find(ItemEntity.class, order.getItemId());
                    System.out.print("looploop2");
                    if (item1.getId().equals(item.getId()) && p.getPurchasedDate().get(Calendar.MONTH) == m
                            && p.getPurchasedDate().get(Calendar.YEAR) == y) {
                        sales += p.getQuantity();
                        revenue += p.getTotalPrice();
                        cost += p.getQuantity() * item.getCost();
                        System.out.print("looploop3");
                    }
                }
                Double profit = revenue - cost;
                totalSales += sales;
                totalRevenue += revenue;
                totalCost += cost;
                totalProfit += profit;
                int n = m + 1;
                table.addCell(y + "-" + n);
                table.addCell(sales.toString());
                table.addCell(revenue.toString());
                table.addCell(cost.toString());
                table.addCell(profit.toString());
            }
        }
        document.add(table);

        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        PdfPTable table2 = new PdfPTable(5);
        table2.getDefaultCell().setBorder(0);

        table2.addCell(" ");
        table2.addCell(totalSales.toString());
        table2.addCell(totalRevenue.toString());
        table2.addCell(totalCost.toString());
        table2.addCell(totalProfit.toString());

        document.add(table2);
        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));

        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("Copyright  2015 All rights reserved | WineXpress",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, BaseColor.BLACK)));
        document.close();
        FileOutputStream fos = new FileOutputStream(RESULT);
        fos.write(baos.toByteArray());
        fos.close();
        System.out.println("created");

        Calendar generatedTime = Calendar.getInstance();
        ReportEntity report = new ReportEntity("ProductReport-" + item.getId() + "-" + reportTitle,
                item.getId().toString(), RESULT, generatedTime);
        em.persist(report);
        em.flush();

    } catch (Exception e) {
    }
}

From source file:sipl.recursos.GenerarPDFGrafica.java

private void addTitlePage(Document document)
        throws DocumentException, MalformedURLException, BadElementException, IOException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);// w w w. java2  s .c  om
    preface.add(new Paragraph(Titulo, catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph(
            "Reporte generado por: " + user.getNombre() + " " + user.getApellido() + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("Este documento es creado a peticin del autor", smallBold));

    addEmptyLine(preface, 6);
    Image img = Image.getInstance(direc + "img//logo_unab.jpg");
    img.scaleAbsolute(70, 100);
    img.setAlignment(Image.ALIGN_CENTER);
    Chunk c = new Chunk(img, 0, 0);
    preface.add(c);
    document.add(preface);
    document.newPage();
    Paragraph preface1 = new Paragraph();
    preface1.add(new Paragraph("Grfica", smallBold));
    addEmptyLine(preface1, 20);
    img = Image.getInstance(imgG);
    img.scaleAbsolute(400, 300);
    img.setAlignment(Image.ALIGN_CENTER);
    c = new Chunk(img, 0, 0);
    preface1.add(c);
    document.add(preface1);
    document.newPage();
}

From source file:sipl.recursos.GenerarPDFListar.java

private void addTitlePage(Document document)
        throws DocumentException, MalformedURLException, BadElementException, IOException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);//from  ww  w . j  a  v  a2  s  .  c  o m
    preface.add(new Paragraph(Titulo, catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph(
            "Reporte generado por: " + user.getNombre() + " " + user.getApellido() + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("Este documento es creado a peticin del autor", smallBold));
    addEmptyLine(preface, 6);
    Image img = Image.getInstance(direc + "img//logo_unab.jpg");
    img.scaleAbsolute(70, 100);
    img.setAlignment(Image.ALIGN_CENTER);
    Chunk c = new Chunk(img, 0, 0);
    preface.add(c);
    document.add(preface);
    document.newPage();
}

From source file:sipl.recursos.GenerarPDFtipomaterial.java

private static void addTitlePage(Document document)
        throws DocumentException, MalformedURLException, BadElementException, IOException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);//ww  w.  j ava2 s  .  c  o  m
    preface.add(new Paragraph(Titulo, catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph(
            "Reporte generado por: " + user.getNombre() + " " + user.getApellido() + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("Este documento es creado a peticin del autor", smallBold));

    addEmptyLine(preface, 6);
    Image img = Image.getInstance(direc + "img//logo_unab.jpg");
    img.scaleAbsolute(70, 100);
    img.setAlignment(Image.ALIGN_CENTER);
    Chunk c = new Chunk(img, 0, 0);
    preface.add(c);
    document.add(preface);
    document.newPage();
    Paragraph preface1 = new Paragraph();
    preface1.add(new Paragraph("Grfica", smallBold));
    addEmptyLine(preface1, 20);
    img = Image.getInstance(imgG);
    img.scaleAbsolute(400, 300);
    img.setAlignment(Image.ALIGN_CENTER);
    c = new Chunk(img, 0, 0);
    preface1.add(c);
    document.add(preface1);
    document.newPage();
}

From source file:Software_Jframes.chart.java

void print_pdf_report(JTable jTable5) {
    Access ac = new Access();
    try {// ww w .j ava 2s . com
        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:src.servlets.ManageAdmin.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from w w  w  .j  a v a 2  s .c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Map m = request.getParameterMap();
    if (m.containsKey("GetPDF")) {
        try {
            String Report = getServletContext().getRealPath("") + "admin\\PDF_Report.pdf";

            FileOutputStream file = new FileOutputStream(Report);
            Document document = new Document();
            document.addAuthor("K00140908");
            PdfWriter.getInstance(document, file);
            ///////////////////////ADDING THE FILES TO PDF////////////////////
            //Inserting Image in PDF
            String uploadPath = getServletContext().getRealPath("") + "images\\logo.gif";

            Image img = Image.getInstance(uploadPath);

            img.scaleAbsolute(120f, 60f);// width,height of image in float

            //            Inserting Title in PDF  ORIGINAL
            //            Font fontTitle=new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.WHITE);
            //            Chunk title=new Chunk("PDF GENERATION in Java with iText", fontTitle);
            //            title.setBackground(new BaseColor(255,102,0), 1f, 1f, 1f, 3f);
            //            title.setLineHeight(30f);
            //            title.setUnderline(BaseColor.BLACK,5f,0.5f,2f,0.5f,PdfContentByte.LINE_CAP_ROUND);
            Font fontTitle = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);
            Chunk title = new Chunk("Lit Realty System Report", fontTitle);
            title.setLineHeight(30f);

            //Inserting Table in PDF
            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(100); // Sets the width percentage that the table will occupy in the page
            table.setSpacingAfter(10f);
            table.setSpacingBefore(15f);
            table.setWidths(new float[] { 2f, 2f, 2f }); // Sets relative width of table

            Font fontHeader = new Font(Font.FontFamily.HELVETICA, 15, Font.BOLD, BaseColor.BLUE);
            PdfPCell headercell = new PdfPCell(new Phrase("Property Photo", fontHeader)); // Creates new cell in table
            headercell.setBackgroundColor(new BaseColor(230, 230, 243));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            headercell = new PdfPCell(new Phrase("Property ID", fontHeader));
            headercell.setBackgroundColor(new BaseColor(233, 233, 233));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            headercell = new PdfPCell(new Phrase("Price", fontHeader));
            headercell.setBackgroundColor(new BaseColor(233, 233, 233));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            PdfPCell cell1 = new PdfPCell(img, false);

            table.addCell(cell1);
            table.addCell("134000");
            table.addCell("213445");
            table.addCell("134000");

            //Inserting List
            com.itextpdf.text.List list = new com.itextpdf.text.List(true, 30);
            list.add(new ListItem("Example1"));
            list.add(new ListItem("Example2"));
            list.add(new ListItem("Example3"));

            //Adding elements into PDF Document
            document.open();

            document.add(img);
            document.add(title);

            document.add(Chunk.NEWLINE);
            document.add(table);

            document.newPage();
            document.add(new Chunk("List of Examples").setUnderline(+1f, -5f));
            document.add(list);

            document.newPage();
            document.add(new Chunk("List of Examples").setUnderline(+1f, -5f));
            document.add(list);

            document.newPage();
            document.add(new Chunk("List of Properts By Agent X").setUnderline(+1f, -5f));
            //////////////////////GET Propertys From Entity///////////////
            List<Properties> allPropertiesList = PropertiesDB.getAllProperties();

            PdfPTable propertyTable = new PdfPTable(3);
            PdfPCell propertyHeadingcell1 = new PdfPCell(new Phrase("Photo"));
            PdfPCell propertyHeadingcell2 = new PdfPCell(new Phrase("Property ID"));
            PdfPCell propertyHeadingcell3 = new PdfPCell(new Phrase("Price"));

            propertyHeadingcell1.setBorder(Rectangle.NO_BORDER);
            propertyHeadingcell2.setBorder(Rectangle.NO_BORDER);
            propertyHeadingcell3.setBorder(Rectangle.NO_BORDER);

            propertyTable.addCell(propertyHeadingcell1);
            propertyTable.addCell(propertyHeadingcell2);
            propertyTable.addCell(propertyHeadingcell3);

            document.add(Chunk.NEWLINE);

            String uploadPathforPropertyPhoto = getServletContext().getRealPath("")
                    + "images\\properties\\thumbnails\\";

            Image propertyThumbnail;

            img.scaleAbsolute(120f, 60f);// width,height of image in float

            for (Properties anProperty : allPropertiesList) {
                propertyThumbnail = Image.getInstance(uploadPathforPropertyPhoto + anProperty.getPhoto());
                PdfPCell propertycell1 = new PdfPCell(propertyThumbnail, false);
                propertycell1.setPaddingBottom(20);
                PdfPCell propertycell2 = new PdfPCell(new Phrase(anProperty.getListingNum().toString()));
                PdfPCell propertycell3 = new PdfPCell(new Phrase(anProperty.getPrice().toString()));

                propertycell1.setBorder(Rectangle.NO_BORDER);
                propertycell2.setBorder(Rectangle.NO_BORDER);
                propertycell3.setBorder(Rectangle.NO_BORDER);

                propertyTable.addCell(propertycell1);
                propertyTable.addCell(propertycell2);
                propertyTable.addCell(propertycell3);

            }
            document.add(Chunk.NEWLINE);
            document.add(propertyTable);
            //////////////////////GET Propertys From Entity///////////////

            document.close();
            file.close();

            System.out.println("Pdf created successfully ! :)");

            String filePath = Report;
            File downloadFile = new File(filePath);
            FileInputStream inStream = new FileInputStream(downloadFile);

            // if you want to use a relative path to context root:
            String relativePath = getServletContext().getRealPath("");
            System.out.println("relativePath = " + relativePath);

            // obtains ServletContext
            ServletContext context = getServletContext();

            // gets MIME type of the file
            String mimeType = context.getMimeType(filePath);
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }
            System.out.println("MIME type: " + mimeType);

            // modifies response
            response.setContentType(mimeType);
            response.setContentLength((int) downloadFile.length());

            // forces download
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
            response.setHeader(headerKey, headerValue);

            // obtains response's output stream
            OutputStream outStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }

            inStream.close();
            outStream.close();
            /////////////////

            processRequest(request, response);
        } catch (DocumentException ex) {
            Logger.getLogger(ManageAdmin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:Tables.Printer.java

public void header(Document doc, String reportType) throws DocumentException {
    String companyInfo = "NJEIFORBI ACCOUNTS BOOK \nFINANCIAL REPORTS";

    Paragraph newLine = new Paragraph("\n");
    doc.add(newLine);/* w w  w. j  av a2 s .co m*/

    // add the paragraph to the document            

    /*new heading*/
    //adding the company logo.
    try {
        Image img = Image.getInstance(this.companyLogo);
        img.scaleAbsolute(80f, 80f);
        img.setAlt("Unity Systems");
        img.setAlignment(Element.ALIGN_CENTER);

        //            Image img = Image.getInstance(this.companyLogo);

        /*with the next 3 lines oc code, the image will align at the center of the page.*/
        //            img.setAbsolutePosition(
        //                (PageSize.A4.getWidth() - img.getScaledWidth()) / 2,
        //                (PageSize.A4.getHeight() - img.getScaledHeight()) / 2);

        doc.add(img);
    } catch (IOException | DocumentException ex) {
        Dialogs.create().title("Logo Not found").message(
                "The Company's logo has not been located. So the printout will be without the logo of the company")
                .showError();
        ex.printStackTrace();
    }

    Paragraph companyName = new Paragraph(companyInfo, this.companyNameFont);
    Paragraph reportTitle = new Paragraph(reportType, this.reportTitleFont);

    companyName.setAlignment(Element.ALIGN_CENTER);
    reportTitle.setAlignment(Element.ALIGN_CENTER);
    newLine.setAlignment(Element.ALIGN_CENTER);

    doc.add(companyName);
    doc.add(reportTitle);
    doc.add(newLine);

    /*new heading ends*/

}