Example usage for com.lowagie.text Image setAbsolutePosition

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

Introduction

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

Prototype


public void setAbsolutePosition(float absoluteX, float absoluteY) 

Source Link

Document

Sets the absolute position of the Image.

Usage

From source file:questions.images.PostCardExtra.java

public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.POSTCARD);
    try {//  w w  w.  j a va  2s .c  o m
        // step 2:
        // we create a writer
        PdfWriter writer = PdfWriter.getInstance(
                // that listens to the document
                document,
                // and directs a PDF-stream to a file
                new FileOutputStream(RESULT));
        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document
        Image img = Image.getInstance(RESOURCE);
        img.scaleToFit(PageSize.POSTCARD.getWidth(), 10000);
        img.setAbsolutePosition(0, 0);
        PdfImage stream = new PdfImage(img, "", null);
        stream.put(new PdfName("MySpecialId"), new PdfName("123456789"));
        PdfIndirectObject ref = writer.addToBody(stream);
        img.setDirectReference(ref.getIndirectReference());
        document.add(img);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

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

From source file:questions.images.TransparentEllipse1.java

public static void main(String[] args) {
    Document document = new Document(PageSize.POSTCARD);
    try {/*from  w w w  .j a  v  a2s.co m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        Image img = Image.getInstance(RESOURCE);
        byte[] bytes = new byte[2500];
        int byteCount = 0;
        int bitCount = 6;
        for (int x = -50; x < 50; x++) {
            for (int y = -50; y < 50; y++) {
                double rSquare = Math.pow(x, 2) + Math.pow(y, 2);
                if (rSquare <= 1600) { // 40
                    bytes[byteCount] += (3 << bitCount);
                } else if (rSquare <= 2025) { // 45
                    bytes[byteCount] += (2 << bitCount);
                } else if (rSquare <= 2500) { // 50
                    bytes[byteCount] += (1 << bitCount);
                }
                bitCount -= 2;
                if (bitCount < 0) {
                    bitCount = 6;
                    byteCount++;
                }
            }
        }
        Image smask = Image.getInstance(100, 100, 1, 2, bytes);
        smask.makeMask();
        img.setImageMask(smask);
        img.setAbsolutePosition(0, 0);
        img.scaleToFit(PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());
        writer.getDirectContent().addImage(img);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();
}

From source file:questions.images.TransparentPng.java

public static final void main(String[] args) throws IOException, DocumentException {
    Image img = Image.getInstance(IMAGE);
    Rectangle rectangle = new Rectangle(img);
    rectangle.setBackgroundColor(Color.YELLOW);
    Document document = new Document(rectangle);
    PdfWriter.getInstance(document, new FileOutputStream(RESULT));
    document.open();/*  ww  w. j av  a 2  s.  co  m*/
    img.setAbsolutePosition(0, 0);
    document.add(img);
    document.close();
}

From source file:questions.importpages.NameCard.java

public static void createOneCard() throws DocumentException, IOException {
    Rectangle rect = new Rectangle(Utilities.millimetersToPoints(86.5f), Utilities.millimetersToPoints(55));
    Document document = new Document(rect);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(CARD));
    writer.setViewerPreferences(PdfWriter.PrintScalingNone);
    document.open();//from  w ww . j  av  a2  s.c  o  m
    PdfReader reader = new PdfReader(LOGO);
    Image img = Image.getInstance(writer.getImportedPage(reader, 1));
    img.scaleToFit(rect.getWidth() / 1.5f, rect.getHeight() / 1.5f);
    img.setAbsolutePosition((rect.getWidth() - img.getScaledWidth()) / 2,
            (rect.getHeight() - img.getScaledHeight()) / 2);
    document.add(img);
    document.newPage();
    BaseFont bf = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    Font font = new Font(bf, 12);
    font.setColor(new CMYKColor(1, 0.5f, 0, 0.467f));
    ColumnText column = new ColumnText(writer.getDirectContent());
    Paragraph p;
    p = new Paragraph("Bruno Lowagie\n1T3XT\nbruno@1t3xt.com", font);
    p.setAlignment(Element.ALIGN_CENTER);
    column.addElement(p);
    column.setSimpleColumn(0, 0, rect.getWidth(), rect.getHeight() * 0.75f);
    column.go();
    document.close();
}

From source file:questions.ocg.AddOptionalWatermark.java

public static void main(String[] args) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(RESOURCE);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    Image image1 = Image.getInstance(IMAGE_PRINTED);
    Image image2 = Image.getInstance(IMAGE_NOT_PRINTED);
    PdfLayer watermark_printed = new PdfLayer("printed", stamper.getWriter());
    watermark_printed.setOn(false);/* w  w w . j  a  v  a 2 s. c o m*/
    watermark_printed.setOnPanel(false);
    watermark_printed.setPrint("print", true);
    PdfLayer watermark_not_printed = new PdfLayer("not_printed", stamper.getWriter());
    watermark_not_printed.setOn(true);
    watermark_not_printed.setOnPanel(false);
    watermark_not_printed.setPrint("print", false);
    for (int i = 0; i < stamper.getReader().getNumberOfPages();) {
        PdfContentByte cb = stamper.getUnderContent(++i);
        Rectangle rectangle = stamper.getReader().getPageSizeWithRotation(i);
        cb.beginLayer(watermark_printed);
        float AbsoluteX = rectangle.getLeft() + (rectangle.getWidth() - image1.getPlainWidth()) / 2;
        float AbsoluteY = rectangle.getBottom() + (rectangle.getHeight() - image1.getPlainHeight()) / 2;
        image1.setAbsolutePosition(AbsoluteX, AbsoluteY);
        cb.addImage(image1);
        cb.endLayer();
        cb.beginLayer(watermark_not_printed);
        AbsoluteX = rectangle.getLeft() + (rectangle.getWidth() - image2.getPlainWidth()) / 2;
        AbsoluteY = rectangle.getBottom() + (rectangle.getHeight() - image2.getPlainHeight()) / 2;
        image2.setAbsolutePosition(AbsoluteX, AbsoluteY);
        cb.addImage(image2);
        cb.endLayer();
    }
    stamper.close();
}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape//from ww  w .  j  a v  a 2s  .  c om
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

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

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

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

