Example usage for com.lowagie.text Rectangle Rectangle

List of usage examples for com.lowagie.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

From source file:displayStructureAsPDFTable.java

License:Open Source License

public void drawStructure(IAtomContainer mol, int cnt) {
    mol = addHeteroHydrogens(mol);/*  w  w w  . j a v  a2 s  .co  m*/

    // do aromaticity detection
    try {
        CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
        cdke.printStackTrace();
    }

    r2dm = new Renderer2DModel();
    renderer = new Renderer2D(r2dm);
    Dimension screenSize = new Dimension(this.width, this.height);
    setPreferredSize(screenSize);
    r2dm.setBackgroundDimension(screenSize); // make sure it is synched with the JPanel size
    setBackground(r2dm.getBackColor());

    try {
        StructureDiagramGenerator sdg = new StructureDiagramGenerator();
        sdg.setMolecule((IMolecule) mol);
        sdg.generateCoordinates();
        this.mol = sdg.getMolecule();

        r2dm.setDrawNumbers(false);
        r2dm.setUseAntiAliasing(true);
        r2dm.setColorAtomsByType(doColor);
        r2dm.setShowExplicitHydrogens(withH);
        r2dm.setShowImplicitHydrogens(true);
        r2dm.setShowAromaticity(true);
        r2dm.setShowReactionBoxes(false);
        r2dm.setKekuleStructure(false);

        GeometryTools.translateAllPositive(this.mol);
        GeometryTools.scaleMolecule(this.mol, getPreferredSize(), this.scale);
        GeometryTools.center(this.mol, getPreferredSize());

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

    this.frame.getContentPane().add(this);
    this.frame.pack();

    Rectangle pageSize = new Rectangle(this.getSize().width, this.getSize().height);
    try {
        StringBuffer comment = new StringBuffer();

        PdfPCell cell = new PdfPCell();
        Phrase phrase = new Phrase();

        addTitle(mol, phrase);

        if (props) {
            Map<Object, Object> propertyMap = mol.getProperties();
            for (Object key : propertyMap.keySet()) {
                if (key.equals("AllRings"))
                    continue;
                if (key.equals("SmallestRings"))
                    continue;
                if (key.equals(CDKConstants.TITLE))
                    continue;
                addProperty(key, mol, phrase);
            }
        }
        cell.addElement(phrase);
        table.addCell(cell);

        Image awtImage = createImage(this.getSize().width, this.getSize().height);
        Graphics snapGraphics = awtImage.getGraphics();
        paint(snapGraphics);

        com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(awtImage, null);
        pdfImage.setAbsolutePosition(0, 0);
        table.addCell(pdfImage);

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:displayStructureAsPDFTable.java

License:Open Source License

public void drawStructure(IAtomContainer mol, int cnt) {

    // do aromaticity detection
    try {/*from   w  w  w  .  j  a  v a 2  s  . c o m*/
        CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
        cdke.printStackTrace();
    }
    mol = addHeteroHydrogens(mol);
    r2dm = new Renderer2DModel();
    renderer = new Renderer2D(r2dm);
    Dimension screenSize = new Dimension(this.width, this.height);
    setPreferredSize(screenSize);
    r2dm.setBackgroundDimension(screenSize); // make sure it is synched with the JPanel size
    setBackground(r2dm.getBackColor());

    try {
        StructureDiagramGenerator sdg = new StructureDiagramGenerator();
        sdg.setMolecule((IMolecule) mol);
        sdg.generateCoordinates();
        this.mol = sdg.getMolecule();

        r2dm.setDrawNumbers(false);
        r2dm.setUseAntiAliasing(true);
        r2dm.setColorAtomsByType(doColor);
        r2dm.setShowAromaticity(true);
        r2dm.setShowAromaticityInCDKStyle(false);
        r2dm.setShowReactionBoxes(false);
        r2dm.setKekuleStructure(false);
        r2dm.setShowExplicitHydrogens(withH);
        r2dm.setShowImplicitHydrogens(true);
        GeometryTools.translateAllPositive(this.mol);
        GeometryTools.scaleMolecule(this.mol, getPreferredSize(), this.scale);
        GeometryTools.center(this.mol, getPreferredSize());
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    this.frame.getContentPane().add(this);
    this.frame.pack();

    String filename;
    if (cnt < 10)
        filename = this.odir + "/img00" + cnt + this.suffix;
    else if (cnt < 100)
        filename = this.odir + "/img0" + cnt + this.suffix;
    else
        filename = this.odir + "/img" + cnt + this.suffix;

    if (oformat.equalsIgnoreCase("png") || oformat.equalsIgnoreCase("jpeg")) {
        BufferedImage img;
        try {
            img = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_RGB);
            //                img = (BufferedImage) createImage(this.getSize().width, this.getSize().height);
            Graphics2D snapGraphics = (Graphics2D) img.getGraphics();
            this.paint(snapGraphics);
            File graphicsFile = new File(filename);
            ImageIO.write(img, oformat, graphicsFile);
        } catch (NullPointerException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    } else if (oformat.equalsIgnoreCase("pdf")) {
        File file = new File(filename);
        Rectangle pageSize = new Rectangle(this.getSize().width, this.getSize().height);
        Document document = new Document(pageSize);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            Image awtImage = createImage(this.getSize().width, this.getSize().height);
            Graphics snapGraphics = awtImage.getGraphics();
            paint(snapGraphics);

            com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(awtImage, null);
            pdfImage.setAbsolutePosition(0, 0);
            cb.addImage(pdfImage);

        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        document.close();
    } else if (oformat.equalsIgnoreCase("svg")) {
        /*
             try {
        SVGWriter cow = new SVGWriter(new FileWriter(filename));
        if (cow != null) {
            cow.writeAtomContainer(mol);
            cow.close();
        }
             } catch (IOException ioe) {
        ioe.printStackTrace();
             } catch (CDKException cdke) {
        cdke.printStackTrace();
             }
        */
    }
}

From source file:bucks.AuditSheet.java

License:Open Source License

void generateSheet(HttpServletResponse res, List<Batch> batches) {

    ///*from  w  w  w.j a  v a 2  s.c  o m*/
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    String spacer = "   \n";
    ServletOutputStream out = null;
    String filename = "marketbucks_audit_sheet.pdf";
    try {
        // space
        //         
        Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
        Document document = new Document(pageSize, 36, 36, 18, 18);// 18,18,54,35         
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        URL imgUrl = new URL(imageUrl);
        Image image = Image.getInstance(imgUrl);
        image.scalePercent(20f);
        // image.scaleAbsolute(100f, 100f);// width, height
        // image.setRotation(3.1f); // in radians
        // image.setRotationDegrees(90f); // degrees
        // image.setSpacingBefore(10f);
        // image.setSpacingAfter(10f);
        // image.setWidthPercentage(25.0f);
        Font fnt = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL);
        Font fntb = new Font(Font.TIMES_ROMAN, 12, Font.BOLD);
        Font fntb2 = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);
        Phrase spacePhrase = new Phrase();
        Chunk ch = new Chunk(spacer, fnt);
        spacePhrase.add(ch);

        float[] widths = { 25f, 75f }; // percentages
        PdfPTable headTable = new PdfPTable(widths);
        headTable.setWidthPercentage(100);
        headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        headTable.addCell(cell);

        Phrase phrase = new Phrase();
        ch = new Chunk("Printed Market Bucks Audit Sheet\n ", fntb2);
        phrase.add(ch);
        Paragraph pp = new Paragraph();
        pp.setIndentationLeft(20);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.add(phrase);
        cell = new PdfPCell(pp);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        headTable.addCell(cell);
        document.add(headTable);
        //
        document.add(spacePhrase);
        document.add(spacePhrase);
        //
        float[] widths3 = { 50f, 50f }; // percentages
        PdfPTable table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        phrase = new Phrase();
        ch = new Chunk(" Date: ", fntb);
        phrase.add(ch);
        ch = new Chunk(Helper.getToday() + "\n\n\n", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        // 
        phrase = new Phrase();
        ch = new Chunk(" ", fntb); // empty cell
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //         
        document.add(table);
        //
        phrase = new Phrase(new Chunk("\n", fnt));
        document.add(phrase);
        //
        float[] widths2 = { 15f, 10f, 15f, 15f, 15f, 15f, 15f }; // percentages
        table = new PdfPTable(widths2);
        table.setWidthPercentage(90);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        // table.getDefaultCell().setPadding(5);
        phrase = new Phrase();
        ch = new Chunk("Count of MB/GC", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Value", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Total Dollars", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Printed By", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Start Number", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("End Number", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("Printed Date", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        // next rows
        //
        for (Batch one : batches) {
            phrase = new Phrase();
            ch = new Chunk(one.getBatch_size(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);

            phrase = new Phrase();
            ch = new Chunk("$" + one.getValue() + ".00", fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);
            //
            phrase = new Phrase();
            ch = new Chunk(moneyFormat.format(one.getTotal()), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);
            //
            phrase = new Phrase();
            ch = new Chunk(one.getUser().toString(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);

            phrase = new Phrase();
            ch = new Chunk(one.getStart_seq(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);

            phrase = new Phrase();
            ch = new Chunk(one.getEnd_seq(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);

            phrase = new Phrase();
            ch = new Chunk(one.getDate(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorderWidth(1f);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(4);
            cell.setLeading(2f, 1.2f);
            table.addCell(cell);
        }
        document.add(table);
        //
        document.add(spacePhrase);
        document.add(spacePhrase);
        //
        ch = new Chunk("Audit By:____________________________________________________________________\n\n",
                fnt);
        phrase = new Phrase();
        phrase.add(ch);
        document.add(phrase);
        ch = new Chunk("           :_______________________________________)_____________________________\n\n",
                fnt);
        phrase = new Phrase();
        phrase.add(ch);
        document.add(phrase);
        ch = new Chunk("           :_____________________________________________________________________\n\n",
                fnt);
        phrase = new Phrase();
        phrase.add(ch);
        document.add(phrase);
        //
        document.add(spacePhrase);
        document.add(spacePhrase);
        //
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setHeader("Content-Disposition", " attachment; filename=" + filename);
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:bucks.GenerateChecks.java

License:Open Source License

void generate(HttpServletResponse res, Batch batch) {
    ServletOutputStream out = null;//from www  .  j  ava  2 s.c o  m
    BuckConf conf = batch.getConf();
    int start_seq = batch.getStart_seq_int();
    int size = batch.getBatch_size_int();
    String type = conf.getType_id();
    String value = conf.getValue();
    String filename = "market_bucks_" + Helper.getCurrentYear() + "_" + batch.getId() + ".pdf";
    // we need to register these fonts
    // windows we use verdana

    //
    // for test purpose
    //
    /*
       start_seq = 612001;
       type="2";
       value="5";
       size = 6;
    */
    try {
        Image image = Image.getInstance(imageUrl);
        // image.setWidthPercentage(20.0f);
        image.scalePercent(10f);
        Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
        // left right top bottom
        Document document = new Document(pageSize, 15, 15, 18, 12);// 1/4 inch
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        //
        int row = 1, page_no = 0;
        int page = 1;
        if (type.equals("1")) { // MB
            for (int jj = 0; jj < size; jj++) {
                generate_mb(document, start_seq + jj, value, image, writer);
                row++;
                if (row == 4 && (jj + 1) < size) { // to avoid empty page
                    row = 1;
                    page++;
                    page_no = writer.getPageNumber();
                    if (page_no < page) {
                        document.newPage();
                    }
                }
            }
        } else { // GC
            for (int jj = 0; jj < size; jj++) {
                generate_gc(document, start_seq + jj, value, image, writer);
                row++;
                if (row == 4 && (jj + 1) < size) { // to avoid empty page
                    row = 1;
                    page++;
                    page_no = writer.getPageNumber();
                    // System.err.println(page+" "+page_no);
                    if (page_no < page) {
                        document.newPage();
                    }
                }
            }
        }
        //
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setHeader("Content-Disposition", " attachment; filename=" + filename);
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:bucks.RedeemInvoice.java

License:Open Source License

void generateInvoice(HttpServletResponse res, Redeem redeem) {

    ///*  ww w  . ja v  a2  s.c o  m*/
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    String spacer = "   \n";
    User user = redeem.getUser();
    Vendor vendor = redeem.getVendor();
    List<Buck> bk_bucks = redeem.getBk_bucks();
    List<Buck> gc5_bucks = redeem.getGc5_bucks();
    List<Buck> gc20_bucks = redeem.getGc20_bucks();
    List<Buck> gc_bucks = redeem.getGc_bucks();
    List<Dispute> disputes = redeem.getDisputes();
    int bk_total = 0, gc5_total = 0, gc20_total = 0, total = 0;
    if (bk_bucks.size() > 0) {
        bk_total = bk_bucks.size() * 3;
    }
    if (gc5_bucks.size() > 0) {
        gc5_total = gc5_bucks.size() * 5;
    }
    if (gc20_bucks.size() > 0) {
        gc20_total = gc20_bucks.size() * 20;
    }
    total = bk_total + gc5_total + gc20_total;
    String vendor_name = "";
    if (vendor != null) {
        vendor_name = vendor.getCleanName();
    }
    ServletOutputStream out = null;
    String filename = "invoice_" + vendor_name + "_" + redeem.getId() + ".pdf";
    try {
        // space
        //         
        Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
        Document document = new Document(pageSize, 36, 36, 18, 18);// 18,18,54,35         
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        Image image = Image.getInstance(imageUrl);
        // image = Image.getInstance(byte bytes[]);// generated image
        image.scalePercent(20f);
        Font fnt = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL);
        Font fntb = new Font(Font.TIMES_ROMAN, 12, Font.BOLD);
        Font fntb2 = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

        //
        Phrase spacePhrase = new Phrase();
        Chunk ch = new Chunk(spacer, fnt);
        spacePhrase.add(ch);

        float[] widths = { 15f, 85f }; // percentages
        PdfPTable headTable = new PdfPTable(widths);
        headTable.setWidthPercentage(100);
        headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        // image.setWidthPercentage(15.0f);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        // cell.setFixedHeight(46f);
        headTable.addCell(cell);

        Phrase phrase = new Phrase();
        ch = new Chunk(
                "City of Bloomington Community Farmers Market\n Gift Certificates/Market Bucks Invoice\n ",
                fntb2);
        phrase.add(ch);
        Paragraph pp = new Paragraph();
        pp.setIndentationLeft(20);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.add(phrase);
        cell = new PdfPCell(pp);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        headTable.addCell(cell);
        document.add(headTable);
        //
        float[] widths3 = { 50f, 50f }; // percentages
        PdfPTable table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        phrase = new Phrase();
        ch = new Chunk(" Vendor Name: ", fntb);
        phrase.add(ch);
        ch = new Chunk(vendor.getFullName(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //         
        phrase = new Phrase();
        ch = new Chunk("Date: ", fntb);
        phrase.add(ch);
        ch = new Chunk(redeem.getDate(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        phrase = new Phrase();
        ch = new Chunk(" Vendor Number: ", fntb);
        phrase.add(ch);
        ch = new Chunk(vendor.getId(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        phrase = new Phrase(); // empty cell
        ch = new Chunk(" ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        table.addCell(cell); // extra space
        table.addCell(cell);
        document.add(table);
        //
        phrase = new Phrase(new Chunk("\n", fnt));
        document.add(phrase);
        //
        float[] widths2 = { 30f, 25f, 15f, 15f, 15f }; // percentages
        table = new PdfPTable(widths2);
        table.setWidthPercentage(90);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        // table.getDefaultCell().setPadding(5);
        phrase = new Phrase();
        ch = new Chunk("Type of Voucher", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("City Account Number", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Quantity", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("Multiply", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("Value", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        // second row
        phrase = new Phrase();
        ch = new Chunk("Market Bucks", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("201-18-1865003-47240", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        String str = " ";
        if (bk_bucks.size() > 0) {
            str = "" + bk_bucks.size();
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("x $3.00 = ", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);

        phrase = new Phrase();
        str = " ";
        if (bk_total > 0) {
            str = "$" + bk_total + ".00";
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);
        //
        // 3rd row
        phrase = new Phrase();
        ch = new Chunk("$5 Gift Cerificates", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("201-18-1865003-47230", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        str = " ";
        if (gc5_bucks.size() > 0) {
            str = "" + gc5_bucks.size();
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("x $5.00 = ", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);

        phrase = new Phrase();
        str = " ";
        if (gc5_total > 0) {
            str = "$" + gc5_total + ".00";
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);
        //
        // 4th row
        phrase = new Phrase();
        ch = new Chunk("$20 Gift Certificates", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("201-18-1865003-47230", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        str = " ";
        if (gc20_bucks.size() > 0) {
            str = "" + gc20_bucks.size();
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("x $20.00 = ", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        str = " ";
        if (gc20_total > 0) {
            str = "$" + gc20_total + ".00";
        }
        phrase = new Phrase();
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);
        //
        // 5th row total
        phrase = new Phrase();
        ch = new Chunk(" Total Value: ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(2f);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("$" + total + ".00", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(2f);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        document.add(table);
        //
        //
        float[] withs5 = { 100f };
        table = new PdfPTable(withs5);
        table.setWidthPercentage(100);
        cell = new PdfPCell(new Phrase(" "));
        cell.setBorder(Rectangle.BOTTOM);
        // cell.setBorderColorBottom(Color.BLACK);
        cell.setBorderWidthBottom(2f);
        table.addCell(cell);
        document.add(table);
        //
        ch = new Chunk("\n", fnt);
        phrase = new Phrase();
        phrase.add(ch);
        document.add(phrase);
        //
        // float[] widths3 = {50f, 50f}; // percentages
        table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        phrase = new Phrase();
        ch = new Chunk(" Data Entry Completed by: ", fntb);
        phrase.add(ch);
        ch = new Chunk(user.getFullName(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk(" Invoice Number: ", fntb);
        phrase.add(ch);
        ch = new Chunk(redeem.getId(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);
        document.add(table);
        document.add(spacePhrase);
        document.add(spacePhrase);
        //
        // adding bucks and GC
        //
        float[] widths4 = { 100f }; // percentages
        table = new PdfPTable(widths4);
        table.setWidthPercentage(100);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        int row = 1, col = 1;
        if (bk_bucks.size() > 0) {
            phrase = new Phrase();
            ch = new Chunk(" Market Bucks ", fntb);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            phrase = new Phrase();
            for (Buck one : bk_bucks) {
                ch = new Chunk("" + one.getId() + " ", fntb);
                phrase.add(ch);
                col++;
                if (col > 15) {
                    row++;
                    col = 1;
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    phrase = new Phrase();
                }
            }
            if (col > 1) {
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
            }
            if (row < 10) {
                for (int j = 0; j < 2; j++) {
                    phrase = new Phrase();
                    ch = new Chunk(" ", fntb);
                    phrase.add(ch);
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    row++;
                }
            }
        }
        col = 1;
        if (gc_bucks.size() > 0) {
            phrase = new Phrase();
            ch = new Chunk(" Gift Certificates ", fntb);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            phrase = new Phrase();
            for (Buck one : gc_bucks) {
                ch = new Chunk("" + one.getId() + " ", fntb);
                phrase.add(ch);
                col++;
                if (col > 15) {
                    row++;
                    col = 1;
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    phrase = new Phrase();
                }
            }
            if (col > 1) {
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
            }
            if (row < 15) {
                for (int j = 0; j < 2; j++) {
                    phrase = new Phrase();
                    ch = new Chunk(" ", fntb);
                    phrase.add(ch);
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    row++;
                }
            }
        }
        if (disputes != null && disputes.size() > 0) {
            phrase = new Phrase();
            ch = new Chunk(" Disputed Market Bucks and/or Gift Certificates (number: reason)", fntb);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            row++;
            for (Dispute one : disputes) {
                phrase = new Phrase();
                ch = new Chunk(one.getBuck_id() + ": " + one.getReason(), fnt);
                phrase.add(ch);
                if (one.hasNotes()) {
                    ch = new Chunk("\nNotice: " + one.getNotes(), fnt);
                    phrase.add(ch);
                    row++;
                }
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
                row++;
            }
        }
        if (redeem.hasNotes()) {
            phrase = new Phrase();
            ch = new Chunk("\nNotice: " + redeem.getNotes(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell);
            row++;
        }
        if (row < 18) {
            for (int j = row; j < 18; j++) {
                phrase = new Phrase();
                ch = new Chunk(" ", fntb);
                phrase.add(ch);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
            }
        }

        document.add(table);
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setHeader("Content-Disposition", " attachment; filename=" + filename);
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:ca.sqlpower.architect.swingui.action.ExportPlaypenToPDFAction.java

License:Open Source License

@Override
public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) {
    logger.debug("Creating PDF of playpen: " + getPlaypen());

    //This is the current play pen snapshot at the time of starting the worker
    //thread. This way the play pen doesn't change while it is printing.
    PlayPen pp = playPen;//w ww .ja v a2 s.c om

    /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) 
     * so nothing is drawn right on the edge of the document. So
     * we multiply by 2 so we can accomodate the translate and ensure
     * nothing gets drawn outside of the document size.
     */
    final int width = pp.getBounds().width + 2 * OUTSIDE_PADDING;
    final int height = pp.getBounds().height + 2 * OUTSIDE_PADDING;
    final Rectangle ppSize = new Rectangle(width, height);

    OutputStream out = null;
    Document d = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY)));
        d = new Document(ppSize);

        d.addTitle(Messages.getString("ExportPlaypenToPDFAction.PdfTitle")); //$NON-NLS-1$
        d.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$
        d.addCreator(Messages.getString("ExportPlaypenToPDFAction.powerArchitectVersion") //$NON-NLS-1$
                + ArchitectVersion.APP_FULL_VERSION);

        PdfWriter writer = PdfWriter.getInstance(d, out);
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphicsShapes(width, height);
        // ensure a margin
        g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING);
        PlayPenContentPane contentPane = pp.getContentPane();
        for (int i = 0; i < contentPane.getChildren().size(); i++) {
            PlayPenComponent ppc = contentPane.getChildren().get(i);
            if (logger.isDebugEnabled()) {
                logger.debug("Painting component " + ppc);
            }
            g.translate(ppc.getLocation().x, ppc.getLocation().y);
            Font gFont = g.getFont();
            ppc.paint(g);
            g.setFont(gFont);
            g.translate(-ppc.getLocation().x, -ppc.getLocation().y);
            monitor.setProgress(i);
        }
        pp.paintComponent(g);
        g.dispose();
    } catch (Exception ex) {
        ASUtils.showExceptionDialog(getSession(),
                Messages.getString("ExportPlaypenToPDFAction.couldNotExportPlaypen"), //$NON-NLS-1$
                ex);
    } finally {
        if (d != null) {
            try {
                d.close();
            } catch (Exception ex) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ExportPlaypenToPDFAction.couldNotCloseDocument"), //$NON-NLS-1$
                        ex);
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ExportPlaypenToPDFAction.couldNotClosePdfFile"), //$NON-NLS-1$
                        ex);
            }
        }
    }
}

From source file:ca.sqlpower.matchmaker.swingui.action.ExportMungePenToPDFAction.java

License:Open Source License

@Override
public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) {
    if (!(session.getOldPane() instanceof MungeProcessEditor)) {
        JOptionPane.showMessageDialog(session.getFrame(),
                "We only allow PDF exports of the playpen at current.", "Cannot Export Playpen",
                JOptionPane.WARNING_MESSAGE);
        return;//from w w  w.j a va 2  s . co m
    }

    MungePen mungePen = ((MungeProcessEditor) session.getOldPane()).getMungePen();

    /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) 
     * so nothing is drawn right on the edge of the document. So
     * we multiply by 2 so we can accomodate the translate and ensure
     * nothing gets drawn outside of the document size.
     */
    final int width = mungePen.getBounds().width + 2 * OUTSIDE_PADDING;
    final int height = mungePen.getBounds().height + 2 * OUTSIDE_PADDING;
    final Rectangle ppSize = new Rectangle(width, height);

    OutputStream out = null;
    Document d = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY)));
        d = new Document(ppSize);

        d.addTitle("DQguru Transform PDF Export");
        d.addAuthor(System.getProperty("user.name"));
        d.addCreator("DQguru version " + MatchMakerVersion.APP_VERSION);

        PdfWriter writer = PdfWriter.getInstance(d, out);
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphicsShapes(width, height);
        // ensure a margin
        g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING);

        mungePen.paintComponent(g);

        int j = 0;
        //paint each component individually to show progress
        for (int i = mungePen.getComponentCount() - 1; i >= 0; i--) {
            JComponent mpc = (JComponent) mungePen.getComponent(i);

            //set text and foreground as paintComponent
            //does not normally do this
            g.setColor(mpc.getForeground());
            g.setFont(mpc.getFont());

            logger.debug("Printing " + mpc.getName() + " to PDF");
            paintComponentAndChildren(mpc, g);

            monitor.setProgress(j);
            j++;
        }
        g.dispose();
    } catch (Exception ex) {
        SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not export the playpen", ex);
    } finally {
        if (d != null) {
            try {
                d.close();
            } catch (Exception ex) {
                SPSUtils.showExceptionDialogNoReport(session.getFrame(),
                        "Could not close document for exporting playpen", ex);
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                SPSUtils.showExceptionDialogNoReport(session.getFrame(),
                        "Could not close pdf file for exporting playpen", ex);
            }
        }
    }
}

From source file:ch.gpb.elexis.cst.view.CstResultPart.java

License:Open Source License

private void makeActions(final Control viewer) {

    actionScreenshot = new Action() {
        public void run() {
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }// w w w  . j  av a  2  s.c  om

            GC gc = null;
            Image image = null;
            try {

                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.png", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }

                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) {
                if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) {

                    if (profile.getAusgabeRichtung()) {
                        image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height);

                    } else {
                        image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                    }
                } else {
                    image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                }

                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);

                gc.dispose();

                loader.data = new ImageData[] { image.getImageData() };
                loader.save(selected, SWT.IMAGE_PNG);

            } catch (Exception e) {
                log.error("Error saving png: " + e.toString());
                showMessage("Error while saving PNG", e.getMessage());
            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
            }

        }
    };
    actionScreenshot.setText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT));
    actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH));

    // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten
    actionPdf = new Action() {
        public void run() {

            //////////////////////////
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }

            GC gc = null;
            Image image = null;
            try {
                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.pdf", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }
                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                int printHeigth = 1123;
                int printWidth = 794;
                if (profile.getAusgabeRichtung()) {
                    printHeigth = 794;
                    printWidth = 1123;

                }

                // get the image from the viewport
                image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height);
                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);
                gc.dispose();

                // prepare title data
                //Date date = new Date();
                //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy  HH:mm");

                Patient patient = Patient.load(profile.getKontaktId());
                //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi ";
                String sTitle;
                sTitle = profile.getOutputHeader() == null ? "No header configured!"
                        : profile.getOutputHeader();

                if (sTitle == null || sTitle.length() == 0) {
                    sTitle = "No header configured!";
                }
                sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime();

                // get option (paging to A4/ in one piece)
                int pdfOutputOption = 0;
                boolean onePage = true;

                PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell());
                dialog.create();

                if (dialog.open() == Window.OK) {
                    pdfOutputOption = dialog.getPdfOutputOption();
                    if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) {
                        onePage = true;
                    } else {

                        onePage = false;
                    }
                }

                float docHeight = viewer.getBounds().height;
                docHeight = docHeight / 7.5f;

                float fontSize = 12f;

                if (docHeight < 360f) {
                    docHeight = 360f;
                }

                BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData());

                // create an Itextt Image from AWT BufferedImage
                com.lowagie.text.Image itextImage = null;
                java.awt.Image awtImage = null;

                try {
                    awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource());
                    itextImage = com.lowagie.text.Image.getInstance(awtImage, null);

                } catch (Exception e) {
                    log.error("Error on image loading: " + e.toString());
                    e.printStackTrace();
                }

                // only for debugging

                //loader.data = new ImageData[] { image.getImageData() };
                //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG);

                Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f);

                // is it a4 quer?
                if (profile.getAusgabeRichtung()) {
                    pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f);

                }

                //System.out.println("pagesize: " + pagesize.toString());

                Document document;
                if (onePage) {
                    document = new Document(pagesize);

                } else {
                    document = new Document(PageSize.A4);
                    if (profile.getAusgabeRichtung()) {
                        document = new Document(PageSize.A4.rotate());
                    }

                }

                document.addCreationDate();

                try {
                    // creation of the different writers
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected));

                    // various fonts
                    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true);
                    BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                    BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", true);

                    com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize);

                    com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize);

                    fontTimes.setSize(fontSize);
                    fontTimes.setStyle(com.lowagie.text.Font.ITALIC);

                    Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize,
                            com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0)));

                    com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader);

                    // headers and footers must be added before the document
                    // is opened

                    Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA,
                            fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0)));

                    Phrase phraseFooter = new Phrase(chunkFooter);
                    phraseFooter.setFont(fontHelv12);

                    HeaderFooter footer = new HeaderFooter(phraseFooter, true);
                    footer.setBorder(Rectangle.NO_BORDER);
                    footer.setAlignment(Element.ALIGN_CENTER);

                    document.setFooter(footer);

                    Phrase headerPhrase = new Phrase(sTitle);
                    headerPhrase.setFont(fontTimes);

                    HeaderFooter header = new HeaderFooter(phraseHeader, false);
                    header.setBorder(Rectangle.BOTTOM);
                    header.setBorderWidth(0.5f);
                    header.setAlignment(Element.ALIGN_LEFT);
                    document.setHeader(header);

                    document.open();

                    //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight());

                    if (onePage) {

                        int scale = 66;
                        itextImage.scalePercent(scale);

                        document.add(itextImage);

                    } else {

                        BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth);

                        for (int i = 0; i < imageChunks.length; i++) {

                            com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance(
                                    Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null);

                            // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer
                            float imgWidth = document.getPageSize().getWidth() - document.leftMargin()
                                    - document.rightMargin();
                            float imgHeigth = itextImage.getHeight() * 0.75f;

                            itextImage2.setAbsolutePosition(30, 20);
                            int scale = 66;
                            itextImage2.scalePercent(scale);

                            document.add(itextImage2);
                            document.newPage();

                        }

                    }

                    // we're done!
                    document.close();

                    ///////////////////////////////

                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    showMessage("Error while generating PDF", ex.getMessage());
                }

            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
                /*
                image.dispose();
                gc.dispose();
                */
            }

        }
    };

    actionPdf.setText(Messages.Cst_Text_Save_as_pdf);
    actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf);
    /*
     * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages()
     * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE));
     */
    actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH));

}

