Example usage for com.lowagie.text Image getInstance

List of usage examples for com.lowagie.text Image getInstance

Introduction

In this page you can find the example usage for com.lowagie.text Image getInstance.

Prototype

public static Image getInstance(Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:org.oss.pdfreporter.pdf.Page.java

License:Open Source License

@Override
public void drawCropped(IImage image, float xoffset, float yoffset, float x, float y, float width, float height)
        throws DocumentException {
    try {/*ww  w. ja  va2  s  .  co  m*/

        Image pdfImage = getImage(image);
        PdfTemplate t = delegate.getPdfWriter().getDirectContent().createTemplate(width, height);
        t.addImage(pdfImage, pdfImage.getWidth(), 0, 0, pdfImage.getHeight(), xoffset,
                -yoffset + height - pdfImage.getHeight());
        pdfImage = Image.getInstance(t);

        pdfImage.setAbsolutePosition(x, y);
        delegate.addImage(pdfImage);
    } catch (Exception e) {
        throw new DocumentException(e);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.helper.RTFImageCache.java

License:Open Source License

/**
 * Helperfunction to extract an image from an imagereference. If the image is contained as java.awt.Image object only,
 * the image is recoded into an PNG-Image.
 *
 * @param reference/*from  ww w  . j av  a  2s .c  om*/
 *          the image reference.
 * @return an image.
 * @throws com.lowagie.text.DocumentException
 *           if no PDFImageElement could be created using the given ImageReference.
 * @throws java.io.IOException
 *           if the image could not be read.
 */
public Image getImage(final ImageContainer reference) throws DocumentException, IOException {
    if (reference == null) {
        throw new NullPointerException();
    }

    Object identity = null;
    java.awt.Image image = null;
    if (reference instanceof URLImageContainer) {
        final URLImageContainer urlImageContainer = (URLImageContainer) reference;
        final ResourceKey url = urlImageContainer.getResourceKey();
        if (url != null && urlImageContainer.isLoadable()) {
            identity = url;
            final Image cached = (Image) cachedImages.get(identity);
            if (cached != null) {
                return cached;
            }

            try {
                final ResourceData resourceData = resourceManager.load(url);
                final byte[] data = resourceData.getResource(resourceManager);
                final Image itextimage = Image.getInstance(data);
                cachedImages.put(identity, itextimage);
                return itextimage;
            } catch (ResourceException re) {
                RTFImageCache.logger.info("Caught illegal Image, will recode to PNG instead", re);
            } catch (BadElementException be) {
                RTFImageCache.logger.info("Caught illegal Image, will recode to PNG instead", be);
            } catch (IOException ioe) {
                RTFImageCache.logger.info("Unable to read the raw-data, will try to recode image-data.", ioe);
            }

            try {
                final Resource resource = resourceManager.create(url, null, Image.class);
                image = (java.awt.Image) resource.getResource();
            } catch (ResourceException re) {
                RTFImageCache.logger.info("Caught illegal Image, will try to find local instance", re);
            }
        }
    }

    if (reference instanceof LocalImageContainer && image == null) {
        final LocalImageContainer localImageContainer = (LocalImageContainer) reference;
        image = localImageContainer.getImage();
        if (image != null) {
            // check, if the content was cached ...
            identity = localImageContainer.getIdentity();
            if (identity != null) {
                final Image cachedImage = (Image) cachedImages.get(identity);
                if (cachedImage != null) {
                    return cachedImage;
                }
            }

        }
    }
    if (image == null) {
        return null;
    }

    final WaitingImageObserver obs = new WaitingImageObserver(image);
    obs.waitImageLoaded();

    try {
        final byte[] data = RenderUtility.encodeImage(image);
        final Image itextimage = Image.getInstance(data);
        if (identity != null) {
            cachedImages.put(identity, itextimage);
        }
        return itextimage;
    } catch (UnsupportedEncoderException uee) {
        logger.warn("Assertation-Failure: PNG encoding failed.", uee);
        return null;
    }

}

From source file:org.posterita.businesslogic.administration.CustomerManager.java

License:Open Source License

public static String fidelityCard(Properties ctx, ArrayList<CustomerBean> customerList)
        throws OperationException {
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    boolean shouldPrintCard = false;

    for (CustomerBean b : customerList) {
        if (b.getIsActive()) {
            shouldPrintCard = true;//from  w  ww .  j  a va2s  .co  m
            break;
        }
    }

    if (!shouldPrintCard) {
        throw new NoCustomerFoundException("Cannot print fidelity card. Cause no active customers were found.");
    }

    Document document = new Document(PageSize.A4, 3, 3, 2, 4);//l,r,t,b

    try {
        //          step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();

        PdfPTable main = new PdfPTable(2);
        main.setWidthPercentage(71.0f);
        main.getDefaultCell().setBorderColor(Color.gray);

        PdfPCell cell = new PdfPCell();
        cell.setMinimumHeight(150.0f);

        Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.BOLD);
        //Font spaceFont = FontFactory.getFont(FontFactory.HELVETICA,6,Font.BOLD);
        //Font spaceFont2 = FontFactory.getFont(FontFactory.HELVETICA,15,Font.BOLD);

        //ResourceBundle rb = ResourceBundle.getBundle("MessageResources");

        for (CustomerBean bean : customerList) {
            if (bean.getIsActive()) {
                String name = bean.getPartnerName();
                String name1 = "";
                String add2 = "";
                String add1 = "";
                String city = "";

                if (bean.getAddress1() != null)
                    add1 = bean.getAddress1();

                if (bean.getAddress2() != null)
                    add2 = bean.getAddress2();

                if (bean.getCity() != null)
                    city = bean.getCity();

                String Address = "   " + add1;
                String Add2 = " " + add2;
                String Add3 = "   " + city;

                String BackPriv1Path = PathInfo.PROJECT_HOME + "/images/BackPriv1.jpg";
                String backPriv2Path = PathInfo.PROJECT_HOME + "/images/backPriv2.jpg";
                String frontImgPath = PathInfo.PROJECT_HOME + "/images/pc.png";

                float WIDTH = 205;
                float HEIGHT = 135;

                Image Back1 = Image.getInstance(BackPriv1Path);
                Back1.scaleAbsolute(WIDTH - 40, HEIGHT / 3);
                Image Back2 = Image.getInstance(backPriv2Path);
                Back2.scaleAbsolute(WIDTH, HEIGHT / 3);
                Image frontImg = Image.getInstance(frontImgPath);
                frontImg.scaleAbsolute(WIDTH, HEIGHT);

                if (bean.getSurname() != null && bean.getSurname().trim().length() > 0)
                    name1 = "   " + name + " " + name1 + bean.getSurname();

                byte[] barcode = BarcodeManager.getBarcodeAsByte(bean.getBpartnerId().toString());
                Image barcodeImg = Image.getInstance(barcode);
                barcodeImg.setRotation(1.57f);
                barcodeImg.scaleAbsolute(HEIGHT - 55f, WIDTH / 5);

                //document.add(barcodeImg);
                PdfPTable card = new PdfPTable(2);
                card.getDefaultCell().setBorderWidth(0.0f);

                PdfPCell c = null;
                card.setWidthPercentage(50.0f);

                PdfPTable t = new PdfPTable(1);
                PdfPTable nametable = new PdfPTable(1);

                c = new PdfPCell(Back1);
                c.setBorderWidth(0.0f);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(name1, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Address, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Add2, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Add3, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                //nametable.getDefaultCell();
                nametable.getDefaultCell().setBorderWidth(0.0f);
                nametable.setHorizontalAlignment(Element.ALIGN_CENTER);
                card.addCell(nametable);

                c = new PdfPCell(barcodeImg);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                c.setHorizontalAlignment(Element.ALIGN_RIGHT);
                c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                c.setPadding(5.0f);
                card.addCell(c);

                c = new PdfPCell(Back2);
                c.setBorderWidth(0.0f);
                c.setColspan(2);
                card.addCell(c);

                c = new PdfPCell(new Phrase(name1, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                c = new PdfPCell(new Phrase(Address, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                c = new PdfPCell(new Phrase(Add3, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                PdfPTable card1 = new PdfPTable(1);
                card.getDefaultCell().setBorderWidth(0.0f);

                PdfPCell c1 = null;
                card.setWidthPercentage(50.0f);

                c1 = new PdfPCell(frontImg);
                c1.setBorderWidth(0.0f);
                card1.addCell(c1);

                main.addCell(card);
                main.addCell(card1);
            }

        }
        document.add(main);

    }
    // TODO handle the following exception neatly
    catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
    return reportName;
}

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String getCompleteOrderPDFReport(Properties ctx, int orderId, String trxName)
        throws OperationException {
    String docStatus = null;/*from   ww w .  j  a v a2 s  .c o m*/
    String dateOrdered = null;
    String orderType = null;
    String orgName = null;
    String orgAddress = null;
    String salesRep = null;
    String paymentBy = null;
    String customerName = null;
    String customerAddress = null;
    String documentNo = null;
    String currency = "Rs ";
    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol() + " ";
    MOrder order = new MOrder(ctx, orderId, trxName);

    // getting payment info
    int[] invoiceIds = MInvoice.getAllIDs(MInvoice.Table_Name,
            "AD_CLIENT_ID=" + Env.getAD_Client_ID(ctx) + " and C_ORDER_ID=" + order.get_ID(), null);
    double paymentByCash = 0.0;
    double paymentByCard = 0.0;
    double paymentByCheque = 0.0;

    MInvoice invoice = null;
    String paymentRule = null;
    boolean isMixed = false;

    for (int i = 0; i < invoiceIds.length; i++) {
        invoice = new MInvoice(ctx, invoiceIds[i], trxName);

        if (i == 0) {
            paymentRule = invoice.getPaymentRule();
        } else {
            if (!paymentRule.equalsIgnoreCase(invoice.getPaymentRule())) {
                isMixed = true;
            }
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Cash)) {
            paymentByCash += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CASH;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_CreditCard)) {
            paymentByCard += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CARD;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_DirectDebit)) {
            paymentByCard += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CARD;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Check)) {
            paymentByCheque += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CHEQUE;
        }

    } // for

    if (isMixed) {
        paymentBy = "Mixed (Cash:" + formatter.format(paymentByCash) + " Card:"
                + formatter.format(paymentByCard) + " Cheque:" + formatter.format(paymentByCheque) + ")";
    }

    // getting orgInfo
    MOrg org = new MOrg(ctx, order.getAD_Org_ID(), trxName);
    int location_id = org.getInfo().getC_Location_ID();
    MLocation location = new MLocation(ctx, location_id, trxName);

    orgName = org.getName();

    String address1 = (location.getAddress1() == null) ? " " : location.getAddress1();
    String address2 = (location.getAddress2() == null) ? " " : location.getAddress2();
    orgAddress = (address1 + " " + address2).trim();

    // getting order type
    orderType = order.getOrderType();

    // getting orderInfo
    docStatus = order.getDocStatusName();
    documentNo = order.getDocumentNo();

    Date d = new Date(order.getCreated().getTime());
    SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateOrdered = s.format(d);

    // getting salesrep
    int saleRep_id = order.getSalesRep_ID();
    MUser user = new MUser(ctx, saleRep_id, trxName);
    salesRep = user.getName();

    // getting customer info
    int bpartner_id = order.getBill_BPartner_ID();
    BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName);

    String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName();
    String name2 = (bean.getName2() == null) ? " " : bean.getName2();
    customerName = (name1 + " " + name2).trim();

    address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1();
    address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2();
    customerAddress = (address1 + " " + address2).trim();

    ArrayList<WebOrderLineBean> orderLineList = POSManager.populateOrderLines(ctx, order);

    // ----------------------------------- generating pdf
    // --------------------------------------
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

    Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 10);

    float cellBorderWidth = 0.0f;

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document

        Image logo = null;

        String imageURI = PathInfo.PROJECT_HOME + "images/logo.gif";
        // "images/pos/openBLUE_POS_Logo.gif";

        try {
            byte logoData[] = OrganisationManager.getLogo(ctx, null);
            logo = Image.getInstance(logoData);
        } catch (LogoException ex) {
            logo = Image.getInstance(imageURI);
        }

        logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight());
        document.add(logo);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = null;

        //
        table.getDefaultCell().setPadding(5.0f);
        table.setWidthPercentage(100.0f);

        // header cell
        Paragraph title = new Paragraph();
        title.add(new Chunk(orgName, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk(orgAddress, subtitleFont));

        // cell = new PdfPCell(new Paragraph(new
        // Chunk("Title1",titleFont)));
        cell = new PdfPCell(title);

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setFixedHeight(logo.getHeight());
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // doc type
        cell = new PdfPCell(new Paragraph(new Chunk(orderType, titleFont)));

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 1
        cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 2
        cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 3
        cell = new PdfPCell(new Paragraph(new Chunk("Ref No: " + documentNo, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 4
        cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 5
        cell = new PdfPCell(new Paragraph(new Chunk("Payment By: " + paymentBy, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 6
        cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // ------------------------------------------------------
        cell = new PdfPCell();
        cell.setColspan(2);
        cell.setBorderWidth(cellBorderWidth);

        PdfPTable t = new PdfPTable(6);
        t.getDefaultCell().setPadding(3.0f);
        t.setWidthPercentage(100.0f);

        int[] widths = { 1, 4, 1, 2, 2, 2 };
        t.setWidths(widths);

        // setting headers
        t.addCell(new Paragraph(new Chunk("SerNo", headerFont)));
        t.addCell(new Paragraph(new Chunk("Name", headerFont)));
        t.addCell(new Paragraph(new Chunk("Qty", headerFont)));
        t.addCell(new Paragraph(new Chunk("Price", headerFont)));
        t.addCell(new Paragraph(new Chunk("VAT", headerFont)));
        t.addCell(new Paragraph(new Chunk("Total", headerFont)));

        // setting table data
        // --------------------------------writing table
        // data------------------------------
        int serNo = 0;
        int totalQty = 0;
        double totalAmt = 0.0;
        double totalTaxAmt = 0.0;
        double grandTotal = 0.0;

        BigDecimal qty = null;
        BigDecimal lineAmt = null;
        BigDecimal taxAmt = null;
        BigDecimal lineTotalAmt = null;

        for (WebOrderLineBean orderlineBean : orderLineList) {
            serNo++;
            qty = orderlineBean.getQtyOrdered();
            lineAmt = orderlineBean.getLineNetAmt();
            taxAmt = orderlineBean.getTaxAmt();
            lineTotalAmt = orderlineBean.getLineTotalAmt();

            totalQty += qty.intValue();
            totalAmt += lineAmt.doubleValue();
            totalTaxAmt += taxAmt.doubleValue();
            grandTotal += lineTotalAmt.doubleValue();

            t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont)));
            t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(lineAmt.doubleValue()), simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(taxAmt.doubleValue()), simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(lineTotalAmt.doubleValue()), simpleFont)));
        }
        // -----------------------------------------------------------------------------------

        // setting table footer
        t.getDefaultCell().setBackgroundColor(new Color(240, 240, 240));

        PdfPCell c = new PdfPCell(new Paragraph(new Chunk("ORDER TOTAL", headerFont)));
        c.setColspan(2);
        c.setBackgroundColor(new Color(240, 240, 240));
        t.addCell(c);

        t.addCell(new Paragraph(new Chunk(totalQty + "", simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalAmt), simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalTaxAmt), simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(grandTotal), simpleFont)));

        t.setSplitRows(true);
        cell.addElement(t);
        // ------------------------------------------------------

        // table.addCell(cell);
        table.setSplitRows(true);

        document.add(table);
        document.add(t);

    } catch (Exception e) {
        throw new OperationException(e);
    }

    // step 5: we close the document
    document.close();

    return reportName;
}

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String getShipmentPDFReport(Properties ctx, int minoutId, String trxName)
        throws OperationException {
    String docStatus = null;/* ww w  .ja v  a 2s . c  om*/
    String dateOrdered = null;
    String docType = null;
    String orgName = null;
    String orgAddress = null;
    String salesRep = null;
    String phone = "      ";
    String fax = "       ";

    String customerName = null;
    String customerAddress = null;
    String documentNo = null;

    MInOut minout = MinOutManager.loadMInOut(ctx, minoutId, trxName);

    // getting orgInfo
    MOrg org = new MOrg(ctx, minout.getAD_Org_ID(), trxName);
    int location_id = org.getInfo().getC_Location_ID();
    MLocation location = new MLocation(ctx, location_id, trxName);
    MBPartner orgPartner = new MBPartner(ctx, org.getLinkedC_BPartner_ID(trxName), trxName);
    MBPartnerLocation meLocation[] = MBPartnerLocation.getForBPartner(ctx, orgPartner.get_ID());

    if (meLocation.length != 1)
        throw new OperationException("Should have only 1 location for organisation business partner!!");

    MBPartnerLocation orgLocation = meLocation[0];

    if (orgLocation.getPhone() != null)
        phone = orgLocation.getPhone();

    if (orgLocation.getFax() != null)
        fax = orgLocation.getFax();
    ;

    orgName = org.getName();

    String address1 = (location.getAddress1() == null) ? " " : location.getAddress1();
    String address2 = (location.getAddress2() == null) ? " " : location.getAddress2();
    orgAddress = (address1 + " " + address2).trim();

    // getting order type
    MDocType doctype = MDocType.get(ctx, minout.getC_DocType_ID());
    docType = doctype.getName();

    // getting orderInfo
    docStatus = minout.getDocStatusName();
    documentNo = minout.getDocumentNo();

    Date d = new Date(minout.getCreated().getTime());
    SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateOrdered = s.format(d);

    // getting salesrep
    int saleRep_id = minout.getSalesRep_ID();
    MUser user = new MUser(ctx, saleRep_id, trxName);
    salesRep = user.getName();

    // getting customer info
    int bpartner_id = minout.getC_BPartner_ID();
    BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName);

    String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName();
    String name2 = (bean.getName2() == null) ? " " : bean.getName2();
    customerName = (name1 + " " + name2).trim();

    address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1();
    address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2();
    customerAddress = (address1 + " " + address2).trim();

    ArrayList<WebMinOutLineBean> orderLineList = MinOutManager.getWebMinOutLines(ctx, minout);

    // ----------------------------------- generating pdf
    // --------------------------------------
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

    Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 10);

    float cellBorderWidth = 0.0f;

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document

        Image logo = null;

        // TODO: make this part dynamic <------------------------------
        // IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!
        String imageURI = PathInfo.PROJECT_HOME + "images/pos/openBLUE_POS_Logo.gif";
        logo = Image.getInstance(imageURI);

        // MAttachment attachment = new
        // MAttachment(ctx,MOrg.Table_ID,org.getID(),null);
        // logo = Image.getInstance(attachment.getEntries()[0].getData());

        try {
            byte logoData[] = OrganisationManager.getLogo(ctx, null);
            logo = Image.getInstance(logoData);
        } catch (LogoException ex) {
            logo = Image.getInstance(imageURI);
        }

        logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight());
        document.add(logo);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = null;

        //
        table.getDefaultCell().setPadding(5.0f);
        table.setWidthPercentage(100.0f);

        // header cell
        Paragraph title = new Paragraph();
        title.add(new Chunk(orgName, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk(orgAddress, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk("Phone: " + phone, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk("Fax: " + fax, subtitleFont));

        // cell = new PdfPCell(new Paragraph(new
        // Chunk("Title1",titleFont)));
        cell = new PdfPCell(title);

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setFixedHeight(logo.getHeight());
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // doc type
        cell = new PdfPCell(new Paragraph(new Chunk(docType, titleFont)));

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 1
        cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 2
        cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 3
        cell = new PdfPCell(new Paragraph(new Chunk("No: " + documentNo, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 4
        cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        /*
         * //row 5 cell = new PdfPCell(new Paragraph(new Chunk("Payment By:
         * "+paymentBy,headerFont))); cell.setColspan(2);
         * cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
         * cell.setBorderWidth(cellBorderWidth); table.addCell(cell);
         */

        // row 6
        cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // ------------------------------------------------------
        cell = new PdfPCell();
        cell.setColspan(2);
        cell.setBorderWidth(cellBorderWidth);

        PdfPTable t = new PdfPTable(3);
        t.getDefaultCell().setPadding(3.0f);
        t.setWidthPercentage(100.0f);

        int[] widths = { 1, 10, 1 };
        t.setWidths(widths);

        // setting headers
        t.addCell(new Paragraph(new Chunk("SerNo", headerFont)));
        t.addCell(new Paragraph(new Chunk("Name", headerFont)));
        t.addCell(new Paragraph(new Chunk("Qty", headerFont)));

        // setting table data
        // --------------------------------writing table
        // data------------------------------
        int serNo = 0;

        BigDecimal qty = null;

        for (WebMinOutLineBean orderlineBean : orderLineList) {
            serNo++;
            qty = orderlineBean.getQtyOrdered();

            t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont)));
            t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont)));
        }
        // -----------------------------------------------------------------------------------

        // table.addCell(cell);
        table.setSplitRows(true);

        document.add(table);
        document.add(t);

    } catch (Exception e) {
        throw new OperationException(e);
    }

    // step 5: we close the document
    document.close();

    return reportName;
}