From source file:sms.ReportForms.java

public void utext(String query, String Name, String dob, String house, String formclass, String kcpe,
        String imgurl, String kcpegrade, String id) {
    methods nn = new methods();
    String u = unig();/*from w  w w  .  ja  va2 s. c  o  m*/
    checkPreviousResults(u, kcpe, kcpegrade, id);
    ArrayList<ExamDbDataHolder> users = selectExamResults(u, query);
    if (users.size() < 2) {
        Form1Exams n = new Form1Exams();
        String[] Subjects = n.findSubjectid();
        String[] Subjectsnames = n.findSubjectname();

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File(","));
        chooser.setDialogTitle("Save at");
        chooser.setApproveButtonText("save");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {

                Document pdfp = new Document();
                PdfWriter w = PdfWriter.getInstance(pdfp,
                        new FileOutputStream(new File(chooser.getSelectedFile(), "" + sid.getText() + ".pdf")));
                pdfp.open();
                PdfContentByte canvas = w.getDirectContentUnder();
                Image imgb = Image.getInstance("C:\\Users\\kimani kogi\\Pictures\\icons\\logo.png");
                imgb.setAbsolutePosition(2, 2);
                imgb.scaleAbsoluteHeight(PageSize.A4.getHeight() / 4);
                imgb.scaleAbsoluteWidth(PageSize.A4.getWidth() / 4);
                canvas.saveState();
                PdfGState state = new PdfGState();
                state.setFillOpacity(0.6f);
                canvas.setGState(state);
                canvas.addImage(imgb);
                canvas.restoreState();

                PdfPTable tbl1 = new PdfPTable(2);
                //  tbl.setWidthPercentage(100);

                tbl1.setTotalWidth(575);
                tbl1.setLockedWidth(true);

                tbl1.setWidths(new int[] { 1, 4 });
                if (imgurl.equals("image")) {
                    tbl1.addCell("no image ");

                    String img = imgurl;
                } else {
                    tbl1.addCell(createImageCell(imgurl));

                }

                tbl1.addCell(createTextCell(schooldetails));

                PdfPTable tbl = new PdfPTable(8);
                //  tbl.setWidthPercentage(100);
                tbl.setTotalWidth(575);
                tbl.setLockedWidth(true);
                tbl.setSpacingBefore(8);
                tbl.setSpacingAfter(6);
                tbl.getDefaultCell().setBorderWidthTop(2);
                tbl.getDefaultCell().setBorderWidthLeft(0);
                tbl.getDefaultCell().setBorderWidthRight(0);
                tbl.setWidths(new int[] { 1, 1, 1, 2, 1, 1, 1, 1 });
                tbl.addCell("Adm No:");
                tbl.addCell(sid.getText());
                tbl.addCell("Name:");
                tbl.addCell(Name);
                tbl.addCell("Form:");
                tbl.addCell(formclass);
                tbl.addCell("Kcpe:");
                tbl.addCell(kcpe);

                tbl.addCell("House:");
                tbl.addCell(house);
                tbl.addCell("Term:");
                tbl.addCell("Second term");
                tbl.addCell("Year:");
                tbl.addCell("2017");
                tbl.addCell("DOB:");
                tbl.addCell(dob);

                PdfPTable tbl2 = new PdfPTable(5);
                //  tbl.setWidthPercentage(100);
                tbl2.setTotalWidth(575);
                tbl2.setLockedWidth(true);
                //  tbl2.getDefaultCell().setFixedHeight(35f);
                tbl2.setWidths(new int[] { 2, 1, 1, 2, 2 });

                tbl2.addCell(creatTextCellHeader("Subjects"));
                tbl2.addCell(creatTextCellHeader("Exams"));
                tbl2.addCell(creatTextCellHeader("Grade"));
                tbl2.addCell(creatTextCellHeader("Ratings"));
                tbl2.addCell(creatTextCellHeader("Remarks"));
                // String []  Subjectsnames=n.findSubjectname();
                for (int i = 0; i < users.size(); i++) {
                    for (int a = 0; a < Subjectsnames.length; a++) {
                        tbl2.addCell(Subjectsnames[a]);
                        String re = null;
                        if (Subjects[a].equals("s1")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getMathematics());
                            re = ((ExamDbDataHolder) users.get(i)).getMathematics();
                            //  JOptionPane.showMessageDialog(null,((ExamDbDataHolder)users.get(i)).getMathematics());
                            // String maths = ((ExamDbDataHolder)users.get(i)).getMathematics();

                        } else if (Subjects[a].equals("s2")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getEnglish());
                            re = ((ExamDbDataHolder) users.get(i)).getEnglish();
                            //row[c] = ((ExamDbDataHolder)users.get(i)).getEnglish();
                            // c++;
                        } else if (Subjects[a].equals("s3")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getKiswahili());
                            re = ((ExamDbDataHolder) users.get(i)).getKiswahili();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getKiswahili();
                            // c++;
                        }

                        else if (Subjects[a].equals("s4")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getPhysics());
                            re = ((ExamDbDataHolder) users.get(i)).getPhysics();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getPhysics();
                            //  c++;
                        } else if (Subjects[a].equals("s5")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getChemistry());
                            re = ((ExamDbDataHolder) users.get(i)).getChemistry();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getChemistry();
                            // c++;
                        } else if (Subjects[a].equals("s6")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getBiology());
                            re = ((ExamDbDataHolder) users.get(i)).getBiology();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getBiology();
                            //  c++;
                        } else if (Subjects[a].equals("s7")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getHistory());
                            re = ((ExamDbDataHolder) users.get(i)).getHistory();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getHistory();
                            //  c++;
                        } else if (Subjects[a].equals("s8")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getGeography());
                            re = ((ExamDbDataHolder) users.get(i)).getGeography();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getGeography();
                            // c++;
                        } else if (Subjects[a].equals("s9")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getCre());
                            re = ((ExamDbDataHolder) users.get(i)).getCre();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getCre();
                            //  c++;
                        } else if (Subjects[a].equals("s10")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getIre());
                            re = ((ExamDbDataHolder) users.get(i)).getIre();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getIre();
                            //  c++;
                        } else if (Subjects[a].equals("s11")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getHre());
                            re = ((ExamDbDataHolder) users.get(i)).getHre();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getHre();
                            //  c++;
                        } else if (Subjects[a].equals("s12")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getAgriculture());
                            re = ((ExamDbDataHolder) users.get(i)).getAgriculture();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getAgriculture();
                            //  c++;
                        } else if (Subjects[a].equals("s13")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getHomescience());
                            re = ((ExamDbDataHolder) users.get(i)).getHomescience();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getHomescience();
                            //  c++;
                        } else if (Subjects[a].equals("s14")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getArtdesign());
                            re = ((ExamDbDataHolder) users.get(i)).getArtdesign();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getArtdesign();
                            //  c++;
                        } else if (Subjects[a].equals("s15")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getComputer());
                            re = ((ExamDbDataHolder) users.get(i)).getComputer();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getComputer();
                            // c++;

                        } else if (Subjects[a].equals("s16")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getBuilding());
                            re = ((ExamDbDataHolder) users.get(i)).getBuilding();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getBuilding();
                            //  c++;
                        } else if (Subjects[a].equals("s17")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getWoodwork());
                            re = ((ExamDbDataHolder) users.get(i)).getWoodwork();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getWoodwork();
                            // c++;
                        } else if (Subjects[a].equals("s18")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getMetalwork());
                            re = ((ExamDbDataHolder) users.get(i)).getMetalwork();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getMetalwork();
                            // c++;
                        } else if (Subjects[a].equals("s19")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getMusic());
                            re = ((ExamDbDataHolder) users.get(i)).getMusic();
                            //   row[c] = ((ExamDbDataHolder)users.get(i)).getMusic();
                            //  c++;
                        } else if (Subjects[a].equals("s20")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getFrench());
                            re = ((ExamDbDataHolder) users.get(i)).getFrench();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getFrench();
                            // c++;
                        } else if (Subjects[a].equals("s21")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getGerman());
                            re = ((ExamDbDataHolder) users.get(i)).getGerman();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getGerman();
                            // c++;
                        } else if (Subjects[a].equals("s22")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getArabic());
                            re = ((ExamDbDataHolder) users.get(i)).getArabic();
                            // row[c] = ((ExamDbDataHolder)users.get(i)).getArabic();
                            // c++;
                        } else if (Subjects[a].equals("s23")) {
                            tbl2.addCell(((ExamDbDataHolder) users.get(i)).getBusiness());
                            re = ((ExamDbDataHolder) users.get(i)).getBusiness();
                            //  row[c] = ((ExamDbDataHolder)users.get(i)).getBusiness();
                            // c++;
                        }
                        String[] gr = nn.checkGrade(re, Subjects[a]);
                        tbl2.addCell(gr[0]);
                        tbl2.addCell(gr[1]);
                        tbl2.addCell("");
                    }
                }

                //add for all other subjects

                PdfPTable tbl3 = new PdfPTable(4);
                //  tbl.setWidthPercentage(100);
                tbl3.setTotalWidth(575);
                tbl3.setLockedWidth(true);
                tbl3.setSpacingBefore(8);
                tbl3.setSpacingAfter(6);
                //  tbl3.getDefaultCell().setBorderWidthTop(0);
                tbl3.getDefaultCell().setBorder(0);
                //  tbl3.getDefaultCell().setBorderWidthLeft(0);
                //  tbl3.getDefaultCell().setBorderWidthRight(0);
                tbl3.setWidths(new int[] { 1, 1, 1, 1 });
                tbl3.addCell(creatTextCellHeader("CURRENT MARKS:"));
                tbl3.addCell(creatTextCellHeader(String.valueOf(((ExamDbDataHolder) users.get(0)).getTotal())));
                float g = Float.valueOf(((ExamDbDataHolder) users.get(0)).getTotal());
                //  tbl.addCell(String.format("%.1f", g));

                String gr = nn.checkGrade(yearid, String.format("%.1f", g / getYear()));

                tbl3.addCell(creatTextCellHeader("PREVIOUS MARKS:"));
                tbl3.addCell(creatTextCellHeader("459"));
                tbl3.addCell(creatTextCellHeader("AVERAGE MARKS:"));
                tbl3.addCell(creatTextCellHeader(String.format("%.1f", g / getYear())));
                tbl3.addCell(creatTextCellHeader("PREVIOUS AVERAGE:"));
                tbl3.addCell(creatTextCellHeader("50"));
                tbl3.addCell(creatTextCellHeader("MEAN GRADE:"));
                tbl3.addCell(creatTextCellHeader(gr));
                tbl3.addCell(creatTextCellHeader("PREVIOUS MEAN GRADE:"));
                tbl3.addCell(creatTextCellHeader("B"));
                tbl3.addCell(creatTextCellHeader("POS"));
                tbl3.addCell(creatTextCellHeader("3 "));
                tbl3.addCell(creatTextCellHeader("OUT OF"));
                tbl3.addCell(creatTextCellHeader("79"));

                PdfPTable tbl4 = new PdfPTable(2);
                //  tbl.setWidthPercentage(100);
                tbl4.setHorizontalAlignment(0);
                //tbl4.HorizontalAlignment=Element.ALIGN_LEFT;
                tbl4.setTotalWidth(575 / 2);
                tbl4.setLockedWidth(true);
                tbl4.setSpacingBefore(8);
                tbl4.setSpacingAfter(6);
                //  tbl3.getDefaultCell().setBorderWidthTop(0);
                tbl4.getDefaultCell().setBorder(0);
                //  tbl3.getDefaultCell().setBorderWidthLeft(0);
                //  tbl3.getDefaultCell().setBorderWidthRight(0);
                tbl4.setWidths(new int[] { 2, 1 });
                PdfPCell cell = new PdfPCell(new Paragraph("REMARKS"));
                cell.setColspan(2);

                tbl4.addCell(cell);
                tbl4.addCell(creatTextCellHeader(
                        "CLASS TEACHERS........................................................."
                                + ":............................\n\n\n"));
                tbl4.addCell(creatTextCellChart("chart"));
                tbl4.addCell(creatTextCellHeader(
                        "SIGNATURE-------------------------------------------------------------"
                                + "-------------------------------\n\n\n"));
                tbl4.addCell(creatTextCellHeader(
                        "-------------\n\n\n-----------------------------------------------------------"
                                + "-----------------------------"));

                pdfp.add(tbl1);

                pdfp.add(tbl);

                pdfp.add(tbl2);
                pdfp.add(tbl3);
                pdfp.add(tbl4);

                //        Paragraph p=new Paragraph();
                //        p.setAlignment(Element.ALIGN_CENTER);
                //        p.setFont(FontFactory.getFont(FontFactory.TIMES_BOLD,18,Font.BOLD));
                //         Paragraph po=new Paragraph();
                //        po.setAlignment(Element.ALIGN_CENTER);
                //        po.setFont(FontFactory.getFont(FontFactory.TIMES_BOLD,16,Font.BOLD));
                //        
                //        Paragraph pd=new Paragraph();
                //          pd.setAlignment(Element.ALIGN_CENTER);
                //         pd.setFont(FontFactory.getFont(FontFactory.TIMES_BOLD,14,Font.BOLD));
                //        p.add("ITHANGA SECONDARY SCHOOL");
                //        po.add("PO.BOX 238  ITHANGA THIKA");
                //         pd.add(new Date().toString());
                //        pdfp.add(p);
                //        pdfp.add(po);
                //        pdfp.add(pd);
                //         
                //        
                //      
                //        pdfp.add(new Paragraph("\n.................................................................."
                //                + ".................................................................................\n"));
                //         String []names=  n.findSubjectname();
                //        PdfPTable tbl=new PdfPTable(names.length+6);
                //        tbl.setWidths(new float[]{1,1,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1});
                //       // tbl.setWidthPercentage(100);
                //        tbl.setTotalWidth(575);
                //        tbl.setLockedWidth(true);
                //         PdfPTable tbl1=new PdfPTable(names.length+6);
                //        tbl1.setWidths(new float[]{1,1,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1});
                //       // tbl.setWidthPercentage(100);
                //        tbl1.setTotalWidth(575);
                //        tbl1.setLockedWidth(true);
                //     PdfPCell cell=new PdfPCell (new Paragraph("RESULTS"));
                //     cell.setColspan((names.length+4)*2);
                //     cell.setBackgroundColor(Color.CYAN);
                //        tbl1.addCell(cell);
                //        tbl1.addCell("Pos");
                //          tbl1.addCell("id");
                //          tbl1.addCell("Name");
                //          int a;

                pdfp.close();
            } catch (Exception j) {
                j.printStackTrace();
            }

            // Image img=new Image.getInstance("j.png");

        }
    }
}

