Example usage for com.itextpdf.text Document getPageSize

List of usage examples for com.itextpdf.text Document getPageSize

Introduction

In this page you can find the example usage for com.itextpdf.text Document getPageSize.

Prototype


public Rectangle getPageSize() 

Source Link

Document

Gets the pagesize.

Usage

From source file:gov.utah.dts.det.ccl.actions.trackingrecordscreening.letters.reports.LivescanAuthorizationB1606.java

private static void generateDocumentPage1(TrackingRecordScreeningLetter screeningLetter, Document document,
        PdfWriter writer) throws BadElementException, DocumentException, Exception {
    PdfPTable table = null;//  w  w  w.  java 2 s .  co  m
    int headerwidths[] = {};
    Paragraph paragraph = null;
    List blist = null;
    ListItem item = null;
    ListItem subItem = null;
    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    StringBuilder sb;
    PdfContentByte over = writer.getDirectContent();

    // LS Authorization Letter Page 1
    addLetterIdentifier(document);

    paragraph = new Paragraph(fixedLeadingLarge);
    paragraph.add(new Phrase("Office of Licensing Livescan Authorization", largefontB));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.setSpacingBefore(30.0f);
    document.add(paragraph);

    paragraph = new Paragraph(fixedLeadingLarge);
    paragraph.add(new Phrase(df.format(screeningLetter.getLetterDate()), mediumfontB));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);

    paragraph = new Paragraph(fixedLeadingMedium);
    paragraph.add(new Phrase("Office of Licensing Information", mediumfontBU));
    paragraph.setSpacingBefore(20.0f);
    document.add(paragraph);

    /*
     * Start of Office of Licensing Information generation
     */
    table = new PdfPTable(2);
    // format the table
    headerwidths = new int[] { 60, 40 }; // percentage
    table.setWidths(headerwidths); // percentage
    table.setWidthPercentage(100);
    table.setSpacingBefore(pageSeparatorSpace);
    table.getDefaultCell().setPadding(0);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
    paragraph = new Paragraph(fixedLeadingLarge);
    paragraph.add(new Phrase("TYPE OF TRANSACTION: FANC", largefontB));
    paragraph.add(Chunk.NEWLINE);
    paragraph.add(new Phrase("REASON FINGERPRINTED: UCA 53-10-108", largefontB));
    paragraph.add(Chunk.NEWLINE);
    paragraph.add(new Phrase("BILLING CODE: B1606", largefontB));
    table.addCell(paragraph);
    paragraph = new Paragraph(fixedLeadingSmall);
    Calendar cal = Calendar.getInstance();
    cal.setTime(screeningLetter.getLetterDate());
    cal.add(Calendar.DAY_OF_MONTH, 16);
    paragraph.add(new Phrase("This Authorization Expires: " + df.format(cal.getTime()), smallfont));
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(paragraph);
    document.add(table);

    // Add Fee information
    paragraph = new Paragraph(fixedLeadingSmall);
    if (screeningLetter.getTrackingRecordScreening().getTrsDpsFbi() != null
            && screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getScanFee() != null) {
        paragraph.add(new Phrase("Scan Fee = ", smallfont));
        paragraph
                .add(new Phrase(
                        CommonUtils.fromDoubleToCurrency(
                                screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getScanFee()),
                        smallfontB));
    } else {
        paragraph.add(new Phrase("Search Fee = ", smallfont));
        if (screeningLetter.getTrackingRecordScreening().getTrsDpsFbi() != null
                && screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getSearchFee() != null) {
            paragraph.add(new Phrase(
                    CommonUtils.fromDoubleToCurrency(
                            screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getSearchFee()),
                    smallfontB));
        } else {
            paragraph.add(SMALL_BLANK);
        }
    }
    paragraph.setSpacingBefore(pageSeparatorSpace);
    document.add(paragraph);

    // Add Authorized Signature line
    paragraph = new Paragraph(fixedLeadingSmall);
    paragraph.add(new Phrase(
            "Office of Licensing Authorized Signature ___________________________________________________  Date ________________",
            smallfont));
    paragraph.setSpacingBefore(18.0f);
    document.add(paragraph);

    // Stamp the document date over the Date line above
    // NOTE: Use showColumnBorders as a diagnostic to display borders of column where date will be placed on document.
    //showColumnBorders(over);
    ColumnText ct = new ColumnText(over);
    ct.setLeading(fixedLeadingSmall);
    ct.addText(new Phrase(df.format(screeningLetter.getLetterDate()), smallfont));
    // Write column to document
    ct.setAlignment(Element.ALIGN_CENTER);
    ct.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]);
    ct.go();

    over.setLineWidth(3.0f);
    over.setCMYKColorStroke(166, 92, 0, 145);
    over.moveTo(document.getPageSize().getLeft(65), BOTTOM_SEPARATOR_EDGE);
    over.lineTo(document.getPageSize().getRight(65), BOTTOM_SEPARATOR_EDGE);
    over.stroke();

    // Add Program & Applicatant header line
    paragraph = new Paragraph(fixedLeadingSmall);
    paragraph.add(new Phrase("Program & Applicant Information and Instructions", smallfontBU));
    paragraph.setSpacingBefore((2 * pageSeparatorSpace) + fixedLeadingSmall);
    document.add(paragraph);

    /*
     * Start of Applicant information line generation
     */
    table = new PdfPTable(3);
    // format the table
    headerwidths = new int[] { 43, 20, 37 }; // percentage
    table.setWidths(headerwidths); // percentage
    table.setWidthPercentage(100);
    table.setSpacingBefore(pageSeparatorSpace);
    table.getDefaultCell().setPadding(0);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_MIDDLE);

    // Add Applicant name
    paragraph = new Paragraph(fixedLeadingSmall);
    paragraph.add(new Phrase("Applicant: ", smallfontB));
    if (screeningLetter.getTrackingRecordScreening().getPerson() != null
            && StringUtils.isNotBlank(screeningLetter.getTrackingRecordScreening().getFirstAndLastName())) {
        paragraph.add(
                new Phrase(screeningLetter.getTrackingRecordScreening().getFirstAndLastName(), smallfontB));
    }
    table.addCell(paragraph);

    // Add Applicant ID
    paragraph = new Paragraph(fixedLeadingSmall);
    paragraph.add(new Phrase("ID: ", smallfontB));
    if (StringUtils.isNotBlank(screeningLetter.getTrackingRecordScreening().getPersonIdentifier())) {
        paragraph.add(
                new Phrase(screeningLetter.getTrackingRecordScreening().getPersonIdentifier(), smallfontB));
    }
    table.addCell(paragraph);

    // Add DOB information
    paragraph = new Paragraph(fixedLeadingSmall);
    paragraph.add(new Phrase("DOB: ", smallfontB));
    try {
        paragraph.add(
                new Phrase(df.format(screeningLetter.getTrackingRecordScreening().getBirthday()), smallfontB));
    } catch (NullPointerException e) {

    }
    table.addCell(paragraph);
    // Add Applicant Information Line Table to document
    document.add(table);
    /*
     * End of Applicant information line generation
     */

    // Add Application program line
    paragraph = new Paragraph(fixedLeadingSmall);
    sb = new StringBuilder();
    sb.append("Applicant Program: ");
    if (screeningLetter.getTrackingRecordScreening().getFacility() != null
            && StringUtils.isNotBlank(screeningLetter.getTrackingRecordScreening().getFacility().getName())) {
        sb.append(screeningLetter.getTrackingRecordScreening().getFacility().getName().toUpperCase());
    }
    paragraph.add(new Phrase(sb.toString(), smallfontB));
    paragraph.setSpacingBefore(pageSeparatorSpace);
    document.add(paragraph);

    // Add Payment information line
    paragraph = new Paragraph(fixedLeadingSmall);
    sb = new StringBuilder();
    sb.append("Payment issued by: ");
    if (screeningLetter.getTrackingRecordScreening().getTrsDpsFbi() != null && StringUtils
            .isNotBlank(screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getIssuedBy())) {
        sb.append(screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getIssuedBy().toUpperCase());
    }
    sb.append("    ");
    sb.append("Check Number: ");
    if (screeningLetter.getTrackingRecordScreening().getTrsDpsFbi() != null && StringUtils
            .isNotBlank(screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getMoNumber())) {
        sb.append(screeningLetter.getTrackingRecordScreening().getTrsDpsFbi().getMoNumber().toUpperCase());
    }
    paragraph.add(new Phrase(sb.toString(), smallfontB));
    paragraph.setSpacingBefore(pageSeparatorSpace);
    document.add(paragraph);

    // Add READ THIS CAREFULLY
    paragraph = new Paragraph(fixedLeadingMedium);
    paragraph.add(new Phrase("READ THIS CAREFULLY", largefontBU));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.setSpacingBefore(pageSeparatorSpace + fixedLeadingLarge);
    document.add(paragraph);

    /*
     * Start of instructions list section
     */
    blist = new List(false, 20);
    item = new ListItem(fixedLeadingSmall);
    item.setListSymbol(new Chunk("1.", mediumfont));
    item.add(new Phrase(
            "The Office of Licensing authorizes the applicant to submit her/his fingerprints for an electronic applicant background check ",
            smallfont));
    item.add(new Phrase(
            "at various sites throughout Utah using the Live Scan system. Each site charges a fee for the electronic fingerprint scan. ",
            smallfont));
    item.add(new Phrase(
            "Scanning fees vary from site to site. This is a separate fee from the one submitted to the Department of Human Services for ",
            smallfont));
    item.add(new Phrase("the actual criminal background search.", smallfont));
    item.setSpacingBefore(page1ListSpace);
    blist.add(item);

    item = new ListItem(fixedLeadingSmall);
    item.setListSymbol(new Chunk("2.", mediumfont));
    item.add(new Phrase(
            "Complete electronic fingerprint submission within 15 days of the date of this authorization letter. If unused, ",
            smallfontB));
    item.add(new Phrase(
            "requests for refunds will not be considered after 30 days. Refund requests require a letter of explanation ",
            smallfontB));
    item.add(new Phrase(
            "from the licensed program accompanied by this original authorization letter. Failure to complete electronic ",
            smallfontB));
    item.add(new Phrase(
            "fingerprint submission within this time will result in the denial of the background screening clearance and ",
            smallfontB));
    item.add(new Phrase(
            "the applicant will not be permitted to have direct access to children or vulnerable adults, will not be eligible ",
            smallfontB));
    item.add(new Phrase(
            "to provide services to programs licensed by the Utah Department of Human Services, Office of Licensing, and will not be ",
            smallfontB));
    item.add(new Phrase("eligible to proceed with foster care or adoption.", smallfontB));
    item.setSpacingBefore(4.0f);
    blist.add(item);

    item = new ListItem(fixedLeadingSmall);
    item.setListSymbol(new Chunk("3.", mediumfont));
    paragraph = new Paragraph(fixedLeadingSmall);
    paragraph.add(new Phrase("You will need to take with you:", smallfont));
    item.add(paragraph);
    List subList = new List(false, 10);
    subList.setIndentationLeft(10);
    subItem = new ListItem(fixedLeadingSmall);
    subItem.add(new Phrase("This original letter. Photocopies and facsimile (FAX) copies will not be accepted.",
            smallfont));
    subList.add(subItem);
    subItem = new ListItem(fixedLeadingSmall);
    subItem.add(new Phrase(
            "Photo I.D. in the form of your driver license or state identification card issued by the Division of Motor Vehicles.",
            smallfont));
    subList.add(subItem);
    subItem = new ListItem(fixedLeadingSmall);
    subItem.add(
            new Phrase("Cash or check as required (see site list for acceptable form of payment).", smallfont));
    subList.add(subItem);
    item.add(subList);
    item.setSpacingBefore(page1ListSpace);
    blist.add(item);

    item = new ListItem(fixedLeadingSmall);
    item.setListSymbol(new Chunk("4.", mediumfont));
    item.add(new Phrase(
            "If the electronically submitted fingerprints are rejected, the Office of Licensing will notify the applicant/licensed program ",
            smallfont));
    item.add(new Phrase("of additional instructions for completing the nationwide background search.",
            smallfont));
    item.setSpacingBefore(page1ListSpace);
    blist.add(item);

    item = new ListItem(fixedLeadingSmall);
    item.setListSymbol(new Chunk("5.", mediumfont));
    item.add(new Phrase(
            "Applicant Signature ___________________________________________________  Date ________________",
            smallfont));
    item.setSpacingBefore(page1ListSpace);
    blist.add(item);
    document.add(blist);
    /*
     * End of instructions list section
     */

    paragraph = new Paragraph();
    paragraph.add(new Phrase(
            "A current list of Livescan sites is available at www.hslic.utah.gov/docs/livescan sites.pdf",
            smallfont));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.setSpacingBefore(pageSeparatorSpace);
    document.add(paragraph);

    paragraph = new Paragraph(fixedLeadingMedium);
    paragraph.add(new Phrase("Live Scan Operator: Keep this original for auditing purposes.", mediumfontB));
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.setSpacingBefore(pageSeparatorSpace);
    document.add(paragraph);
}