From source file:org.posterita.core.PDFReportGenerator.java

License:Open Source License

protected Image getTextAsImage(String text) throws OperationException {
    try {//w w  w .j  a v a 2  s. c o m
        PdfTemplate template = writer.getDirectContent().createTemplate(20, 20);
        //BaseFont bf = BaseFont.createFont("Helvetica", "winansi", false); 
        BaseFont bf = HEADER_FONT.getBaseFont();
        float size = 10;
        float width = bf.getWidthPoint(text, size);
        template.beginText();
        //template.setRGBColorFillF(1, 1, 1);
        template.setFontAndSize(bf, size);
        template.setTextMatrix(0, 2);
        template.showText(text);
        template.endText();
        template.setWidth(width);
        template.setHeight(size + 2);
        // make an Image object from the template
        Image img = Image.getInstance(template);
        img.setAlignment(Image.RIGHT | Image.TEXTWRAP);

        return img;

    } catch (Exception e) {
        throw new OperationException(e);
    }
}

From source file:org.primefaces.showcase.view.data.dataexporter.CustomizedDocumentsView.java

License:Open Source License

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();/*w ww.java  2 s . co  m*/
    pdf.setPageSize(PageSize.A4);

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    String logo = externalContext.getRealPath("") + File.separator + "resources" + File.separator + "demo"
            + File.separator + "images" + File.separator + "prime_logo.png";

    pdf.add(Image.getInstance(logo));
}