From source file:za.co.equalpay.web.utils.PDFExportUtility.java

/**
 * Perform the standard PDF PreProcessing: <br>
 * Add Customer logo image and Phrase as header to the first page, <br>
 * Add Line Separator to the bottom of the Image <br>
 * and add the standard footer message to the PDF document<br>
 *
 * @throws MalformedURLException// w w  w  . j  av  a2s . co m
 * @throws IOException
 * @throws DocumentException
 */
public void preProcess() throws MalformedURLException, IOException, DocumentException {
    document.setMargins(50f, 50f, 10f, 20f);

    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
    // Font font = new Font(bf_helv, 8);

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();

    String fontPath = LogoPathFinder.getFontPath(servletContext, "Tahoma");
    BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, true);
    Font tahoma = new Font(bf, 16, Font.BOLD);
    tahoma.setColor(Color.GRAY);

    Font fontBold = new Font(bf, 8, Font.BOLD);
    fontBold.setColor(Color.GRAY);

    Font f = new Font(bf, 8, Font.NORMAL);
    f.setColor(Color.GRAY);

    Font sf = new Font(bf, 6, Font.NORMAL);
    sf.setColor(Color.LIGHT_GRAY);

    // image.setIndentationLeft(360f);
    // PdfPCell imgCell = new PdfPCell(image, false);
    // imgCell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
    // imgCell.setBorder(0);
    //
    // PdfPCell emptyCell = new PdfPCell(new Phrase("TESTING...", tahoma));
    // emptyCell.setBorder(0);
    // PdfPTable footerTable = new PdfPTable(1);
    // footerTable.setWidthPercentage(100);
    //
    //
    // phrase = new Phrase(PDF_FOOTER_MESSAGE, f);
    //
    // PdfPCell cell = new PdfPCell(phrase);
    // cell.setBorder(0);
    // footerTable.addCell(cell);
    // table.setWidths(new int[] { 1, 2 });
    // table.addCell(emptyCell);
    // footerTable.addCell(emptyCell);
    // phrase.add(footerTable);
    // phrase.add(new Chunk(image, 475f, 0));
    // Phrase subPhrase = new Phrase();
    // subPhrase.add(new Phrase("\nwww.meddev.co.za\n", sf));
    // subPhrase.add(new Phrase(PDF_FOOTER_MESSAGE, f));
    // phrase.add(subPhrase);
    // phrase.add(new Chunk("www.meddev.co.za", f));
    // phrase.add(new Phrase(PDF_FOOTER_MESSAGE, f));
    // load document footer
    HeaderFooter footer = new HeaderFooter(new Phrase(PDF_FOOTER_MESSAGE, f), false);
    // HeaderFooter footer = new HeaderFooter(paragraph, false);
    // HeaderFooter footer = new HeaderFooter(phrase, false);

    footer.setAlignment(Element.ALIGN_LEFT);
    footer.setBorder(Rectangle.NO_BORDER);
    document.setFooter(footer);

    // document.open();
    //
    // ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // PdfWriter writer = PdfWriter.getInstance(document, baos);
    //
    // writer.open();
    // PdfContentByte cb = writer.getDirectContent();
    // cb.addImage(image);
    // ColumnText columnText = new ColumnText(cb);
    // load the customer logo
    String logoPath = LogoPathFinder.getPath(servletContext, "meddev-logo2");

    Image image = Image.getInstance(logoPath);
    image.scaleToFit(149, 55);
    image.setIndentationLeft(360f);

    PdfPCell imageCell = new PdfPCell(image, false);
    imageCell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
    imageCell.setBorder(0);

    PdfPCell headerTextCell = new PdfPCell(new Phrase(header, tahoma));
    headerTextCell.setBorder(0);

    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.setWidths(new int[] { 1, 2 });
    table.addCell(headerTextCell);
    table.addCell(imageCell);

    phrase = new Phrase();
    phrase.add(table);

    // load document header
    HeaderFooter header = new HeaderFooter(phrase, false);
    header.setAlignment(Element.ALIGN_CENTER);
    header.setBorder(Rectangle.NO_BORDER);

    document.setHeader(header);

    // create gray line separator
    // Chunk lineSeparator = new Chunk(new LineSeparator(1, 100, Color.GRAY,
    // Element.ALIGN_CENTER, -2));
    // document.add(lineSeparator);
    Font headerFont = new Font(bf_helv, 9);
    // write the header lines for this statement
    phrase = new Phrase(12, "\n", headerFont);
    phrase.add("\n\n");

    // open the pdf document for editing
    document.open();
    document.setPageSize(PageSize.A4);

    // Meddev Information Block
    table = new PdfPTable(4);
    table.setWidthPercentage(100);

    // table.setWidths(new int[] { 25, 25, 30, 20 });
    Phrase phrase1 = new Phrase();
    phrase1.add(new Phrase("MED DEV cc", fontBold));
    phrase1.add(new Phrase("\nUNIT 10, THE CORNER", f));
    phrase1.add(new Phrase("\nc/o Theuns & Hilde Ave", f));
    phrase1.add(new Phrase("\nHennopspark, 0157", f));
    phrase1.add(new Phrase("\nTel: +27 (0) 12 653 3063", f));
    phrase1.add(new Phrase("\nReg No: 2006/166603/23", f));
    phrase1.add(new Phrase("\n", f));

    Phrase phrase2 = new Phrase();
    phrase2.add(new Phrase("VAT No: ", fontBold));
    phrase2.add(new Phrase("4150231498", f));
    phrase2.add(new Phrase("\nImport/Export #: ", fontBold));
    phrase2.add(new Phrase("20544748", f));
    phrase2.add(new Phrase("\n", f));

    Phrase phrase3 = new Phrase();
    phrase3.add(new Phrase("QUOTE NO ", fontBold));
    phrase3.add(new Phrase("\nDATE ", fontBold));
    phrase3.add(new Phrase("\nREFERNCE ", fontBold));
    phrase3.add(new Phrase("\nSUPPLIER CODE ", fontBold));
    phrase3.add(new Phrase("\nEXPIRY DATE ", fontBold));

    Phrase phrase4 = new Phrase();
    //        phrase4.add(new Phrase(quotation.getQuotationNumber(), f));
    //        phrase4.add(new Phrase("\n" + DateFormatter.formatMonthDate(quotation.getQuotationDate()), f));
    //        phrase4.add(new Phrase("\n" + (quotation.getClient().getReference() == null ? "-" : quotation.getClient().getReference()), f));
    //        phrase4.add(new Phrase("\nMEDDEV1", f));
    //        phrase4.add(new Phrase("\n" + DateFormatter.formatMonthDate(quotation.calculateExpiryDate()), f));

    PdfPCell cell1 = new PdfPCell(phrase1);
    cell1.setBorder(0);
    PdfPCell cell2 = new PdfPCell(phrase2);
    cell2.setBorder(0);
    PdfPCell cell3 = new PdfPCell(phrase3);
    cell3.setBorder(0);
    PdfPCell cell4 = new PdfPCell(phrase4);
    cell4.setBorder(0);

    table.addCell(cell1);
    table.addCell(cell2);
    table.addCell(cell3);
    table.addCell(cell4);

    phrase.add(table);

    // create gray line separator
    Chunk lineSeparator = new Chunk(new LineSeparator(1, 100, Color.GRAY, Element.ALIGN_CENTER, -2));
    phrase.add(lineSeparator);

    // Customer Information Block
    table = new PdfPTable(3);
    table.setWidthPercentage(100);
    table.setWidths(new int[] { 5, 2, 3 });

    //        Phrase phrase11 = new Phrase();
    //        phrase11.add(new Phrase(quotation.getClient().getCompany().toUpperCase() + "(CLIENT)", fontBold));
    //        if (quotation.getClient().getVatRegNo() != null && quotation.getClient().getVatRegNo().trim().length() > 0) {
    //            phrase11.add(new Phrase("\nCustomer VAT No: ", fontBold));
    //            phrase11.add(new Phrase(quotation.getClient().getVatRegNo(), f));
    //        }
    //        if (quotation.getClient().getResAddress1() != null && quotation.getClient().getResAddress1().trim().length() > 0) {
    //            phrase11.add(new Phrase("\n" + quotation.getClient().getResAddress1(), f));
    //        }
    //        if (quotation.getClient().getResAddress2() != null && quotation.getClient().getResAddress2().trim().length() > 0) {
    //            phrase11.add(new Phrase("\n" + quotation.getClient().getResAddress2(), f));
    //        }
    //        if (quotation.getClient().getResCity() != null && quotation.getClient().getResCity().trim().length() > 0) {
    //            phrase11.add(new Phrase("\n" + quotation.getClient().getResCity(), f));
    //        }
    //        if (quotation.getClient().getPhone() != null && quotation.getClient().getPhone().trim().length() > 0) {
    //            phrase11.add(new Phrase("\nTel: " + quotation.getClient().getPhone(), f));
    //        }

    //PdfPCell cell11 = new PdfPCell(phrase11);
    //cell11.setBorder(0);

    phrase2 = new Phrase();
    phrase2.add(new Phrase("CURRENCY: ", fontBold));
    PdfPCell cell12 = new PdfPCell(phrase2);
    cell12.setBorder(0);

    phrase3 = new Phrase();
    //phrase3.add(new Phrase(quotation.getClient().getCurrencyCode(), f));
    PdfPCell cell13 = new PdfPCell(phrase3);
    cell13.setBorder(0);

    // table.addCell(cell11);
    table.addCell(cell12);
    table.addCell(cell13);

    phrase.add(table);

    // create gray line separator
    phrase.add("\n");
    document.add(phrase);

    String footerImagePath = LogoPathFinder.getPath(servletContext, "footer-image");

    Image footerImage = Image.getInstance(footerImagePath);
    footerImage.scaleToFit(90, 50);
    footerImage.setAbsolutePosition((PageSize.A4.getWidth() - (footerImage.getScaledWidth() + 40)),
            (PageSize.A4.getHeight() - (PageSize.A4.getHeight() - (footerImage.getScaledHeight() - 10))));

    document.add(footerImage);

}