From source file:classroom.filmfestival_c.Movies22.java

public static void main(String[] args) {
    // step 1//from w w  w . jav  a 2  s  .com
    Document document = new Document(new Rectangle(WIDTH, HEIGHT));
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FORM));
        writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage);
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();

        // top part of the card
        cb.setColorFill(RED);
        cb.rectangle(0, mm2pt(57f), WIDTH, HEIGHT - mm2pt(57f));
        cb.fill();
        cb.setColorFill(BLACK);
        cb.rectangle(0, mm2pt(61), WIDTH, mm2pt(21f));
        cb.fill();
        cb.setColorFill(WHITE);

        Image kubrick = Image.getInstance(KUBRICK);
        kubrick.scaleToFit(WIDTH, mm2pt(21));
        kubrick.setAbsolutePosition(0, mm2pt(61));
        cb.addImage(kubrick);

        Image logo = Image.getInstance(LOGO);
        logo.scaleToFit(mm2pt(14), mm2pt(14));
        logo.setAbsolutePosition(mm2pt(37), mm2pt(65));
        cb.addImage(logo);

        cb.beginText();
        cb.setFontAndSize(FONT, 7);
        cb.showTextAligned(Element.ALIGN_CENTER, "Flanders International Film Festival-Ghent", WIDTH / 2,
                mm2pt(58.5f), 0);
        cb.endText();

        // bottom part of the card

        TextField filmfestival = new TextField(writer, new Rectangle(0, 0, WIDTH, mm2pt(9)), "filmfestival");
        filmfestival.setBackgroundColor(GRAY);
        filmfestival.setTextColor(WHITE);
        filmfestival.setText("www.filmfestival.be");
        filmfestival.setFontSize(14);
        filmfestival.setOptions(TextField.READ_ONLY);
        filmfestival.setAlignment(Element.ALIGN_CENTER);
        writer.addAnnotation(filmfestival.getTextField());

        cb.beginText();
        cb.moveText(mm2pt(1.5f), mm2pt(12));
        cb.setFontAndSize(FONT, 21);
        cb.setColorFill(RED);
        cb.showText("10");
        cb.setColorFill(BLUE);
        cb.showText("/");
        cb.setColorFill(RED);
        cb.showText("21");
        cb.setColorFill(BLUE);
        cb.showText("OCT");
        cb.setColorFill(GREEN);
        cb.showText("2006");
        cb.endText();
        cb.setColorStroke(BLUE);
        cb.moveTo(mm2pt(24.5f), mm2pt(29));
        cb.lineTo(mm2pt(24.5f), mm2pt(36));
        cb.moveTo(mm2pt(24.5f), mm2pt(48));
        cb.lineTo(mm2pt(24.5f), mm2pt(54));
        cb.stroke();

        // central part of the card
        PushbuttonField photo = new PushbuttonField(writer,
                new Rectangle(mm2pt(3), mm2pt(29), mm2pt(24), mm2pt(54)), "photo");
        PdfTemplate t1 = cb.createTemplate(mm2pt(21), mm2pt(25));
        t1.setColorFill(GRAY);
        t1.rectangle(0, 0, mm2pt(21), mm2pt(25));
        t1.fill();
        photo.setTemplate(t1);
        photo.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
        writer.addAnnotation(photo.getField());

        TextField type = new TextField(writer,
                new Rectangle(mm2pt(26), mm2pt(46), WIDTH - mm2pt(1.5f), mm2pt(54)), "type");
        type.setTextColor(GRAY);
        type.setText("TYPE");
        type.setFontSize(0);
        writer.addAnnotation(type.getTextField());

        TextField number = new TextField(writer,
                new Rectangle(mm2pt(26), mm2pt(44), WIDTH - mm2pt(1.5f), mm2pt(48)), "number");
        number.setText("N\u00b0 0000000");
        number.setFontSize(8);
        writer.addAnnotation(number.getTextField());

        TextField name = new TextField(writer,
                new Rectangle(mm2pt(26), mm2pt(28), WIDTH - mm2pt(1.5f), mm2pt(40)), "name");
        name.setText("Name");
        name.setFontSize(8);
        name.setOptions(TextField.MULTILINE);
        writer.addAnnotation(name.getTextField());

        PushbuttonField barcode = new PushbuttonField(writer,
                new Rectangle(mm2pt(3), mm2pt(23), WIDTH - mm2pt(3), mm2pt(28)), "barcode");
        PdfTemplate t2 = cb.createTemplate(WIDTH - mm2pt(6), mm2pt(5));
        t2.setColorFill(GRAY);
        t2.rectangle(0, 0, WIDTH - mm2pt(6), mm2pt(5));
        t2.fill();
        barcode.setTemplate(t2);
        barcode.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
        writer.addAnnotation(barcode.getField());

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // step 4
    document.close();
}