From source file:org.revager.export.PDFPageEventHelper.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    int columnNumber;

    try {//from   w  ww .j av  a 2 s.co  m
        Rectangle page = document.getPageSize();
        float pageWidth = page.getWidth() - document.leftMargin() - document.rightMargin();

        /*
         * Write marks
         */
        setMarks(writer, document);

        /*
         * Define fonts
         */
        headBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font headFont = new Font(headBaseFont, headFontSize);

        footBaseFont = BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font footFont = new Font(footBaseFont, footFontSize);

        /*
         * Cell fill for space between head/foot and content
         */
        PdfPCell cellFill = new PdfPCell();
        cellFill.setMinimumHeight(PDFTools.cmToPt(0.8f));
        cellFill.setBorderWidth(0);

        /*
         * Write head
         */
        if (headLogoPath != null) {
            columnNumber = 2;
        } else {
            columnNumber = 1;
        }

        PdfPTable head = new PdfPTable(columnNumber);

        Phrase phraseTitle = new Phrase(headTitle, headFont);

        PdfPCell cellTitle = new PdfPCell(phraseTitle);
        cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT);
        cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cellTitle.setPaddingTop(0);
        cellTitle.setPaddingBottom(PDFTools.cmToPt(0.2f));
        cellTitle.setPaddingLeft(0);
        cellTitle.setPaddingRight(0);
        cellTitle.setBorderWidthTop(0);
        cellTitle.setBorderWidthBottom(0.5f);
        cellTitle.setBorderWidthLeft(0);
        cellTitle.setBorderWidthRight(0);

        head.addCell(cellTitle);

        if (headLogoPath != null) {
            Image headLogo = Image.getInstance(headLogoPath);
            headLogo.scaleToFit(PDFTools.cmToPt(5.0f), PDFTools.cmToPt(1.1f));

            PdfPCell cellLogo = new PdfPCell(headLogo);
            cellLogo.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cellLogo.setVerticalAlignment(Element.ALIGN_BOTTOM);
            cellLogo.setPaddingTop(0);
            cellLogo.setPaddingBottom(PDFTools.cmToPt(0.15f));
            cellLogo.setPaddingLeft(0);
            cellLogo.setPaddingRight(0);
            cellLogo.setBorderWidthTop(0);
            cellLogo.setBorderWidthBottom(0.5f);
            cellLogo.setBorderWidthLeft(0);
            cellLogo.setBorderWidthRight(0);

            head.addCell(cellLogo);

            head.addCell(cellFill);
        }

        head.addCell(cellFill);

        head.setTotalWidth(pageWidth);
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        /*
         * Write foot
         */
        if (footText == null) {
            footText = " ";
        }

        PdfPTable foot = new PdfPTable(1);

        foot.addCell(cellFill);

        PdfPCell cellFootText = new PdfPCell(new Phrase(footText, footFont));
        cellFootText.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellFootText.setVerticalAlignment(Element.ALIGN_TOP);
        cellFootText.setPaddingTop(PDFTools.cmToPt(0.15f));
        cellFootText.setPaddingBottom(0);
        cellFootText.setPaddingLeft(0);
        cellFootText.setPaddingRight(0);
        cellFootText.setBorderWidthTop(0.5f);
        cellFootText.setBorderWidthBottom(0);
        cellFootText.setBorderWidthLeft(0);
        cellFootText.setBorderWidthRight(0);

        foot.addCell(cellFootText);

        /*
         * Print page numbers
         */
        PdfContentByte contentByte = writer.getDirectContent();
        contentByte.saveState();

        String text = MessageFormat.format(translate("Page {0} of") + " ", writer.getPageNumber());

        float textSize = footBaseFont.getWidthPoint(text, footFontSize);
        float textBase = document.bottom() - PDFTools.cmToPt(1.26f);
        contentByte.beginText();
        contentByte.setFontAndSize(footBaseFont, footFontSize);

        float adjust;
        if (footText.trim().equals("")) {
            adjust = (pageWidth / 2) - (textSize / 2) - footBaseFont.getWidthPoint("0", footFontSize);
        } else {
            adjust = 0;
        }

        contentByte.setTextMatrix(document.left() + adjust, textBase);
        contentByte.showText(text);
        contentByte.endText();
        contentByte.addTemplate(template, document.left() + adjust + textSize, textBase);

        contentByte.stroke();
        contentByte.restoreState();

        foot.setTotalWidth(pageWidth);
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExceptionConverter(e);
    }
}