From source file:gov.utah.dts.det.ccl.documents.reporting.reports.CaseloadReport.java

@Override
public void render(Map<String, Object> context, OutputStream outputStream, FileDescriptor descriptor)
        throws TemplateException {
    List<Object[]> results = getResults(context);

    ColumnType columnType = ColumnType.valueOf((String) context.get(COLUMN_TYPE_KEY));
    RoleType roleType = RoleType.valueOf((String) context.get(SPECIALIST_TYPE_KEY));

    ReportTable<Integer> reportTable = new ReportTable<Integer>();

    for (Object[] res : results) {
        String column = null;/* w w w .ja v  a2  s  .  com*/
        switch (columnType) {
        case LICENSE_TYPE:
            column = (String) res[3];
            break;
        case CITY:
            column = (String) res[3];
            break;
        case COUNTY:
            column = locationService.getCounty((String) res[3], (String) res[4], (String) res[5]);
            break;
        case ZIP_CODE:
            String zip = (String) res[5];
            if (zip.length() > 5) {
                zip = zip.substring(0, 5);
            }
            column = zip;
            break;
        }

        if (StringUtils.isBlank(column)) {
            column = "Unknown";
        }

        reportTable.addColumn(column);

        String specRow = null;
        String specFnm = (String) res[1];
        String specLnm = (String) res[2];
        if (StringUtils.isNotBlank(specFnm) || StringUtils.isNotBlank(specLnm)) {
            PersonalName name = new PersonalName(specFnm, specLnm);
            specRow = name.getFirstAndLastName();
        } else {
            specRow = "Unknown";
        }

        reportTable.addRow(specRow);

        Integer val = reportTable.getTableDataItem(specRow, column);
        if (val == null) {
            val = new Integer(1);
        } else {
            val = new Integer(val.intValue() + 1);
        }
        reportTable.addTableDataItem(specRow, column, val);
    }

    setFileName(context, descriptor);

    Document document = new Document(PAGE_SIZE, MARGIN, MARGIN, MARGIN, MARGIN);
    try {
        PdfWriter canvas = PdfWriter.getInstance(document, outputStream);
        document.open();

        ColumnText text = new ColumnText(canvas.getDirectContent());
        text.setSimpleColumn(document.getPageSize().getLeft(MARGIN), document.getPageSize().getBottom(MARGIN),
                document.getPageSize().getRight(MARGIN), document.getPageSize().getTop(MARGIN));

        StringBuilder sb = new StringBuilder(roleType.getDisplayName());
        sb.append(" Caseloads");
        Paragraph heading = new Paragraph(sb.toString(), REPORT_HEADING_FONT);
        heading.setAlignment(Element.ALIGN_CENTER);
        text.addElement(heading);
        text.go();
        float yLine = text.getYLine();
        yLine -= FONT_SIZE;

        int columns = reportTable.getColumns().size() + 2;

        String[][] totTab = new String[reportTable.getRows().size()][columns];
        float maxLicWidth = 0f;
        float maxTotWidth = FONT_SIZE;
        int rowIdx = 0;
        for (Iterator<String> rowItr = reportTable.getRows().iterator(); rowItr.hasNext();) {
            String row = rowItr.next();
            totTab[rowIdx][0] = row;
            float licWidth = getTextWidth(row, FONT);
            if (licWidth > maxLicWidth) {
                maxLicWidth = licWidth;
            }

            int rowTotal = 0;
            int colIdx = 1;
            for (Iterator<String> colItr = reportTable.getColumns().iterator(); colItr.hasNext();) {
                String col = colItr.next();
                Integer val = reportTable.getTableDataItem(row, col);
                if (val != null) {
                    totTab[rowIdx][colIdx] = val.toString();
                    rowTotal += val.intValue();
                }
                colIdx++;
            }
            String rowTotalStr = Integer.toString(rowTotal);
            float totWidth = getTextWidth(rowTotalStr, TABLE_HEADER_FONT);
            if (totWidth > maxTotWidth) {
                maxTotWidth = totWidth;
            }
            totTab[rowIdx][columns - 1] = rowTotalStr;
            rowIdx++;
        }

        //add border and cell padding to licensor width
        maxLicWidth += (TABLE_CELL_PADDING * 2) + (TABLE_BORDER_SIZE * 2);
        maxTotWidth += (TABLE_CELL_PADDING * 2) + (TABLE_BORDER_SIZE * 2);

        float width = PAGE_SIZE.getWidth() - (2 * MARGIN);
        width -= maxLicWidth;

        float[] colWidths = new float[columns];
        colWidths[0] = maxLicWidth;
        for (int i = 1; i < columns; i++) {
            colWidths[i] = maxTotWidth;
        }

        PdfPTable table = new PdfPTable(reportTable.getColumns().size() + 2);
        table.setHeaderRows(1);
        table.setLockedWidth(true);
        table.setTotalWidth(colWidths);
        table.setSpacingBefore(FONT_SIZE);
        setDefaultCellAttributes(table.getDefaultCell());

        PdfPCell cell = null;

        cell = new PdfPCell(new Phrase(""));
        cell.setBorderWidthTop(0);
        cell.setBorderWidthLeft(0);
        table.addCell(cell);
        for (Iterator<String> itr = reportTable.getColumns().iterator(); itr.hasNext();) {
            cell = getRotatedHeaderCell(itr.next());
            table.addCell(cell);
        }
        cell = getRotatedHeaderCell("Total");
        table.addCell(cell);

        for (String[] row : totTab) {
            for (int i = 0; i < row.length; i++) {
                if (row[i] == null) {
                    table.addCell(getNumberCell(""));
                } else {
                    table.addCell(getCell(new Phrase(row[i], i == row.length - 1 ? TABLE_HEADER_FONT : FONT),
                            i == 0 ? Element.ALIGN_LEFT : Element.ALIGN_CENTER));
                }

            }
        }

        writeTable(table, document, canvas.getDirectContent(), colWidths, yLine, true);
    } catch (DocumentException de) {
        throw new TemplateException(de);
    }
    document.close();
}

