Example usage for com.lowagie.text.pdf PdfPCell setFixedHeight

List of usage examples for com.lowagie.text.pdf PdfPCell setFixedHeight

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPCell setFixedHeight.

Prototype

public void setFixedHeight(float fixedHeight) 

Source Link

Document

Set a fixed height for the cell.

Usage

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

License:Open Source License

public MemoryFileDTO createFileLabelsPDF(ArrayList<LabelDTO> labels, LabelConfigDTO labelConfig) {
    Document document = new Document();
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("biblivre_etiquetas_" + new Date().getTime() + ".pdf");
    try {//  w  w w  . j av  a2 s . c o m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        float verticalMargin = (297.0f - (labelConfig.getHeight() * labelConfig.getRows())) / 2;
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                verticalMargin * ApplicationConstants.MM_UNIT, verticalMargin * ApplicationConstants.MM_UNIT);
        document.open();

        PdfPTable table = new PdfPTable(labelConfig.getColumns());
        table.setWidthPercentage(100f);
        PdfPCell cell;

        int i = 0;
        for (i = 0; i < labelConfig.getOffset(); i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }

        for (LabelDTO ldto : labels) {
            PdfContentByte cb = writer.getDirectContent();

            String holdingSerial = String.valueOf(ldto.getHoldingSerial());
            while (holdingSerial.length() < 10) {
                holdingSerial = "0" + holdingSerial;
            }
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            code39.setCode(holdingSerial);
            code39.setStartStopText(false);

            Image image39 = code39.createImageWithBarcode(cb, null, null);
            if (labelConfig.getHeight() > 30.0f) {
                image39.scalePercent(110f);
            } else {
                image39.scalePercent(90f);
            }

            Paragraph para = new Paragraph();
            Phrase p1 = new Phrase(StringUtils.left(ldto.getAuthor(), 28) + "\n");
            Phrase p2 = new Phrase(StringUtils.left(ldto.getTitle(), 28) + "\n\n");
            Phrase p3 = new Phrase(new Chunk(image39, 0, 0));
            para.add(p1);
            para.add(p2);
            para.add(p3);

            cell = new PdfPCell(para);
            i++;
            cell.setNoWrap(true);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);

            Paragraph para2 = new Paragraph();
            Phrase p5 = new Phrase(ldto.getLocationA() + "\n");
            Phrase p6 = new Phrase(ldto.getLocationB() + "\n");
            Phrase p7 = new Phrase(ldto.getLocationC() + "\n");
            Phrase p8 = new Phrase(ldto.getLocationD() + "\n");
            Phrase p4 = new Phrase(ldto.getAssetHolding() + "\n");
            para2.add(p5);
            para2.add(p6);
            para2.add(p7);
            para2.add(p8);
            para2.add(p4);

            cell = new PdfPCell(para2);
            i++;
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % labelConfig.getColumns()) != 0) {
            while ((i % labelConfig.getColumns()) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:biblivre3.circulation.CirculationBO.java

License:Open Source License

public MemoryFileDTO createFileUserCardsPDF(ArrayList<UserCardDTO> cards, int startOffset, Properties i18n) {
    Document document = new Document();
    MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("user_cards_" + new Date().getTime() + ".pdf");
    try {//  w w  w .j  a v  a2  s  .  c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                9.09f * ApplicationConstants.MM_UNIT, 9.09f * ApplicationConstants.MM_UNIT);
        document.open();
        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100f);
        PdfPCell cell;
        int i = 0;
        for (i = 0; i < startOffset; i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }
        for (UserCardDTO card : cards) {
            String userEnrollNumber = String.valueOf(card.getUserId());
            PdfContentByte cb = writer.getDirectContent();
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            while (userEnrollNumber.length() < 10) {
                userEnrollNumber = "0" + userEnrollNumber;
            }
            code39.setCode(userEnrollNumber);
            code39.setStartStopText(false);
            Image image39 = code39.createImageWithBarcode(cb, null, null);
            image39.scalePercent(110f);
            Paragraph para = new Paragraph();
            String name = card.getUserName();
            name = name.length() >= 30 ? name.substring(0, 30) : name;
            Phrase p1 = new Phrase(name + "\n");
            Phrase p2 = new Phrase(new Chunk(image39, 0, 0));
            Phrase p3 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_SERIAL") + ": " + card.getUserId() + "\n");
            Phrase p4 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_TYPE") + ": " + card.getUserType() + "\n\n");
            para.add(p1);
            para.add(p3);
            para.add(p4);
            para.add(p2);
            cell = new PdfPCell(para);
            i++;
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % 3) != 0) {
            while ((i % 3) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (DocumentException de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:bucks.GenerateChecks.java

License:Open Source License

void generate_mb(Document document, int seq, String value, Image image, PdfWriter writer) {
    try {/*from w  w w  .  ja  v  a 2  s  .  co m*/
        float[] widths = { 15f, 40f, 45f }; // percentages         
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(100);
        table.setSpacingAfter(0f);
        table.setSpacingBefore(0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        // cell.setFixedHeight(46f);
        table.addCell(cell);
        Phrase phrase = new Phrase();
        Chunk ch = new Chunk("FARMERS' MARKET BUCKS\n", fntb2);
        phrase.add(ch);
        ch = new Chunk("Parks & Recreation\nBloomington, IN", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Issue Date___________ ", fnt10);
        phrase.add(ch);
        ch = new Chunk("No. " + seq, fnt10);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        // document.add(table);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is good for ", fnt);
        phrase.add(ch);
        ch = new Chunk("$" + value + ".00 ", fntb2);
        phrase.add(ch);
        ch = new Chunk("towards the purchase of ", fnt);
        phrase.add(ch);
        ch = new Chunk("eligible food items ", fntb);
        phrase.add(ch);
        ch = new Chunk("at the Bloomington Community Farmers' Market. ", fnt);
        phrase.add(ch);
        ch = new Chunk("No change allowed. \n", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(48f);
        cell.setColspan(3);
        table.addCell(cell);

        document.add(table);
        //
        float[] widths2 = { 60f, 25f, 10f, 5f };
        table = new PdfPTable(widths2);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        //table.getDefaultCell().setPadding(0);
        table.setSpacingAfter(0f);
        table.setSpacingBefore(0f);
        //
        phrase = new Phrase();
        ch = new Chunk(
                "Customers shall redeem this certificate at Farmers' Market\nby December 1st of the year issued.",
                fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);

        cell.setColspan(2);
        cell.setFixedHeight(81f);
        table.addCell(cell);
        //
        Barcode barcode = BarcodeFactory.createCode39("" + seq, false);
        // barcode text has problem, so we turned off
        // and decided to add it ourselves.
        barcode.setDrawingText(false);
        // barcode.setFont(new java.awt.Font("Arial", java.awt.Font.PLAIN, 16));
        // barcode.setLabel(""+seq);
        BufferedImage bi = BarcodeImageHandler.getImage(barcode);
        /*
        int width = bi.getWidth();
        int height = bi.getHeight();
        Graphics2D g2 = bi.createGraphics();
        g2.setColor(Color.BLACK);
        g2.drawString(""+seq, 60, 70);
        g2.dispose();
        */
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //
        // added this hack to get rid of underline in the barcode
        // this worked on windows, but the text did not show up on linux
        // that is why we decided to abandon the text all the way
        // and add it ourselves
        /*
        BarcodeImageHandler.writePNG(barcode, baos);
        File bcImg = File.createTempFile("bc-", ".png");
        bcImg.deleteOnExit();
        byte[] imageBytes = baos.toByteArray();
        FileOutputStream fos = new FileOutputStream(bcImg);
        BarcodeImageHandler.writePNG(barcode, fos);
        */
        //
        // old
        ImageIO.write(bi, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        //
        Image barCodeImage = Image.getInstance(imageBytes);

        barCodeImage.setRotationDegrees(90f);
        // barCodeImage.scalePercent(35f);
        barCodeImage.scalePercent(35f, 50f);
        // float widthf = barCodeImage.getWidth();
        // float heightf = barCodeImage.getHeight();

        cell = new PdfPCell(barCodeImage);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        // cell.setFixedHeight(81f);
        table.addCell(cell);
        //
        // the barcode text that we added underneath the barcode
        //
        int textWidth = 53, textHeight = 50;
        BufferedImage bi2 = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = bi2.createGraphics();
        g.setFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 10));
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, textWidth, textHeight);
        g.setColor(Color.BLACK);
        g.drawString("" + seq, 5, 10);

        g.dispose();
        baos = new ByteArrayOutputStream();
        ImageIO.write(bi2, "png", baos);
        imageBytes = baos.toByteArray();
        Image barCodeTextImage = Image.getInstance(imageBytes);

        barCodeTextImage.setRotationDegrees(90f);
        cell = new PdfPCell(barCodeTextImage);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is not refundable and cannot be replaced if lost or stolen.\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(34f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("\nMust have official stamp to be valid.\n\n", fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setColspan(3);
        table.addCell(cell);
        document.add(table);
        //
        float[] widths4 = { 40f, 60f }; // percentages         
        table = new PdfPTable(widths4);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        table.setSpacingBefore(0f);
        table.setSpacingAfter(0f);
        phrase = new Phrase();
        ch = new Chunk("APPROVED BY THE STATE BOARD OF ACCOUNTS\nFOR THE CITY OF BLOOMINGTON, IN 2007\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);

        cell.setFixedHeight(40f); // 40
        table.addCell(cell);
        phrase = new Phrase();
        ch = new Chunk(
                "VENDERS SHALL REDEEM THIS CERTIFICATE THROUGH BLOOMINGTON'S\nPARKS & REC DEPT. BY DECEMBER 15TH OF THE YEAR ISSUED\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);
        document.add(table);
    } catch (Exception ex) {
        System.err.println(ex);
    }

}

From source file:bucks.GenerateChecks.java

License:Open Source License

void generate_gc(Document document, int seq, String value, Image image, PdfWriter writer) {
    try {//from w w w  .j  a v  a  2  s  . co  m
        float[] widths = { 13f, 54f, 33f }; // percents
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.setSpacingAfter(0f);
        table.setSpacingBefore(0f);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(46f);
        table.addCell(cell);
        Phrase phrase = new Phrase();
        Chunk ch = new Chunk("FARMERS' MARKET GIFT CERTIFICATE\n", fntb2);
        phrase.add(ch);
        ch = new Chunk("Parks & Recreation\nBloomington, IN", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Issue Date__________ ", fnt10);
        phrase.add(ch);
        ch = new Chunk("No. " + seq, fnt10);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is good for ", fnt);
        phrase.add(ch);
        ch = new Chunk("$" + value + ".00 ", fntb2);
        phrase.add(ch);
        ch = new Chunk("towards the purchase of ", fnt);
        phrase.add(ch);
        ch = new Chunk("products from ", fnt);
        phrase.add(ch);
        ch = new Chunk("the Bloomington Community Farmers' Market and A Fair of The Arts Vendors. ", fnt);
        phrase.add(ch);
        ch = new Chunk("Change may be given. \n", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setColspan(3);
        cell.setFixedHeight(48f);
        table.addCell(cell);
        document.add(table);
        //
        float[] widths2 = { 60f, 25f, 10f, 5f };
        table = new PdfPTable(widths2);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0f);
        table.setSpacingAfter(0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        //
        phrase = new Phrase();
        ch = new Chunk("Customers shall redeem this certificate at Market\nwithin one year of date issued. ",
                fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setColspan(2);

        cell.setFixedHeight(81f);
        table.addCell(cell);

        Barcode barcode = BarcodeFactory.createCode39("" + seq, true);
        barcode.setDrawingText(false);
        BufferedImage bi = BarcodeImageHandler.getImage(barcode);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //
        ImageIO.write(bi, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        //
        Image barCodeImage = Image.getInstance(imageBytes);

        barCodeImage.setRotationDegrees(90);
        // barCodeImage.scalePercent(35f);
        barCodeImage.scalePercent(35f, 50f);
        cell = new PdfPCell(barCodeImage);
        //
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        table.addCell(cell);
        //
        // adding text underneath the barcode
        //
        int textWidth = 53, textHeight = 50;
        BufferedImage bi2 = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = bi2.createGraphics();
        g.setFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 10));
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, textWidth, textHeight);
        g.setColor(Color.BLACK);
        g.drawString("" + seq, 5, 10);

        g.dispose();
        baos = new ByteArrayOutputStream();
        ImageIO.write(bi2, "png", baos);
        imageBytes = baos.toByteArray();
        Image barCodeTextImage = Image.getInstance(imageBytes);

        barCodeTextImage.setRotationDegrees(90f);
        cell = new PdfPCell(barCodeTextImage);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is not refundable and cannot be replaced if lost or stolen.\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(30f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("\nMust have official stamp to be valid.\n\n", fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setColspan(3);
        table.addCell(cell);
        document.add(table);
        //
        float[] widths3 = { 40f, 60f }; // percentages         
        table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

        phrase = new Phrase();
        ch = new Chunk("APPROVED BY THE STATE BOARD OF ACCOUNTS\nFOR THE CITY OF BLOOMINGTON, IN 2007\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        // cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setFixedHeight(44f);
        table.addCell(cell);
        phrase = new Phrase();
        ch = new Chunk(
                "VENDERS SHALL REDEEM THIS CERTIFICATE THROUGH BLOOMINGTON'S\nPARKS & REC DEPT. BY DECEMBER 15TH OF THE YEAR RECEIVED\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);

        document.add(table);
        // document.add( Chunk.NEWLINE );
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:classroom.filmfestival_b.Movies14.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//from   ww w  .  jav  a  2  s  . c  o  m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies15.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1/*from w  w w .  ja  v a 2s. c o  m*/
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setComplete(false);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        int counter = 10;
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
            if (counter % 10 == 0) {
                document.add(table);
            }
            System.out.println(writer.getPageNumber());
            counter++;
        }
        table.setComplete(true);
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

public static void convertHSSF2Pdf(Workbook wb, String header, File reportFile) throws Exception {
    assert wb != null;
    assert reportFile != null;

    //Precompute formula
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);//  w  ww .  ja  v  a  2  s .  c o m

        for (Row r : sheet) {
            for (Cell c : r) {
                if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                    try {
                        evaluator.evaluateFormulaCell(c);
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                }
            }
        }
    }

    File tmp = File.createTempFile("tmp_", ".xlsx");
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) {
        wb.write(out);
    }

    //Find page orientation
    int maxColumnsGlobal = 0;
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            maxColumnsGlobal = Math.max(maxColumnsGlobal, row.getLastCellNum());
        }
    }

    Rectangle pageSize = maxColumnsGlobal < 10 ? PageSize.A4 : PageSize.A4.rotate();
    Document pdfDocument = new Document(pageSize, 10f, 10f, 20f, 20f);

    PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(reportFile));
    addHeader(writer, header);
    pdfDocument.open();
    //we have two columns in the Excel sheet, so we create a PDF table with two columns
    //Note: There are ways to make this dynamic in nature, if you want to.
    //Loop through sheets
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);

        //Loop through rows, to find number of columns
        int minColumns = 1000;
        int maxColumns = 0;
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            if (row.getFirstCellNum() >= 0)
                minColumns = Math.min(minColumns, row.getFirstCellNum());
            if (row.getLastCellNum() >= 0)
                maxColumns = Math.max(maxColumns, row.getLastCellNum());
        }
        if (maxColumns == 0)
            continue;

        //Loop through first rows, to find relative width
        float[] widths = new float[maxColumns];
        int totalWidth = 0;
        for (int c = 0; c < maxColumns; c++) {
            int w = sheet.getColumnWidth(c);
            widths[c] = w;
            totalWidth += w;
        }

        for (int c = 0; c < maxColumns; c++) {
            widths[c] /= totalWidth;
        }

        //Create new page and a new chapter with the sheet's name
        if (sheetNo > 0)
            pdfDocument.newPage();
        Chapter pdfSheet = new Chapter(sheet.getSheetName(), sheetNo + 1);

        PdfPTable pdfTable = null;
        PdfPCell pdfCell = null;
        boolean inTable = false;

        //Loop through cells, to create the content
        //         boolean leftBorder = true;
        //         boolean[] topBorder = new boolean[maxColumns+1];
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);

            //Check if we exited a table (empty line)
            if (row == null) {
                if (pdfTable != null) {
                    addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
                    pdfTable = null;
                }
                inTable = false;
                continue;
            }

            //Check if we start a table (>MIN_COL_IN_TABLE columns)
            if (row.getLastCellNum() >= MIN_COL_IN_TABLE) {
                inTable = true;
            }

            if (!inTable) {
                //Process the data outside table, just add the text
                boolean hasData = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
                        continue;
                    Chunk chunk = getChunk(wb, cell);
                    pdfSheet.add(chunk);
                    pdfSheet.add(new Chunk(" "));
                    hasData = true;
                }
                if (hasData)
                    pdfSheet.add(Chunk.NEWLINE);

            } else {
                //Process the data in table
                if (pdfTable == null) {
                    //Create table
                    pdfTable = new PdfPTable(maxColumns);
                    pdfTable.setWidths(widths);
                    //                  topBorder = new boolean[maxColumns+1];
                }

                int cellNumber = minColumns;
                //               leftBorder = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    for (; cellNumber < cell.getColumnIndex(); cellNumber++) {
                        pdfCell = new PdfPCell();
                        pdfCell.setBorder(0);
                        pdfTable.addCell(pdfCell);
                    }

                    Chunk phrase = getChunk(wb, cell);
                    pdfCell = new PdfPCell(new Phrase(phrase));
                    pdfCell.setFixedHeight(row.getHeightInPoints() - 3);
                    pdfCell.setNoWrap(!cell.getCellStyle().getWrapText());
                    pdfCell.setPaddingLeft(1);
                    pdfCell.setHorizontalAlignment(
                            cell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER ? PdfPCell.ALIGN_CENTER
                                    : cell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT
                                            ? PdfPCell.ALIGN_RIGHT
                                            : PdfPCell.ALIGN_LEFT);
                    pdfCell.setUseBorderPadding(false);
                    pdfCell.setUseVariableBorders(false);
                    pdfCell.setBorderWidthRight(cell.getCellStyle().getBorderRight() == 0 ? 0 : .5f);
                    pdfCell.setBorderWidthBottom(cell.getCellStyle().getBorderBottom() == 0 ? 0
                            : cell.getCellStyle().getBorderBottom() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthLeft(cell.getCellStyle().getBorderLeft() == 0 ? 0
                            : cell.getCellStyle().getBorderLeft() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthTop(cell.getCellStyle().getBorderTop() == 0 ? 0
                            : cell.getCellStyle().getBorderTop() > 1 ? 1 : .5f);
                    String color = cell.getCellStyle().getFillForegroundColorColor() == null ? null
                            : ((XSSFColor) cell.getCellStyle().getFillForegroundColorColor()).getARGBHex();
                    if (color != null)
                        pdfCell.setBackgroundColor(new Color(Integer.decode("0x" + color.substring(2))));
                    pdfTable.addCell(pdfCell);
                    cellNumber++;
                }
                for (; cellNumber < maxColumns; cellNumber++) {
                    pdfCell = new PdfPCell();
                    pdfCell.setBorder(0);
                    pdfTable.addCell(pdfCell);
                }
            }

            //Custom code to add all images on the first sheet (works for reporting)
            if (sheetNo == 0 && row.getRowNum() == 0) {
                for (PictureData pd : wb.getAllPictures()) {
                    try {
                        Image pdfImg = Image.getInstance(pd.getData());
                        pdfImg.scaleToFit(
                                pageSize.getWidth() * .8f - pageSize.getBorderWidthLeft()
                                        - pageSize.getBorderWidthRight(),
                                pageSize.getHeight() * .8f - pageSize.getBorderWidthTop()
                                        - pageSize.getBorderWidthBottom());
                        pdfSheet.add(pdfImg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (pdfTable != null) {
            addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
        }

        pdfDocument.add(pdfSheet);
    }
    pdfDocument.close();

}

From source file:com.allinfinance.system.util.PdfUtil.java

License:Open Source License

public static void create(String mchtId, String selMchtId, String path, List<Object[]> list,
        LinkedHashMap<String, List<Object[]>> map, Set<String> set) throws Exception {

    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

    ////from   w  ww .  j av  a2s  .  c om
    Font font17 = new Font(bfChinese, 17, Font.BOLD);
    Font font8 = new Font(bfChinese, 8, Font.NORMAL);
    Font font9 = new Font(bfChinese, 9, Font.NORMAL);
    Font font9Bold = new Font(bfChinese, 9, Font.BOLD);
    Font font8Red = new Font(bfChinese, 8, Font.NORMAL);
    font8Red.setColor(Color.RED);
    Font font8Green = new Font(bfChinese, 8, Font.NORMAL);
    font8Green.setColor(Color.GREEN);

    logger.info("Starting build document...");

    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();
    LINECANVAS border = new LINECANVAS();

    //
    float[] widths = { 0.1f, 0.35f, 0.35f, 0.1f, 0.1f };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.getDefaultCell().setFixedHeight(12);

    //CELL
    PdfPCell cellMchntId = new PdfPCell(new Paragraph(mchtId, font8));
    cellMchntId.setBorder(PdfPCell.BOTTOM);
    cellMchntId.setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell cellMchntName = new PdfPCell(new Paragraph(InformationUtil.getMchtName(mchtId), font8));
    cellMchntName.setBorder(PdfPCell.BOTTOM);
    cellMchntName.setHorizontalAlignment(Element.ALIGN_CENTER);

    String point = InformationUtil.getCurPaperPoint(selMchtId);
    PdfPCell cellPoint;
    cellPoint = new PdfPCell(new Paragraph(point, font8Red));
    cellPoint.setBorder(PdfPCell.NO_BORDER);
    cellPoint.setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell cellLevel;
    String level = InformationUtil.getCurPaperLevel(selMchtId);
    if (Integer.valueOf(point) >= 60) {
        cellLevel = new PdfPCell(new Paragraph(level, font8Green));
    } else {
        cellLevel = new PdfPCell(new Paragraph(level, font8Red));
    }
    cellLevel.setBorder(PdfPCell.NO_BORDER);
    cellLevel.setHorizontalAlignment(Element.ALIGN_CENTER);

    //
    Image img = Image.getInstance(
            ServletActionContext.getServletContext().getResource("/ext/resources/images/Title_logo.gif"));
    img.scalePercent(70);
    float w = img.getScaledWidth();
    float h = img.getScaledHeight();
    writer.getDirectContent().addImage(img, w, 0, 0, h, 36, PageSize.A4.getHeight() - 36 - h);

    //
    PdfPCell cell = new PdfPCell(new Paragraph("?", font17));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setColspan(5);
    cell.setFixedHeight(h);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setFixedHeight(20);
    cell.setColspan(5);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    table.addCell(new Paragraph("?", font8));
    table.addCell(cellMchntId);
    table.addCell(" ");
    table.addCell(new Paragraph(": ", font8));
    table.addCell(cellPoint);

    table.addCell(new Paragraph("??", font8));
    table.addCell(cellMchntName);
    table.addCell(" ");
    table.addCell(new Paragraph(": ", font8));
    table.addCell(cellLevel);

    document.add(table);
    document.add(new Paragraph("\n\n"));

    //?
    PdfPTable t = new PdfPTable(1);

    Iterator<Object[]> it0 = list.iterator();
    int i = 1;
    while (it0.hasNext()) {
        Object[] obj = it0.next();
        PdfPCell c = new PdfPCell();
        c.addElement(new Paragraph("Q" + String.valueOf(i++) + "" + obj[1].toString(), font9Bold));
        List<Object[]> opts = map.get(obj[0].toString());
        String opt = "";
        Iterator<Object[]> it1 = opts.iterator();
        while (it1.hasNext()) {
            Object[] o = it1.next();
            if (set.contains(o[0])) {
                opt += "? ";
                opt += o[1].toString();
                opt += "         ";
            } else {
                opt += " ";
                opt += o[1].toString();
                opt += "         ";
            }
        }
        c.addElement(new Paragraph(opt.trim(), font9));
        c.setBorder(PdfPCell.NO_BORDER);
        if (i - 1 != list.size()) {
            c.setCellEvent(border);
        }
        t.addCell(c);
    }

    PdfPTable oTable = new PdfPTable(1);
    oTable.setWidthPercentage(100);
    PdfPCell ce = new PdfPCell(t);
    ce.setBorderColor(Color.GRAY);
    oTable.addCell(ce);

    document.add(oTable);

    document.close();

    logger.info("Finish build document...");

}

From source file:com.allinfinance.system.util.PdfUtil.java

License:Open Source License

public static void create(String path, List<Object[]> list, LinkedHashMap<String, List<Object[]>> map)
        throws Exception {

    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

    ////from   w  ww.j  a v  a 2  s . c om
    Font font17 = new Font(bfChinese, 17, Font.BOLD);
    Font font8 = new Font(bfChinese, 8, Font.NORMAL);
    Font font10 = new Font(bfChinese, 10, Font.NORMAL);
    Font font10Bold = new Font(bfChinese, 10, Font.BOLD);
    Font font8Red = new Font(bfChinese, 8, Font.NORMAL);
    font8Red.setColor(Color.RED);
    Font font8Green = new Font(bfChinese, 8, Font.NORMAL);
    font8Green.setColor(Color.GREEN);

    logger.info("Starting build document...");

    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();
    LINECANVAS border = new LINECANVAS();

    //
    float[] widths = { 0.1f, 0.35f, 0.55f };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.getDefaultCell().setFixedHeight(12);

    //CELL
    PdfPCell cellMchntId = new PdfPCell(new Paragraph("XXXXXXXXXXXXXXX", font8));
    cellMchntId.setBorder(PdfPCell.BOTTOM);
    cellMchntId.setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell cellMchntName = new PdfPCell(new Paragraph("?", font8));
    cellMchntName.setBorder(PdfPCell.BOTTOM);
    cellMchntName.setHorizontalAlignment(Element.ALIGN_CENTER);

    //
    Image img = Image.getInstance(
            ServletActionContext.getServletContext().getResource("/ext/resources/images/Title_logo.gif"));
    img.scalePercent(70);
    float w = img.getScaledWidth();
    float h = img.getScaledHeight();
    writer.getDirectContent().addImage(img, w, 0, 0, h, 36, PageSize.A4.getHeight() - 36 - h);

    //
    PdfPCell cell = new PdfPCell(new Paragraph("?", font17));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setColspan(3);
    cell.setFixedHeight(h);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setFixedHeight(20);
    cell.setColspan(3);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    table.addCell(new Paragraph("?", font8));
    table.addCell(cellMchntId);
    table.addCell(" ");

    table.addCell(new Paragraph("??", font8));
    table.addCell(cellMchntName);
    table.addCell(" ");

    document.add(table);
    document.add(new Paragraph("\n\n"));

    //?
    PdfPTable t = new PdfPTable(1);

    Iterator<Object[]> it0 = list.iterator();
    int i = 1;
    while (it0.hasNext()) {
        Object[] obj = it0.next();
        PdfPCell c = new PdfPCell();
        c.addElement(new Paragraph("Q" + String.valueOf(i++) + "" + obj[1].toString(), font10Bold));
        List<Object[]> opts = map.get(obj[0].toString());
        String opt = "";
        Iterator<Object[]> it1 = opts.iterator();
        while (it1.hasNext()) {
            Object[] o = it1.next();
            opt += " ";
            opt += o[1].toString();
            opt += "         ";
        }
        c.addElement(new Paragraph(opt.trim(), font10));
        c.setBorder(PdfPCell.NO_BORDER);
        if (i - 1 != list.size()) {
            c.setCellEvent(border);
        }
        t.addCell(c);
    }

    PdfPTable oTable = new PdfPTable(1);
    oTable.setWidthPercentage(100);
    PdfPCell ce = new PdfPCell(t);
    ce.setBorderColor(Color.GRAY);
    oTable.addCell(ce);

    document.add(oTable);

    document.close();

    logger.info("Finish build document...");

}

From source file:com.efficio.fieldbook.service.LabelPrintingServiceImpl.java

License:Open Source License

/**
 * Gets the cell height.//from www .j av  a 2s.c  o m
 *
 * @param numberOfRowsPerPage the number of rows per page
 * @param pageSizeId the page size id
 * @return the cell height
 */
/*
private float getCellHeight(int numberOfRowsPerPage, int pageSizeId){
if(pageSizeId == AppConstants.SIZE_OF_PAPER_A4){
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 97f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;
    }
}else{
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 98.1f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;//ok
    }
}
           
return 0f;
}
*/
/* (non-Javadoc)
 * @see com.efficio.fieldbook.service.api.LabelPrintingService#generateLabels(com.efficio.fieldbook.web.fieldmap.bean.UserFieldmap)
 */
@Override
public String generatePDFLabels(List<StudyTrialInstanceInfo> trialInstances,
        UserLabelPrinting userLabelPrinting, ByteArrayOutputStream baos) throws MiddlewareQueryException {

    // setUserLabelPrinting(form.getUserLabelPrinting());
    int pageSizeId = Integer.parseInt(userLabelPrinting.getSizeOfLabelSheet());
    int numberOfLabelPerRow = Integer.parseInt(userLabelPrinting.getNumberOfLabelPerRow());
    int numberofRowsPerPageOfLabel = Integer.parseInt(userLabelPrinting.getNumberOfRowsPerPageOfLabel());
    int totalPerPage = numberOfLabelPerRow * numberofRowsPerPageOfLabel;
    String leftSelectedFields = userLabelPrinting.getLeftSelectedLabelFields();
    String rightSelectedFields = userLabelPrinting.getRightSelectedLabelFields();
    String barcodeNeeded = userLabelPrinting.getBarcodeNeeded();

    String firstBarcodeField = userLabelPrinting.getFirstBarcodeField();
    String secondBarcodeField = userLabelPrinting.getSecondBarcodeField();
    String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField();

    String currentDate = DateUtil.getCurrentDate();
    // String fileName = currentDate + ".pdf";

    String fileName = userLabelPrinting.getFilenameDLLocation();

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);

        try {

            // Image image1 = Image.getInstance(imageLocation);

            // PageSize.A4
            LabelPaper paper = LabelPaperFactory.generateLabelPaper(numberOfLabelPerRow,
                    numberofRowsPerPageOfLabel, pageSizeId);

            Rectangle pageSize = PageSize.LETTER;

            if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4.getInt())
                pageSize = PageSize.A4;

            Document document = new Document(pageSize);
            /*
             * 2, 2, 33.3f, 5
             * 15, 0, 42, 5
             * 10, 0, 17, 5
             * 10, 0, 17, 5
             * 5, 0, 0, 5
             * 15, 0, 37, 5
             * 10, 0, 17, 5
            if (pageSizeId == AppConstants.SIZE_OF_PAPER_LETTER) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(10, 0, 17, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(5, 0, 0, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(2, 2, 33.3f, 5);
            } else if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(15, 0, 42, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(15, 0, 37, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(6, 2, 17.5f, 5);
            }
            */
            //float marginLeft, float marginRight, float marginTop, float marginBottom
            document.setMargins(paper.getMarginLeft(), paper.getMarginRight(), paper.getMarginTop(),
                    paper.getMarginBottom());

            // PdfWriter writer = PdfWriter.getInstance(document, baos);
            PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
            // step 3
            document.open();
            // step 4

            PdfContentByte canvas = writer.getDirectContent();

            int i = 0;
            int fixTableRowSize = numberOfLabelPerRow;
            PdfPTable table = new PdfPTable(fixTableRowSize);

            // table.writeSelectedRows(0, -1, 10, 12, canvas);
            float columnWidthSize = 265f;// 180f;
            float[] widthColumns = new float[fixTableRowSize];

            for (int counter = 0; counter < widthColumns.length; counter++) {
                widthColumns[counter] = columnWidthSize;
            }

            table.setWidths(widthColumns);
            table.setWidthPercentage(100);
            int width = 600;
            int height = 75;

            List<File> filesToBeDeleted = new ArrayList<File>();
            //float cellHeight = getCellHeight(numberofRowsPerPageOfLabel, pageSizeId);
            float cellHeight = paper.getCellHeight();

            for (StudyTrialInstanceInfo trialInstance : trialInstances) {
                FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance();

                Map<String, String> moreFieldInfo = new HashMap<String, String>();
                moreFieldInfo.put("locationName", fieldMapTrialInstanceInfo.getLocationName());
                moreFieldInfo.put("blockName", fieldMapTrialInstanceInfo.getBlockName());
                moreFieldInfo.put("selectedName", trialInstance.getFieldbookName());
                moreFieldInfo.put("trialInstanceNumber", fieldMapTrialInstanceInfo.getTrialInstanceNo());

                for (FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) {

                    i++;
                    String barcodeLabel = generateBarcodeField(moreFieldInfo, fieldMapLabel, firstBarcodeField,
                            secondBarcodeField, thirdBarcodeField, barcodeNeeded);
                    if ("0".equalsIgnoreCase(barcodeNeeded)) {
                        barcodeLabel = " ";
                    }

                    BitMatrix bitMatrix = new Code128Writer().encode(barcodeLabel, BarcodeFormat.CODE_128,
                            width, height, null);
                    String imageLocation = System.getProperty("user.home") + "/" + Math.random() + ".png";
                    File imageFile = new File(imageLocation);
                    FileOutputStream fout = new FileOutputStream(imageFile);
                    MatrixToImageWriter.writeToStream(bitMatrix, "png", fout);
                    filesToBeDeleted.add(imageFile);

                    Image mainImage = Image.getInstance(imageLocation);

                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(cellHeight);
                    cell.setNoWrap(false);
                    cell.setPadding(5f);
                    cell.setPaddingBottom(1f);

                    PdfPTable innerImageTableInfo = new PdfPTable(1);
                    innerImageTableInfo.setWidths(new float[] { 1 });
                    innerImageTableInfo.setWidthPercentage(82);
                    PdfPCell cellImage = new PdfPCell();
                    if ("1".equalsIgnoreCase(barcodeNeeded)) {
                        cellImage.addElement(mainImage);
                    } else {
                        cellImage.addElement(new Paragraph(" "));
                    }
                    cellImage.setBorder(Rectangle.NO_BORDER);
                    cellImage.setBackgroundColor(Color.white);
                    cellImage.setPadding(1.5f);

                    innerImageTableInfo.addCell(cellImage);

                    //float fontSize = 6.8f;
                    float fontSize = paper.getFontSize();
                    //if (numberofRowsPerPageOfLabel == 10)
                    //    fontSize = 4.8f;

                    Font fontNormal = FontFactory.getFont("Arial", fontSize, Font.NORMAL);

                    // cell.addElement(mainImage);
                    cell.addElement(innerImageTableInfo);

                    cell.addElement(new Paragraph());
                    for (int row = 0; row < 5; row++) {
                        if (row == 0) {
                            PdfPTable innerDataTableInfo = new PdfPTable(1);
                            innerDataTableInfo.setWidths(new float[] { 1 });
                            innerDataTableInfo.setWidthPercentage(85);

                            Font fontNormalData = FontFactory.getFont("Arial", 5.0f, Font.NORMAL);
                            PdfPCell cellInnerData = new PdfPCell(new Phrase(barcodeLabel, fontNormalData));

                            cellInnerData.setBorder(Rectangle.NO_BORDER);
                            cellInnerData.setBackgroundColor(Color.white);
                            cellInnerData.setPaddingBottom(0.2f);
                            cellInnerData.setPaddingTop(0.2f);
                            cellInnerData.setHorizontalAlignment(Element.ALIGN_MIDDLE);

                            innerDataTableInfo.addCell(cellInnerData);
                            innerDataTableInfo.setHorizontalAlignment(Element.ALIGN_MIDDLE);
                            cell.addElement(innerDataTableInfo);
                        }
                        PdfPTable innerTableInfo = new PdfPTable(2);
                        innerTableInfo.setWidths(new float[] { 1, 1 });
                        innerTableInfo.setWidthPercentage(85);

                        String leftText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel, leftSelectedFields,
                                row);
                        PdfPCell cellInnerLeft = new PdfPCell(new Paragraph(leftText, fontNormal));

                        cellInnerLeft.setBorder(Rectangle.NO_BORDER);
                        cellInnerLeft.setBackgroundColor(Color.white);
                        cellInnerLeft.setPaddingBottom(0.5f);
                        cellInnerLeft.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerLeft);

                        String rightText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel,
                                rightSelectedFields, row);
                        PdfPCell cellInnerRight = new PdfPCell(new Paragraph(rightText, fontNormal));

                        cellInnerRight.setBorder(Rectangle.NO_BORDER);
                        cellInnerRight.setBackgroundColor(Color.white);
                        cellInnerRight.setPaddingBottom(0.5f);
                        cellInnerRight.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerRight);

                        cell.addElement(innerTableInfo);
                    }

                    cell.setBorder(Rectangle.NO_BORDER);
                    cell.setBackgroundColor(Color.white);

                    //cell.setBorderColor(Color.BLUE);

                    table.addCell(cell);

                    if (i % numberOfLabelPerRow == 0) {
                        // we go the next line

                        int needed = fixTableRowSize - numberOfLabelPerRow;

                        for (int neededCount = 0; neededCount < needed; neededCount++) {
                            PdfPCell cellNeeded = new PdfPCell();

                            cellNeeded.setBorder(Rectangle.NO_BORDER);
                            cellNeeded.setBackgroundColor(Color.white);

                            table.addCell(cellNeeded);
                        }

                        table.completeRow();
                        if (numberofRowsPerPageOfLabel == 10) {

                            //table.setSpacingAfter(9f);
                            table.setSpacingAfter(paper.getSpacingAfter());
                        }

                        document.add(table);

                        table = new PdfPTable(fixTableRowSize);
                        table.setWidths(widthColumns);
                        table.setWidthPercentage(100);

                    }
                    if (i % totalPerPage == 0) {
                        // we go the next page
                        document.newPage();
                    }
                    fout.flush();
                    fout.close();

                }
            }
            // we need to add the last row
            if (i % numberOfLabelPerRow != 0) {
                // we go the next line

                int needed = fixTableRowSize - numberOfLabelPerRow;
                int remaining = numberOfLabelPerRow - (i % numberOfLabelPerRow);
                for (int neededCount = 0; neededCount < remaining; neededCount++) {
                    PdfPCell cellNeeded = new PdfPCell();

                    cellNeeded.setBorder(Rectangle.NO_BORDER);
                    cellNeeded.setBackgroundColor(Color.white);

                    table.addCell(cellNeeded);
                }

                table.completeRow();
                if (numberofRowsPerPageOfLabel == 10) {

                    table.setSpacingAfter(paper.getSpacingAfter());
                }

                document.add(table);

                table = new PdfPTable(fixTableRowSize);
                table.setWidths(widthColumns);
                table.setWidthPercentage(100);

            }

            document.close();
            for (File file : filesToBeDeleted) {
                file.delete();
            }
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

    } catch (WriterException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return fileName;
}