From source file:org.saiku.web.rest.resources.ExporterResource.java

License:Apache License

/**
 * Export chart to a file.//www.  j  a  v a2s  .c  om
 * @summary Export Chart.
 * @param type The export type (png, svg, jpeg)
 * @param svg The SVG
 * @param size The size
 * @param name The name
 * @return A reponse containing the chart export.
 */
@POST
@Produces({ "image/*" })
@Path("/saiku/chart")
public Response exportChart(@FormParam("type") @DefaultValue("png") String type, @FormParam("svg") String svg,
        @FormParam("size") Integer size, @FormParam("name") String name) {
    try {
        final String imageType = type.toUpperCase();
        Converter converter = Converter.byType("PDF");
        if (converter == null) {
            throw new Exception("Image convert is null");
        }

        //             resp.setContentType(converter.getContentType());
        //             resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension());
        //             final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null;
        //             final String svgDocument = req.getParameter("svg");
        //             if (svgDocument == null)
        //             {
        //                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter");
        //                 return;
        //             }
        if (StringUtils.isBlank(svg)) {
            throw new Exception("Missing 'svg' parameter");
        }
        final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8"));
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        converter.convert(in, out, size);
        out.flush();
        byte[] doc = out.toByteArray();
        byte[] b = null;
        if (getVersion() != null && !getVersion().contains("EE")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            PdfReader reader = new PdfReader(doc);
            PdfStamper pdfStamper = new PdfStamper(reader, baos);

            URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png");
            Image image = Image.getInstance(dir_url);

            for (int i = 1; i <= reader.getNumberOfPages(); i++) {

                PdfContentByte content = pdfStamper.getOverContent(i);

                image.setAbsolutePosition(450f, 280f);
                /*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize
                   (1).getHeight() - image.getScaledHeight());*/
                //image.setAlignment(Image.MIDDLE);
                content.addImage(image);
            }
            pdfStamper.close();
            b = baos.toByteArray();
        } else {
            b = doc;
        }

        if (!type.equals("pdf")) {

            PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null);

            PDPageTree pdPages = document.getDocumentCatalog().getPages();
            PDPage page = pdPages.get(0);
            BufferedImage o = new PDFRenderer(document).renderImage(0);
            ByteArrayOutputStream imgb = new ByteArrayOutputStream();
            String ct = "";
            String ext = "";
            if (type.equals("png")) {
                ct = "image/png";
                ext = "png";
            } else if (type.equals("jpg")) {
                ct = "image/jpg";
                ext = "jpg";
            }
            ImageIO.write(o, type, imgb);
            byte[] outfile = imgb.toByteArray();
            if (name == null || name.equals("")) {
                name = "chart";
            }
            return Response.ok(outfile).type(ct)
                    .header("content-disposition", "attachment; filename = " + name + "." + ext)
                    .header("content-length", outfile.length).build();
        } else {
            if (name == null || name.equals("")) {
                name = "chart";
            }
            return Response.ok(b).type(converter.getContentType())
                    .header("content-disposition",
                            "attachment; filename = " + name + "." + converter.getExtension())
                    .header("content-length", b.length).build();
        }
    } catch (Exception e) {
        log.error("Error exporting Chart to  " + type, e);
        return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
    }
}