From source file:io.github.nick11roberts.pdf_drive.PreviewActivity.java

License:Open Source License

public void addImagesToPDF() throws Exception {
    Document document = new Document();
    ByteArrayOutputStream stream;
    Bitmap bmpImage;/*w  w  w .j  av a  2s .  c o m*/
    byte[] imagebytes;
    Image image;
    float scaler;
    PdfWriter.getInstance(document, new FileOutputStream(tmpPdfFile));
    document.open();
    for (int i = camIndex - 1; i >= 0; i--) {
        stream = new ByteArrayOutputStream();
        bmpImage = Bitmap.createBitmap(imagesFromCamera.get(i));
        //bmpImage = rotateImage(bmpImage, -90);         
        bmpImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        imagebytes = stream.toByteArray();
        image = Image.getInstance(imagebytes);
        scaler = ((document.getPageSize().getWidth()) / image.getWidth()) * 100;
        image.scalePercent(scaler);
        image.setAlignment(Image.MIDDLE | Image.ALIGN_MIDDLE);
        document.add(image);
        document.newPage();
        stream.close();
        stream = null;
    }

    document.close();
}

From source file:jdbreport.model.io.pdf.itext5.PdfWriter.java

License:Apache License

private int saveSheet(Document document, int listCount, ReportModel model)
        throws DocumentException, IOException, SaveReportException {

    model.updatePages(0);//from   www  . j a  v a2 s.  c  om

    ReportPage pageFormat = model.getReportPage();
    Paper paper = pageFormat.getPaper();
    Rectangle pageSize = new Rectangle((float) paper.getWidth(), (float) paper.getHeight());

    if (pageFormat.getOrientation() == ReportPage.LANDSCAPE) {
        pageSize = pageSize.rotate();
    }
    document.setPageSize(pageSize);
    document.setMargins((float) pageFormat.getLeftMargin(Units.PT), (float) pageFormat.getRightMargin(Units.PT),
            (float) pageFormat.getTopMargin(Units.PT), (float) pageFormat.getBottomMargin(Units.PT));
    if (listCount > 0) {
        document.newPage();
    }
    listCount++;

    TableRowModel rowModel = model.getRowModel();

    float columnMargin = (float) Units.PT.setXPixels(model.getColumnModel().getColumnMargin());

    ReportPrintable printable = new ReportPrintable(model);
    int pageCount = printable.calcCountPage(model.getReportPage());
    Map<Integer, PageClip> clips = printable.getPageClips();

    int leftCol;
    int topRow;
    int rightCol;
    int bottomRow;

    for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
        PageClip pageClip = clips.get(pageIndex);
        if (pageClip == null)
            break;

        leftCol = pageClip.getLeftCol();
        rightCol = pageClip.getRightCol();

        topRow = pageClip.getTopRow();
        bottomRow = pageClip.getBottomRow();

        int columnCount = rightCol - leftCol;

        float[] widths = new float[columnCount];
        for (int c = 0; c < widths.length; c++) {
            ReportColumn column = (ReportColumn) model.getColumnModel().getColumn(leftCol + c);
            widths[c] = (float) column.getNativeWidth() + columnMargin;
        }
        PdfPTable table = createPdfTable(columnCount, widths, document.getPageSize());

        for (int row = topRow; row < bottomRow; row++) {
            TableRow reportRow = rowModel.getRow(row);

            for (int col = leftCol; col < rightCol; col++) {
                jdbreport.model.Cell srcCell = reportRow.getCellItem(col);
                if (!srcCell.isChild()) {
                    PdfPCell pdfCell = writeCell(model, srcCell, row, col);
                    table.addCell(pdfCell);
                }
            }

        }

        document.add(table);

        if (pageIndex < clips.size()) {
            document.newPage();
        }

    }
    return listCount;
}

From source file:Login.ventas.fproyectos.java

/**
 * Creates new form cliente/*from  w ww  .  j  a  v a2s  .  c om*/
 * @param user
 */