From source file:classroom.filmfestival_c.Movies25.java

public static void createTemplate() {
    // our template will be 35 x 50 mm
    Document document = new Document(
            new Rectangle(Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(50)));
    try {//from   w  w  w.  ja v  a2s .co m
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(TEMPLATE));
        writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage);
        // step 3
        document.open();
        // step 4

        // space reserved for the film poster
        PushbuttonField foto = new PushbuttonField(writer,
                new Rectangle(Utilities.millimetersToPoints(0), Utilities.millimetersToPoints(25),
                        Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(50)),
                POSTER);
        foto.setBackgroundColor(Color.BLUE);
        writer.addAnnotation(foto.getField());

        // space reserved for the text
        TextField tekst = new TextField(writer,
                new Rectangle(Utilities.millimetersToPoints(0), Utilities.millimetersToPoints(7),
                        Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(25)),
                TEXT);
        tekst.setOptions(TextField.MULTILINE);
        writer.addAnnotation(tekst.getTextField());

        // space reserved for the year
        TextField prijs = new TextField(writer,
                new Rectangle(Utilities.millimetersToPoints(0), Utilities.millimetersToPoints(0),
                        Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(7)),
                YEAR);
        prijs.setAlignment(Element.ALIGN_CENTER);
        prijs.setBackgroundColor(Color.BLUE);
        prijs.setTextColor(Color.WHITE);
        writer.addAnnotation(prijs.getTextField());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    // step 5
    document.close();
}