From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java

License:Educational Community License

public void addTitlePage(String evaltitle, String groupNames, String startDate, String endDate,
        String responseInformation, byte[] bannerImageBytes, String evalSystemTitle, String informationTitle) {
    try {//from  ww w. j  av  a  2s  .  c  o m
        float pagefooter = paragraphFont.getSize();

        PdfContentByte cb = pdfWriter.getDirectContent();

        float docMiddle = (document.right() - document.left()) / 2 + document.leftMargin();

        Paragraph emptyPara = new Paragraph(" ");
        emptyPara.setSpacingAfter(100.0f);

        // Title
        Paragraph titlePara = new Paragraph("\n\n\n" + evaltitle, frontTitleFont);
        titlePara.setAlignment(Element.ALIGN_CENTER);
        document.add(titlePara);

        // Groups

        Paragraph groupPara = new Paragraph(groupNames, frontAuthorFont);
        groupPara.setSpacingBefore(25.0f);
        groupPara.setAlignment(Element.ALIGN_CENTER);
        document.add(groupPara);

        // Little info area? I don't know, it was on the mockup though
        Paragraph infoPara = new Paragraph(informationTitle, frontInfoFont);
        infoPara.setAlignment(Element.ALIGN_CENTER);
        infoPara.setSpacingBefore(90.0f);
        document.add(infoPara);

        // Started on
        Paragraph startedPara = new Paragraph(startDate, frontInfoFont);
        startedPara.setAlignment(Element.ALIGN_CENTER);
        startedPara.setSpacingBefore(25.0f);
        document.add(startedPara);

        // Ended on
        Paragraph endedPara = new Paragraph(endDate, frontInfoFont);
        endedPara.setAlignment(Element.ALIGN_CENTER);
        endedPara.setSpacingBefore(25.0f);
        document.add(endedPara);

        // Reply Rate
        Paragraph replyRatePara = new Paragraph(responseInformation, frontInfoFont);
        replyRatePara.setAlignment(Element.ALIGN_CENTER);
        replyRatePara.setSpacingBefore(25.0f);
        document.add(replyRatePara);

        // Logo and Tagline
        cb.beginText();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 12);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, evalSystemTitle, docMiddle, document.bottom() + 20, 0);
        cb.endText();

        if (bannerImageBytes != null) {
            Image banner = Image.getInstance(bannerImageBytes);
            cb.addImage(banner, banner.getWidth(), 0, 0, banner.getHeight(),
                    docMiddle - (banner.getWidth() / 2), document.bottom() + 35);
        }

        document.newPage();

        responseArea = new ColumnText(cb);
        responseArea.setSimpleColumn(document.left(), document.top(), document.right() / 2,
                document.bottom() + pagefooter);
        responseArea.go();
    } catch (DocumentException | IOException de) {
        throw UniversalRuntimeException.accumulate(de, "Unable to create title page");
    }
}