public fproyectos(Login user) {
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    @SuppressWarnings("MismatchedReadAndWriteOfArray")
    String[] fecha = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre",
            "Octubre", "Noviembre", "Diciembre" };
    initComponents();
    Calendar rightNow = Calendar.getInstance();
    int ccyy = rightNow.get(Calendar.YEAR);
    int month = rightNow.get(Calendar.MONTH);
    setSize(d.width, d.height - 95);
    this.usuario = user;
    add(f);
    f.setLocation(jPanel1.getX(), jPanel1.getY());
    add(f3);
    f3.setLocation(jPanel1.getX(), jPanel1.getY());
    add(f4);
    f4.setLocation(jPanel1.getX(), jPanel1.getY());
    add(f5);
    f5.setLocation(jPanel1.getX(), jPanel1.getY());
    add(f2);
    f2.setLocation(jPanel1.getX(), jPanel1.getY());

    f2.getjButton1().addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            try {
                ServiceHb helper = new ServiceHb();
                helper.iniciarTransaccion();
                Fcomisiones fc = helper.getFcomisiones(idcliente, idinstalacion);
                if (helper.getFcomisiones(idcliente, idinstalacion) == null) {
                    fc = new Fcomisiones();
                    Calendar d = Calendar.getInstance();
                    fc.setFecha(new java.sql.Date(d.getTime().getTime()));
                    fc.setClientes(
                            (Clientes) helper.obtenerObjeto(Clientes.class, Integer.parseInt(idcliente)));
                    fc.setInstalacion((Instalacion) helper.obtenerObjeto(Instalacion.class,
                            Integer.parseInt(idinstalacion)));
                    fc.setRentabilidad(f2.getjLabel20().getText());
                    fc.setValor1(f2.getjLabel11().getText().substring(2, f2.getjLabel11().getText().length()));
                    fc.setValor2(f2.getjLabel2().getText().substring(3, f2.getjLabel2().getText().length()));
                    fc.setDiferido(f2.getjLabel4().getText());
                    fc.setDias(numeroinstala);
                    helper.crearObjeto(fc);
                    helper.confirmarTransaccion();
                    helper.cerrarSesion();
                    JOptionPane.showMessageDialog(null,
                            "Comision prepara con fecha " + Funcion.DateFormatSql(d.getTime()));
                } else {
                    Calendar d = Calendar.getInstance();
                    fc.setFecha(new java.sql.Date(d.getTime().getTime()));
                    fc.setRentabilidad(f2.getjLabel20().getText());
                    fc.setValor1(f2.getjLabel11().getText().substring(2, f2.getjLabel11().getText().length()));
                    fc.setValor2(f2.getjLabel2().getText().substring(3, f2.getjLabel2().getText().length()));
                    fc.setDiferido(f2.getjLabel4().getText());
                    fc.setDias(numeroinstala);
                    helper.actualizarObjeto(fc);
                    helper.confirmarTransaccion();
                    helper.cerrarSesion();
                    JOptionPane.showMessageDialog(null,
                            "Actualizado / Comision prepara con fecha " + Funcion.DateFormatSql(d.getTime()));
                }
            } catch (Exception io) {
                System.out.println(io);
            }
        }
    });
    f2.getjButton2().addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        @SuppressWarnings("UseSpecificCatch")
        public void mouseClicked(MouseEvent e) {
            float ancho = 0;
            try {
                Document documento = new Document(PageSize.A4, 0, 0, 0, 0);
                ancho = documento.getPageSize().getWidth() - 100;
                FileOutputStream ficheroPdf;
                PdfWriter writer = null;
                PdfWriter writer2 = null;
                String direccion = "";
                Calendar now2 = Calendar.getInstance();
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    //Mostrar la ventana para abrir archivo y recoger la respuesta
                    //En el parmetro del showOpenDialog se indica la ventana
                    //  al que estar asociado. Con el valor this se asocia a la
                    //  ventana que la abre.
                    int respuesta = chooser.showOpenDialog(null);
                    String cadena = "";
                    if (respuesta == JFileChooser.APPROVE_OPTION) {
                        direccion = chooser.getSelectedFile().getAbsolutePath();
                    }
                    Calendar d = Calendar.getInstance();
                    ficheroPdf = new FileOutputStream(direccion + "/" + idcliente + idinstalacion + ".pdf");
                    writer = PdfWriter.getInstance(documento, ficheroPdf);
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
                ServiceHb helper = null;
                try {
                    List<Productos> lt = null;
                    helper = new ServiceHb();
                    helper.iniciarTransaccion();
                    PdfPTable tabla;
                    PdfPCell casilla;
                    PdfPTable salto = null;
                    PdfPCell celda;
                    Font fontpersonalizado = FontFactory.getFont("ARIAL", 7, Font.BOLD);
                    Font fontpersonalizado2 = FontFactory.getFont("ARIAL", 7, Font.NORMAL);
                    documento.open();
                    PdfContentByte canvas = writer.getDirectContent();
                    fondos(documento, canvas);
                    //Materiales
                    double total = 0;
                    double total2 = 0;
                    double total3 = 0;
                    double total4 = 0;
                    double total5 = 0;
                    tabla = new PdfPTable(6);
                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                    tabla.setTotalWidth(ancho);
                    tabla.setLockedWidth(true);
                    celda = new PdfPCell(new Paragraph("ADQUISICION DE MATERIALES"));
                    celda.setColspan(6);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);
                    float pagina = documento.getPageSize().getHeight() - 140;
                    final float max = pagina;
                    pagina = pagina - tabla.getRow(0).calculateHeights();
                    if (ltart != null) {
                        Object nuevo2[] = { "FECHA", "DETALLE", "CANT.", "PRECIO", "SUBTOTAL", "TOTAL DIARIO" };
                        for (Object obj : nuevo2) {
                            celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                            celda.setBorderColor(new Color(195, 195, 195));
                            celda.setColspan(1);
                            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                            tabla.addCell(celda);
                        }
                        pagina = pagina - tabla.getRow(1).calculateHeights();
                        int tam = 0;
                        double diario = 0;
                        int turno = 0;
                        for (int i = 0; i < ltart.size(); i++) {
                            turno = 0;
                            fact = helper.getFacturafecha(ltart.get(i).getIdfactura());
                            String fecha = "";
                            if (fact != null) {
                                fecha = Funcion.DateFormatSql(fact.getFecha());
                            }
                            if ((i + 1) == ltart.size()) {
                                diario = diario + Double.parseDouble(ltart.get(i).getTotal());
                                turno = 1;
                            } else {
                                fact2 = helper.getFacturafecha(ltart.get(i + 1).getIdfactura());
                                String fecha2 = "";
                                if (fact2 != null) {
                                    fecha2 = Funcion.DateFormatSql(fact2.getFecha());
                                    if (fecha.equalsIgnoreCase(fecha2)) {
                                        diario = diario + Double.parseDouble(ltart.get(i).getTotal());
                                    } else {
                                        diario = diario + Double.parseDouble(ltart.get(i).getTotal());
                                        turno = 1;
                                    }
                                }
                            }
                            String uni = "$ " + df.format(Double.parseDouble(ltart.get(i).getUnitario()))
                                    .replace(",", ".");
                            String tot = "$ "
                                    + df.format(Double.parseDouble(ltart.get(i).getTotal())).replace(",", ".");
                            total = total + Double.parseDouble(ltart.get(i).getTotal());
                            if (turno == 0) {
                                Object nuevo[] = { fecha, ltart.get(i).getDescripcion(),
                                        ltart.get(i).getCantidad(), uni, tot, "" };
                                for (Object obj : nuevo) {

                                    celda = new PdfPCell(
                                            new Paragraph((String) obj, new Font(fontpersonalizado2)));
                                    if (((String) obj).equalsIgnoreCase("")) {
                                        celda.setBorder(Rectangle.RIGHT);
                                    }
                                    celda.setBorderColor(new Color(195, 195, 195));
                                    celda.setColspan(1);
                                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    tabla.addCell(celda);
                                }
                            } else {
                                Object nuevo[] = { fecha, ltart.get(i).getDescripcion(),
                                        ltart.get(i).getCantidad(), uni, tot,
                                        "$ " + df.format(diario).replace(",", ".") };
                                int va = 0;
                                for (Object obj : nuevo) {
                                    va++;
                                    celda = new PdfPCell(
                                            new Paragraph((String) obj, new Font(fontpersonalizado2)));
                                    if (va == 5) {
                                        celda.setBorder(Rectangle.BOTTOM);
                                    }
                                    celda.setColspan(1);
                                    celda.setBorderColor(new Color(195, 195, 195));
                                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    tabla.addCell(celda);
                                }
                                diario = 0;
                            }
                            pagina = pagina - tabla.getRow(tam).getMaxHeights();
                            tam++;
                            if (pagina < 11) {
                                salto = new PdfPTable(1);
                                casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                                casilla.setMinimumHeight(90);
                                casilla.setBorder(PdfPCell.NO_BORDER);
                                salto.addCell(casilla);
                                documento.add(salto);

                                documento.add(tabla);
                                documento.newPage();
                                fondos(documento, canvas);
                                tabla = new PdfPTable(6);
                                tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                                tabla.setTotalWidth(ancho);
                                tabla.setLockedWidth(true);
                                pagina = max;
                                tam = 0;
                            }

                        }
                    }
                    salto = new PdfPTable(1);
                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                    casilla.setMinimumHeight(90);
                    casilla.setBorder(PdfPCell.NO_BORDER);
                    salto.addCell(casilla);
                    documento.add(salto);

                    celda = new PdfPCell(new Paragraph("Total", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(
                            new Paragraph("Adquisicin de Materiales", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(4);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("$ " + df.format(total).replace(",", "."),
                            new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    documento.add(tabla);
                    documento.newPage();
                    fondos(documento, canvas);
                    /*Parte 2*/

                    tabla = new PdfPTable(4);
                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                    tabla.setTotalWidth(ancho);
                    tabla.setLockedWidth(true);
                    tabla.setWidths(new int[] { 1, 3, 1, 1 });
                    celda = new PdfPCell(new Paragraph("MANO DE OBRA TECNICOS"));
                    celda.setColspan(4);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);
                    pagina = documento.getPageSize().getHeight() - 140;
                    pagina = pagina - tabla.getRow(0).calculateHeights();

                    if (list != null) {
                        Object nuevo2[] = { "FECHA", "DETALLE", "CANT.", "SUBTOTAL" };
                        for (Object obj : nuevo2) {
                            celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                            celda.setBorderColor(new Color(195, 195, 195));
                            celda.setColspan(1);
                            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                            tabla.addCell(celda);
                        }
                        pagina = pagina - tabla.getRow(1).calculateHeights();
                        int tam = 0;
                        double diario = 0;
                        int turno = 0;
                        for (Ctepagar list1 : list) {
                            if (list1.getDetalle().contains("ci:")) {
                                String fecha = list1.getFecha();
                                String desc = list1.getDetalle();
                                String[] cadena = desc.split(" ");
                                String result = "";
                                int contador = 0;
                                for (String n : cadena) {
                                    if (n.contains("ci:")) {
                                        result = result + ", ";
                                        contador++;
                                    } else {
                                        result = result + n + " ";
                                    }
                                }
                                result = result.substring(0, result.length() - 2);
                                String uni = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                String tot = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                total2 = total2 + Double.parseDouble(list1.getValor());
                                Object nuevo[] = { fecha, result, "" + contador, tot };
                                for (Object obj : nuevo) {
                                    celda = new PdfPCell(
                                            new Paragraph((String) obj, new Font(fontpersonalizado2)));
                                    celda.setBorderColor(new Color(195, 195, 195));
                                    celda.setColspan(1);
                                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    tabla.addCell(celda);
                                }
                                pagina = pagina - tabla.getRow(tam).getMaxHeights();
                                tam++;
                                if (pagina < 90) {
                                    salto = new PdfPTable(1);
                                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado2)));
                                    casilla.setMinimumHeight(90);
                                    casilla.setBorder(PdfPCell.NO_BORDER);
                                    salto.addCell(casilla);
                                    documento.add(salto);

                                    documento.add(tabla);
                                    documento.newPage();
                                    fondos(documento, canvas);
                                    tabla = new PdfPTable(4);
                                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                                    tabla.setTotalWidth(ancho);
                                    tabla.setLockedWidth(true);
                                    tabla.setWidths(new int[] { 1, 3, 1, 1 });
                                    pagina = max;
                                    tam = 0;
                                }
                            }
                        }
                    }
                    salto = new PdfPTable(1);
                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                    casilla.setMinimumHeight(90);
                    casilla.setBorder(PdfPCell.NO_BORDER);
                    salto.addCell(casilla);
                    documento.add(salto);

                    celda = new PdfPCell(new Paragraph("Total", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("Mano de Obra Tcnicos", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(2);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("$ " + df.format(total2).replace(",", "."),
                            new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    documento.add(tabla);

                    documento.newPage();
                    fondos(documento, canvas);

                    tabla = new PdfPTable(3);
                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                    tabla.setTotalWidth(ancho);
                    tabla.setLockedWidth(true);
                    tabla.setWidths(new int[] { 1, 3, 1 });
                    celda = new PdfPCell(new Paragraph("TRANSPORTE"));
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);
                    pagina = documento.getPageSize().getHeight() - 140;
                    pagina = pagina - tabla.getRow(0).calculateHeights();

                    if (list != null) {
                        Object nuevo2[] = { "FECHA", "DETALLE", "SUBTOTAL" };
                        for (Object obj : nuevo2) {
                            celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                            celda.setBorderColor(new Color(195, 195, 195));
                            celda.setColspan(1);
                            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                            tabla.addCell(celda);
                        }
                        pagina = pagina - tabla.getRow(1).calculateHeights();
                        int tam = 0;
                        for (Ctepagar list1 : list) {
                            if (list1.getDetalle().contains("Transporte")) {
                                String fecha = list1.getFecha();
                                String desc = list1.getDetalle();
                                String result = "";
                                String uni = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                String tot = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                total3 = total3 + Double.parseDouble(list1.getValor());
                                Object nuevo[] = { fecha, desc, tot };
                                for (Object obj : nuevo) {
                                    celda = new PdfPCell(
                                            new Paragraph((String) obj, new Font(fontpersonalizado2)));
                                    celda.setBorderColor(new Color(195, 195, 195));
                                    celda.setColspan(1);
                                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    tabla.addCell(celda);
                                }
                                pagina = pagina - tabla.getRow(tam).getMaxHeights();
                                tam++;
                                if (pagina < 50) {
                                    salto = new PdfPTable(1);
                                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado2)));
                                    casilla.setMinimumHeight(90);
                                    casilla.setBorder(PdfPCell.NO_BORDER);
                                    salto.addCell(casilla);
                                    documento.add(salto);

                                    documento.add(tabla);
                                    documento.newPage();
                                    fondos(documento, canvas);
                                    tabla = new PdfPTable(3);
                                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                                    tabla.setTotalWidth(ancho);
                                    tabla.setLockedWidth(true);
                                    tabla.setWidths(new int[] { 1, 3, 1 });
                                    pagina = max;
                                    tam = 0;
                                }
                            }
                        }
                    }
                    salto = new PdfPTable(1);
                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                    casilla.setMinimumHeight(90);
                    casilla.setBorder(PdfPCell.NO_BORDER);
                    salto.addCell(casilla);
                    documento.add(salto);

                    celda = new PdfPCell(new Paragraph("Total", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("Transporte", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("$ " + df.format(total3).replace(",", "."),
                            new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    documento.add(tabla);

                    documento.newPage();
                    fondos(documento, canvas);

                    tabla = new PdfPTable(3);
                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                    tabla.setTotalWidth(ancho);
                    tabla.setLockedWidth(true);
                    tabla.setWidths(new int[] { 1, 3, 1 });
                    celda = new PdfPCell(new Paragraph("COMBUSTIBLE"));
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);
                    pagina = documento.getPageSize().getHeight() - 140;
                    pagina = pagina - tabla.getRow(0).calculateHeights();

                    if (list != null) {
                        Object nuevo2[] = { "FECHA", "DETALLE", "SUBTOTAL" };
                        for (Object obj : nuevo2) {
                            celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                            celda.setBorderColor(new Color(195, 195, 195));
                            celda.setColspan(1);
                            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                            tabla.addCell(celda);
                        }
                        pagina = pagina - tabla.getRow(1).calculateHeights();
                        int tam = 0;
                        for (Ctepagar list1 : list) {
                            if (list1.getDetalle().contains("Combustible")) {
                                String fecha = list1.getFecha();
                                String desc = list1.getDetalle();
                                String result = "";
                                String uni = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                String tot = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                total4 = total4 + Double.parseDouble(list1.getValor());
                                Object nuevo[] = { fecha, desc, tot };
                                for (Object obj : nuevo) {
                                    celda = new PdfPCell(
                                            new Paragraph((String) obj, new Font(fontpersonalizado2)));
                                    celda.setBorderColor(new Color(195, 195, 195));
                                    celda.setColspan(1);
                                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    tabla.addCell(celda);
                                }
                                pagina = pagina - tabla.getRow(tam).getMaxHeights();
                                tam++;
                                if (pagina < 50) {
                                    salto = new PdfPTable(1);
                                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                                    casilla.setMinimumHeight(90);
                                    casilla.setBorder(PdfPCell.NO_BORDER);
                                    salto.addCell(casilla);
                                    documento.add(salto);

                                    documento.add(tabla);
                                    documento.newPage();
                                    fondos(documento, canvas);
                                    tabla = new PdfPTable(3);
                                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                                    tabla.setTotalWidth(ancho);
                                    tabla.setLockedWidth(true);
                                    tabla.setWidths(new int[] { 1, 3, 1 });
                                    pagina = max;
                                    tam = 0;
                                }
                            }
                        }
                    }
                    salto = new PdfPTable(1);
                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                    casilla.setMinimumHeight(90);
                    casilla.setBorder(PdfPCell.NO_BORDER);
                    salto.addCell(casilla);
                    documento.add(salto);

                    celda = new PdfPCell(new Paragraph("Total", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("Combustible", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("$ " + df.format(total4).replace(",", "."),
                            new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    documento.add(tabla);

                    documento.newPage();
                    fondos(documento, canvas);

                    //Extras

                    tabla = new PdfPTable(3);
                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                    tabla.setTotalWidth(ancho);
                    tabla.setLockedWidth(true);
                    tabla.setWidths(new int[] { 1, 3, 1 });
                    celda = new PdfPCell(new Paragraph("EXTRAS"));
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);
                    pagina = documento.getPageSize().getHeight() - 140;
                    pagina = pagina - tabla.getRow(0).calculateHeights();

                    if (list != null) {
                        Object nuevo2[] = { "FECHA", "DETALLE", "SUBTOTAL" };
                        for (Object obj : nuevo2) {
                            celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                            celda.setBorderColor(new Color(195, 195, 195));
                            celda.setColspan(1);
                            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                            tabla.addCell(celda);
                        }
                        pagina = pagina - tabla.getRow(1).calculateHeights();
                        int tam = 0;
                        for (Ctepagar list1 : list) {
                            if (!list1.getDetalle().contains("Combustible")
                                    && !list1.getDetalle().contains("ci:")
                                    && !list1.getDetalle().contains("Transporte")) {
                                String fecha = list1.getFecha();
                                String desc = list1.getDetalle();
                                String result = "";
                                String uni = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                String tot = "$ "
                                        + df.format(Double.parseDouble(list1.getValor())).replace(",", ".");
                                total5 = total5 + Double.parseDouble(list1.getValor());
                                Object nuevo[] = { fecha, desc, tot };
                                for (Object obj : nuevo) {
                                    celda = new PdfPCell(
                                            new Paragraph((String) obj, new Font(fontpersonalizado2)));
                                    celda.setBorderColor(new Color(195, 195, 195));
                                    celda.setColspan(1);
                                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    tabla.addCell(celda);
                                }
                                pagina = pagina - tabla.getRow(tam).getMaxHeights();
                                tam++;
                                if (pagina < 50) {
                                    salto = new PdfPTable(1);
                                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                                    casilla.setMinimumHeight(90);
                                    casilla.setBorder(PdfPCell.NO_BORDER);
                                    salto.addCell(casilla);
                                    documento.add(salto);

                                    documento.add(tabla);
                                    documento.newPage();
                                    fondos(documento, canvas);
                                    tabla = new PdfPTable(3);
                                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                                    tabla.setTotalWidth(ancho);
                                    tabla.setLockedWidth(true);
                                    tabla.setWidths(new int[] { 1, 3, 1 });
                                    pagina = max;
                                    tam = 0;
                                }
                            }
                        }
                    }
                    salto = new PdfPTable(1);
                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                    casilla.setMinimumHeight(90);
                    casilla.setBorder(PdfPCell.NO_BORDER);
                    salto.addCell(casilla);
                    documento.add(salto);

                    celda = new PdfPCell(new Paragraph("Total", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("Extra", new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("$ " + df.format(total5).replace(",", "."),
                            new Font(fontpersonalizado2)));
                    celda.setBorderColor(new Color(195, 195, 195));
                    celda.setColspan(1);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);

                    documento.add(tabla);

                    documento.newPage();
                    fondos(documento, canvas);

                    //Final Vendedor

                    tabla = new PdfPTable(3);
                    tabla.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                    tabla.setTotalWidth(ancho);
                    tabla.setLockedWidth(true);
                    tabla.setWidths(new int[] { 1, 3, 1 });
                    celda = new PdfPCell(new Paragraph(nombrecliente));
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);

                    celda = new PdfPCell(new Paragraph("Venta"));
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);

                    pagina = documento.getPageSize().getHeight() - 140;
                    pagina = pagina - tabla.getRow(0).calculateHeights();

                    Object nuevo2[] = { "FECHA", "DETALLE", "TOTAL" };
                    for (Object obj : nuevo2) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                        celda.setBorderColor(new Color(195, 195, 195));
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo3[] = { "", nombreinstalacion, totalinstalacion };
                    for (Object obj : nuevo3) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorderColor(new Color(195, 195, 195));
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    celda = new PdfPCell(new Paragraph("INVERSION", new Font(fontpersonalizado)));
                    celda.setBorder(PdfPCell.NO_BORDER);
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tabla.addCell(celda);
                    Object nuevo4[] = { "Uso de Materiales", "", "$ " + df.format(total).replace(",", ".") };
                    for (Object obj : nuevo4) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo5[] = { "Mano de obra tcnicos", "",
                            "$ " + df.format(total2).replace(",", ".") };
                    for (Object obj : nuevo5) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo6[] = { "Transporte", "", "$ " + df.format(total3).replace(",", ".") };
                    for (Object obj : nuevo6) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo7[] = { "Combustible", "", "$ " + df.format(total4).replace(",", ".") };
                    for (Object obj : nuevo7) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo71[] = { "Extras", "", "$ " + df.format(total5).replace(",", ".") };
                    for (Object obj : nuevo71) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo8[] = { "Total Inversin", "",
                            "$ " + df.format(total + total2 + total3 + total4).replace(",", ".") };
                    for (Object obj : nuevo8) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado2)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    celda = new PdfPCell(new Paragraph(""));
                    celda.setColspan(3);
                    celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                    celda.setBorder(PdfPCell.NO_BORDER);
                    tabla.addCell(celda);

                    Object nuevo9[] = { "Utilidad del proyecto", "", "$ "
                            + df.format(proyectoval - total - total2 - total3 - total4).replace(",", ".") };
                    for (Object obj : nuevo9) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                        celda.setColspan(1);
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }
                    Object nuevo10[] = { "Rentabilidad ", "", df.format(porcent).replace(",", ".") + " %" };
                    for (Object obj : nuevo10) {
                        celda = new PdfPCell(new Paragraph((String) obj, new Font(fontpersonalizado)));
                        celda.setBorder(PdfPCell.NO_BORDER);
                        celda.setColspan(1);
                        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                        tabla.addCell(celda);
                    }

                    salto = new PdfPTable(1);
                    casilla = new PdfPCell(new Phrase("", new Font(fontpersonalizado)));
                    casilla.setMinimumHeight(90);
                    casilla.setBorder(PdfPCell.NO_BORDER);
                    salto.addCell(casilla);
                    documento.add(salto);

                    documento.add(tabla);

                    /*Fin Parte 3*/
                    documento.close();
                    helper.cerrarSesion();
                } catch (Exception ex) {
                    documento.close();
                }
                JOptionPane.showMessageDialog(null, "PDF Generado");
            } catch (Exception io) {
                System.out.println(io);
            }
        }
    });
    f.getjTable1().addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int row = f.getjTable1().getSelectedRow();
            int col = f.getjTable1().getSelectedColumn();
            if (col == 4) {
                f2.setVisible(true);
                f.setVisible(false);
                idcliente = f.getjTable1().getValueAt(row, 5).toString();
                idinstalacion = f.getjTable1().getValueAt(row, 6).toString();
                f2.getjLabel15().setText(f.getjTable1().getValueAt(row, 0).toString());
                f2.getjLabel8().setText(f.getjTable1().getValueAt(row, 2).toString());
                nombrecliente = f.getjTable1().getValueAt(row, 0).toString();
                nombreinstalacion = f.getjTable1().getValueAt(row, 2).toString();
                updateTablas up = new updateTablas(1);
                up.start();
            }
        }
    });
    f5.getjComboBox1().addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            DefaultTableModel temp2 = (DefaultTableModel) f5.getjTable2().getModel();
            for (int i = temp2.getRowCount() - 1; i >= 0; i--) {
                temp2.removeRow(i);
            }
            f5.setComi(null);
            f5.setNinstalacion("");
            f5.setNcliente("");
            f5.setList(null);
            f5.setId("");
            updateTablas up = new updateTablas(4);
            up.start();
        }
    });
    f3.getjTable1().addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int row = f3.getjTable1().getSelectedRow();
            int col = f3.getjTable1().getSelectedColumn();
            if (col == 6) {
                visible(f4);
                fcomisiones = f3.getjTable1().getValueAt(row, 6).toString();
                try {
                    ServiceHb helper = new ServiceHb();
                    helper.iniciarTransaccion();
                    Fcomisiones ft = (Fcomisiones) helper.obtenerObjeto(Fcomisiones.class,
                            Integer.parseInt(fcomisiones));
                    numeroinstala = ft.getDias();
                    f4.setIdcliente("" + ft.getClientes().getId());
                    f4.setIdinstalacion("" + ft.getInstalacion().getId());
                    f4.getDiasint().setText(numeroinstala);
                    helper.cerrarSesion();
                } catch (Exception io) {

                }
                f4.getjLabel1().setText(fcomisiones);
                f4.getC1().setText(f3.getjTable1().getValueAt(row, 0).toString());
                f4.getC2().setText(f3.getjTable1().getValueAt(row, 1).toString());
                double campo1 = Double
                        .parseDouble(f3.getjTable1().getValueAt(row, 3).toString().replace("$ ", ""));
                double campo2 = Double
                        .parseDouble(f3.getjTable1().getValueAt(row, 4).toString().replace("-$ ", ""));
                f4.getC3().setText(f3.getjTable1().getValueAt(row, 3).toString());
                f4.getC4().setText(f3.getjTable1().getValueAt(row, 4).toString());
                f4.getC5().setText(f3.getjTable1().getValueAt(row, 5).toString());
                f4.getC6().setText("$ " + df.format((campo1 - campo2)).replace(",", "."));

                updateTablas up = new updateTablas(3);
                up.start();
            }
        }
    });

    setVisible(false);
}

From source file:Login.ventas.fproyectos.java

public void fondos(Document documento, PdfContentByte canvas) {
    try {/*ww  w  . j a va 2s .c  o  m*/
        Image imghead = Image.getInstance(usuario.getDireccion() + "/plantilla.jpg");
        imghead.setAbsolutePosition(0, 0);
        imghead.setAlignment(Image.ALIGN_CENTER);
        float scaler = ((documento.getPageSize().getWidth() - documento.leftMargin() - documento.rightMargin())
                / imghead.getWidth()) * 100;
        imghead.scalePercent(scaler);
        PdfTemplate tp = canvas.createTemplate(PageSize.A4.getWidth(), PageSize.A4.getHeight()); //el rea destinada para el encabezado
        tp.addImage(imghead);
        x = (int) imghead.getWidth();
        y = (int) imghead.getHeight();
        canvas.addTemplate(tp, 0, 0);//posicin del tmplate derecha y abajo
    } catch (IOException | DocumentException io) {

    }
}

From source file:me.champeau.deck2pdf.Browser.java

License:Apache License

public void doExport(final Profile profile, final int width, final int height) {
    final PauseTransition pt = new PauseTransition();
    pt.setDuration(Duration.millis(profile.getPause()));
    final AtomicInteger cpt = new AtomicInteger();
    final Document document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
    try {/*from w w w.jav  a  2 s  .  c  o  m*/
        PdfWriter.getInstance(document, new FileOutputStream(exportFile));
    } catch (DocumentException | FileNotFoundException e) {
        handleError(e);
        return;
    }
    document.open();
    profile.setDocument(document);
    pt.setOnFinished(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            WritableImage image = browser.snapshot(null, null);
            BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
            double scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                    - document.rightMargin()) / image.getWidth()) * 100;

            try {
                com.itextpdf.text.Image image2 = com.itextpdf.text.Image.getInstance(bufferedImage, null);
                image2.scalePercent((float) scaler);
                document.add(image2);
                document.newPage();
                int current = cpt.incrementAndGet();
                int nbSlides = profile.getSlideCount();
                System.out.println("Exported slide " + current + (nbSlides > 0 ? "/" + nbSlides : ""));
                if (!profile.isLastSlide(current)) {
                    profile.nextSlide();
                    pt.setDuration(Duration.millis(profile.getPause()));
                    pt.play();
                } else {
                    profile.finish();
                    document.close();
                    System.out.println("Export complete.");
                    Platform.exit();
                }
            } catch (IOException | DocumentException e) {
                handleError(e);
            }
        }
    });
    webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
        public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
            if (newState == Worker.State.SUCCEEDED) {
                profile.setup();
                profile.ready(new Runnable() {
                    public void run() {
                        pt.play();
                    }
                });
            }
        }
    });
}

From source file:modelo.Ejemplo1.java

/**
 * Raz.//from   w w w. j  ava2s  .co  m
 */
public static void main(String[] args) {
    //Creamos la representacin de una pgina, con un tamao
    //por defecto.

    Rectangle pagina = new Rectangle(PageSize.LETTER);

    //Establecemos el color de la pgina y reescribimos la funcin
    //toString de la clase BaseColor para obtener el nombre del color.

    // Creamos un documento y le pasamos como parametro un objeto de
    // tipo Rectangle, dicho objeto contiene las especificaciones
    // de como se vera nuestra pgina.
    Document documento = new Document(pagina);

    try {

        // Obtenemos una instancia de un objeto PDFWriter
        PdfWriter.getInstance(documento, new FileOutputStream("Ejemplo1.pdf"));
        documento.open();

        // Generamos nuestro contenido.
        String contenido = "Generacin de un PDF simple:\n " + "\t\tAncho de pgina: "
                + documento.getPageSize().getWidth() + "\n\t\tAlto de pgina: "
                + documento.getPageSize().getHeight() + "\n\t\tColor de pgina: ";

        // Lo agregamos al documento por medio de una instancia
        // de un obtjeto Paragraph.
        //
        documento.add(new Paragraph(contenido));

        // Cerramos el documento para hacer persistente el contenido.
        documento.close();

    } catch (DocumentException ex) {
        // Atrapamos excepciones concernientes al documento.
    } catch (java.io.IOException ex) {
        // Atrapamos excepciones concernientes al I/O.
    }
}

From source file:net.algem.billing.InvoiceView.java

License:Open Source License

private void drawPdf(Document document, PdfWriter writer) {

    PdfContentByte cb = writer.getDirectContent();
    Graphics2D g = cb.createGraphics(document.getPageSize().getWidth(), document.getPageSize().getHeight());
    Quote quote = get();//ww w.  j  av  a 2  s  .com
    String genericLabel = invoice.getClass() == Quote.class ? BundleUtil.getLabel("Quotation.label")
            : BundleUtil.getLabel("Invoice.label");
    int left = ImageUtil.mmToPoints(110);
    int top = ImageUtil.mmToPoints(50);
    int bottom = ImageUtil.mmToPoints(297 - 20);// hauteur de page - 20 mm de marge
    int margin = ImageUtil.mmToPoints(15);

    Font defaultFont = g.getFont();
    g.setFont(serif);
    int itemsHeight = ((g.getFontMetrics().getHeight() * 2) * (quote.getItems().size() - 1)); // average
    int footerHeight = InvoiceFooterEditor.getFooter().size() * 10;
    int maxHeight = top + 160 + 20 + itemsHeight + ImageUtil.mmToPoints(50);

    drawHeader(g, defaultFont, quote, genericLabel, top, left, margin);
    int tablebottom = drawContent(g, quote, top, margin);

    if (maxHeight > (bottom - footerHeight)) {
        g.setFont(serif.deriveFont(Font.ITALIC));
        g.drawString(MessageUtil.getMessage("see.back.page.label"), margin, tablebottom + 10);
        drawFooter(g, margin, bottom);
        //IMPORTANT
        g.dispose();
        document.newPage();
        g = cb.createGraphics(document.getPageSize().getWidth(), document.getPageSize().getHeight());

        g.setFont(serif.deriveFont(Font.ITALIC));
        g.drawString("(page 2)", margin, top + 90);
        g.setFont(serif);
        g.drawString(genericLabel + " : " + quote.getNumber(), margin, top + 100);
        // description
        g.drawString(BundleUtil.getLabel("Invoice.description.label") + " : " + quote.getDescription(), margin,
                top + 140);
        // pied tableau
        new InvoiceFooterElement(margin, top + 160, quote).draw(g);
        // infos lgales
        drawFooter(g, margin, bottom);
        g.dispose();
    } else {
        // pied tableau
        new InvoiceFooterElement(margin, tablebottom + 20, quote).draw(g);
        // infos lgales
        drawFooter(g, margin, bottom);
        g.dispose();
    }

}

From source file:net.FilterLogic.imaging.ToPDF.java

License:Apache License

private void writeMultiPagePDF(String fileName) throws Exception {
    float STD_WIDTH = 620;
    float STD_HEIGHT = 775;
    float newWidth = 0;
    float newHeight = 0;
    float xPos = 0;
    float yPos = 0;

    boolean scaleImage = true;
    boolean pdfAutoOrientation = true;
    boolean autoCenter = false;
    boolean portrait = true;

    BufferedImage img = null;//from  ww  w . j a va 2 s  .  c om
    Document pdf;

    PdfWriter writer;

    try {
        // scale image
        String si = this.documentProperties.getProperty(KEY_SCALE_TO_FIT, KEY_SCALE_TO_FIT_DEFAULT);
        scaleImage = Boolean.parseBoolean(si);

        // auto-orientation
        String ao = this.documentProperties.getProperty(KEY_AUTO_ORIENTATION, KEY_AUTO_ORIENTATION_DEFAULT);
        pdfAutoOrientation = Boolean.parseBoolean(ao);

        // auto-center
        String ac = this.documentProperties.getProperty(KEY_AUTO_CENTER, KEY_AUTO_CENTER_DEFAULT);
        autoCenter = Boolean.parseBoolean(ac);

        if (document.size() > 0)
            img = document.get(0);

        if (img != null) {

            // if dpi set, calculate new width/height
            if (horizontalDPI > 0 && verticalDPI > 0) {
                float xd = (float) horizontalDPI / 100;
                float yd = (float) verticalDPI / 100;

                newWidth = img.getWidth() / xd;
                newHeight = img.getHeight() / yd;
            } else {
                newWidth = img.getWidth();
                newHeight = img.getHeight();
            }

            // if image width or height changed, scale
            if (newWidth != img.getWidth() || newHeight != img.getHeight())
                scaleImage = true;

            // if auto orientation, set portrait or landscape 
            if (pdfAutoOrientation) {
                if (newWidth >= newHeight) {
                    pdf = new Document(PageSize.LETTER.rotate());
                    portrait = false;
                } else {
                    pdf = new Document(PageSize.LETTER);
                    portrait = true;
                }
            } else {
                // else, always portrait
                pdf = new Document(PageSize.LETTER);
                portrait = true;
            }

            writer = PdfWriter.getInstance(pdf, new FileOutputStream(fileName));

            writer.setFullCompression();

            pdf.open();

            // set document props
            setDocumentProperties(pdf);

            int t = 0;

            float pdfPageWidth = pdf.getPageSize().getWidth();
            float pdfPageHeight = pdf.getPageSize().getHeight();

            // if new image larger than standard size, override and enable image scaling
            if (newWidth > pdfPageWidth || newHeight > pdfPageHeight) {
                scaleImage = true;

                if (newWidth > pdfPageWidth)
                    newWidth = pdfPageWidth;

                if (newHeight > pdfPageHeight)
                    newHeight = pdfPageHeight;
            }

            // break out each page to single file
            while (t < totalPages) {
                PdfContentByte cb = writer.getDirectContent();
                com.itextpdf.text.Image pdfImage;

                if (img != null) {
                    pdfImage = com.itextpdf.text.Image.getInstance(img, null);

                    // calculate center
                    if (autoCenter) {
                        if (portrait) {
                            xPos = (pdfPageWidth - newWidth) / 2;
                            yPos = (pdfPageHeight - newHeight) / 2;
                        } else {
                            //xPos = ((pdfPageHeight * (float)1.60) - newWidth) / 2;
                            xPos = (pdfPageHeight - newWidth) / 2;
                            yPos = (pdfPageWidth - newHeight) / 2;
                        }
                    } else {
                        // if not scaling, set image to top left
                        if (!scaleImage) {
                            xPos = 0;
                            // calculate top left corner
                            yPos = pdfPageWidth - newHeight;
                        } else {
                            xPos = 0;
                            yPos = 0;
                        }
                    }

                    // check if x and y pos >=0
                    if (xPos < 0)
                        xPos = 0;
                    if (yPos < 0)
                        yPos = 0;

                    if (scaleImage) {

                        if (!portrait) {
                            pdfImage.scaleToFit(newHeight, newWidth);
                        } else {
                            pdfImage.scaleToFit(newWidth, newHeight);
                        }

                        // check is scaled height/width match new width/height
                        // if not, recalculate center if autcenter enabled.
                        if (newWidth != pdfImage.getScaledWidth() || newHeight != pdfImage.getScaledHeight()) {
                            newWidth = pdfImage.getScaledWidth();
                            newHeight = pdfImage.getScaledHeight();

                            // calculate center
                            if (autoCenter) {
                                xPos = (pdfPageWidth - newWidth) / 2;
                                yPos = (pdfPageHeight - newHeight) / 2;

                                // check if x and y pos >=0
                                if (xPos < 0)
                                    xPos = 0;
                                if (yPos < 0)
                                    yPos = 0;
                            }
                        }

                        pdfImage.setAbsolutePosition(xPos, yPos);
                    } else {
                        pdfImage.setAbsolutePosition(xPos, yPos);
                    }

                    cb.addImage(pdfImage);

                    // inc counter
                    ++t;

                    if (t < totalPages) {
                        img = document.get(t);

                        // if dpi set, calculate new width/height
                        if (horizontalDPI > 0 && verticalDPI > 0) {
                            float xd = (float) horizontalDPI / 100;
                            float yd = (float) verticalDPI / 100;

                            newWidth = img.getWidth() / xd;
                            newHeight = img.getHeight() / yd;
                        } else {
                            newWidth = img.getWidth();
                            newHeight = img.getHeight();
                        }

                        // if auto orientation, set portrait or landscape 
                        if (pdfAutoOrientation) {
                            if (newWidth >= newHeight) {
                                pdf.setPageSize(PageSize.LETTER.rotate());
                                portrait = false;
                            } else {
                                pdf.setPageSize(PageSize.LETTER);
                                portrait = true;
                            }
                        } else {
                            // else, always portrait
                            pdf.setPageSize(PageSize.LETTER);
                            portrait = true;
                        }

                        // create new page.  must happen after setting page orientation
                        pdf.newPage();
                        writer.newPage();

                        // get new pages width/height
                        pdfPageWidth = pdf.getPageSize().getWidth();
                        pdfPageHeight = pdf.getPageSize().getHeight();

                        // set width/height to something normal
                        if (newWidth > pdfPageWidth)
                            newWidth = pdfPageWidth;

                        if (newHeight > pdfPageHeight)
                            newHeight = pdfPageHeight;
                    }
                }

            }

            pdf.close();

            // add file name to list
            fileNames = new ArrayList<String>();
            fileNames.add(fileName);
        }
    } catch (Exception e) {
        throw new Exception(e);
    }
}