Example usage for com.itextpdf.text Image setAlignment

List of usage examples for com.itextpdf.text Image setAlignment

Introduction

In this page you can find the example usage for com.itextpdf.text Image setAlignment.

Prototype


public void setAlignment(final int alignment) 

Source Link

Document

Sets the alignment for the image.

Usage

From source file:dbms_prj.Display.java

public void create_pdf() throws Exception {
    Document doc = new Document();
    PdfWriter.getInstance(doc, new FileOutputStream(S1 + ".pdf"));
    Image image = Image.getInstance("src/Travel partners.png");
    image.scaleAbsolute(500f, 200f);/*from   w  w  w .ja  v a  2  s . c o m*/
    Image ima = Image.getInstance("src/images.jpg");
    ima.scaleAbsolute(100f, 100f);
    ima.setAlignment(Element.ALIGN_CENTER);
    PdfPTable table = new PdfPTable(9);
    PdfPCell cell = new PdfPCell(new Paragraph("Ticket"));
    cell.setColspan(9);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPadding(10.0f);
    cell.setBackgroundColor(new BaseColor(140, 221, 8));
    table.addCell(cell);
    table.addCell("PNR");
    table.addCell("BOOK_ID");
    table.addCell("FLIGHT_NO");
    table.addCell("NAME");
    table.addCell("SOURCE");
    table.addCell("DESTINATION");
    table.addCell("STATUS");
    table.addCell("FARE");
    table.addCell("Date");
    table.addCell(S1);
    table.addCell(S11);
    table.addCell(S4);
    table.addCell(S6 + " " + S7);
    table.addCell(S8);
    table.addCell(S9);
    table.addCell(S5);
    table.addCell(S10);
    table.addCell(S12);
    table.setSpacingBefore(30.0f); // Space Before table starts, like margin-top in CSS
    table.setSpacingAfter(30.0f);
    doc.open();
    //doc.add(new Paragraph("Hello!! Yo this is my first pdf!"));
    doc.add(image);
    doc.add(new Paragraph("Ticket created on " + new Date().toString()));
    doc.add(table);
    //doc.add(list);
    doc.add(ima);
    doc.close();
}

From source file:dbms_prj.Status.java

public void create_pdf() throws Exception {
    Document doc = new Document();
    PdfWriter.getInstance(doc, new FileOutputStream(S1 + ".pdf"));
    Image image = Image.getInstance("src/Travel partners.png");
    image.scaleAbsolute(500f, 200f);//from   w  w  w.  j  ava 2s . c  o m
    Image ima = Image.getInstance("src/images.jpg");
    ima.scaleAbsolute(100f, 100f);
    ima.setAlignment(Element.ALIGN_CENTER);
    PdfPTable table = new PdfPTable(9);
    PdfPCell cell = new PdfPCell(new Paragraph("Ticket"));
    cell.setColspan(9);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPadding(10.0f);
    table.setTotalWidth(300.0f);

    cell.setBackgroundColor(new BaseColor(140, 221, 8));
    table.addCell(cell);
    table.addCell("PNR");
    table.addCell("BOOK_ID");
    table.addCell("FLIGHT_NO");
    table.addCell("NAME");
    table.addCell("SOURCE");
    table.addCell("DESTINATION");
    table.addCell("STATUS");
    table.addCell("FARE");
    table.addCell("Date");
    table.addCell(S1);
    table.addCell(S11);
    table.addCell(S4);
    table.addCell(S6 + S7);
    table.addCell(S8);
    table.addCell(S9);
    table.addCell(S5);
    table.addCell(S10);
    table.addCell(S2);
    table.setSpacingBefore(50.0f); // Space Before table starts, like margin-top in CSS
    table.setSpacingAfter(50.0f);
    doc.open();
    //doc.add(new Paragraph("Hello!! Yo this is my first pdf!"));
    doc.add(image);
    //doc.add(new Paragraph("Ticket created on " + new Date().toString()));
    doc.add(table);
    //doc.add(list);
    doc.add(ima);
    doc.close();
}

From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java

License:Apache License

/**
 * Diese Methode erzeugt die Titelseite fr das PDF-Dokument mit der
 * Bezeichnung des Verfahrens.//from  ww  w  . j  ava2s.co m
 * 
 * @param bezVerfahren
 *            Bezeichnung des profilierten Verfahrens
 * @throws DocumentException
 * @throws MalformedURLException
 * @throws IOException
 */
private void erzeugeTitelSeite() throws DocumentException, MalformedURLException, IOException {
    // Symbol, falls vorhanden
    String pathImage = "./logo_doku.png";
    try {
        // Image image =
        // Image.getInstance(PdfCreatorImpl.class.getResource(pathImage));
        Image image = Image.getInstance(pathImage);
        image.setAlignment(Element.ALIGN_RIGHT);
        docPdf.add(image);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Fehler beim Einbinden der Grafik '" + pathImage + "'.", e);
        }
    }
    docPdf.add(getEmptyLineText());

    // Restliche Texte werden im Event-Handler geschrieben

    // Seitenumbruch
    docPdf.newPage();
}

From source file:digilib.pdf.PDFTitlePage.java

License:Open Source License

private Image getLogo() {
    try {/*from   w  ww  .  j a  v a  2  s. co  m*/
        URL url = new URL(job_info.getDlConfig().getAsString("pdf-logo"));
        if (url != null && !url.equals("")) {
            Image logo = Image.getInstance(url);
            logo.setAlignment(Element.ALIGN_CENTER);
            return logo;
        }
    } catch (BadElementException e) {
        logger.error(e.getMessage());
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
    return null;
}

From source file:edu.clemson.lph.pdfgen.PDFGen.java

License:Open Source License

private void printDoc() {
    if (sSourceFile == null || osDest == null) {
        logger.error("Cannot print nothing");
        return;/*from   ww w.  j  ava  2 s  . c o  m*/
    }
    boolean bBold = false;
    boolean bCenter = false;
    boolean bItalic = false;
    boolean bSmallItalic = false;
    boolean bUnderline = false;
    try {
        Document doc = new Document();
        float fCorr = doc.getPageSize().getWidth() / 8.5f;
        doc.setMargins(1.0f * fCorr, 1.0f * fCorr, 1.0f * fCorr, 1.0f * fCorr);

        PdfWriter.getInstance(doc, osDest);
        doc.open();
        BufferedReader br = new BufferedReader(new FileReader(sSourceFile));
        String sLine = br.readLine();
        while (sLine != null) {
            bBold = false;
            bCenter = false;
            if (sLine.startsWith(".")) {
                String sRest = sLine.substring(1);
                String sCodes = sRest.substring(0, sRest.indexOf('.'));
                sLine = sRest.substring(sRest.indexOf('.') + 1);
                if ("image".equals(sCodes)) {
                    String sFileName = sLine;
                    com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(sFileName);
                    image.setAlignment(Element.ALIGN_CENTER);
                    doc.add(image);
                    sLine = br.readLine();
                    continue;
                } else if ("himage".equals(sCodes)) {
                    String sFileName = sLine;
                    com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(sFileName);
                    image.scaleToFit(500, 40);
                    image.setAlignment(Element.ALIGN_CENTER);
                    doc.add(image);
                    Paragraph p = new Paragraph(" ");
                    doc.add(p);
                    sLine = br.readLine();
                    continue;
                } else if ("fimage".equals(sCodes)) {
                    int iBlanks = 9; // How do I figure out how many to get to end?
                    for (int i = 0; i < iBlanks; i++) {
                        Paragraph p = new Paragraph(" ");
                        doc.add(p);
                    }
                    String sFileName = sLine;
                    com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(sFileName);
                    image.scaleToFit(500, 40);
                    image.setAlignment(Element.ALIGN_CENTER);
                    doc.add(image);
                    sLine = br.readLine();
                    continue;
                } else if ("list".equals(sCodes)) {
                    String sFullLine = doSub(sLine);
                    StringTokenizer tok = new StringTokenizer(sFullLine, "\n");
                    List list = new List(List.UNORDERED);
                    while (tok.hasMoreTokens()) {
                        String sNextLine = tok.nextToken();
                        ListItem listItem = new ListItem(sNextLine, fNormal);
                        list.add(listItem);
                    }
                    doc.add(list);
                    sLine = br.readLine();
                    continue;
                }
                if (sCodes.contains("b"))
                    bBold = true;
                if (sCodes.contains("c"))
                    bCenter = true;
                if (sCodes.contains("i"))
                    bItalic = true;
                if (sCodes.contains("si"))
                    bSmallItalic = true;
                if (sCodes.contains("u"))
                    bUnderline = true;
            }
            if (sLine.trim().length() == 0)
                sLine = " ";

            String sFullLine = doSub(sLine);
            Paragraph p = new Paragraph();
            if (bBold)
                p.setFont(fBold);
            else if (bSmallItalic)
                p.setFont(fSmallItalic);
            else if (bItalic)
                p.setFont(fItalic);
            else if (bUnderline)
                p.setFont(fUnderline);
            else
                p.setFont(fNormal);
            if (bCenter) {
                p.setAlignment(Element.ALIGN_CENTER);
            } else {
                p.setAlignment(Element.ALIGN_LEFT);
            }
            p.add(sFullLine);
            doc.add(p);
            sLine = br.readLine();
        }
        br.close();
        doc.close();
    } catch (FileNotFoundException e) {
        logger.error("Could not find source file " + sSourceFile + " or destination", e);
    } catch (IOException e) {
        logger.error("Could not read file " + sSourceFile, e);
    } catch (DocumentException e) {
        logger.error("Error creating iText Document", e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

private void createImage(Document document, PdfWriter writer, Font featureHeaderStyle)
        throws BadElementException, MalformedURLException, IOException, DocumentException {
    Image imageSprite = Image.getInstance(new URL(
            "http://lh3.ggpht.com/_4msVPAgKJv8/SCRYD-pPVKI/AAAAAAAAAYU/zUN963EPoZc/s1024/102_0609.JPG"));
    imageSprite.setAbsolutePosition(400, 500);
    imageSprite.scaleAbsolute(171.0f, 250.0f);
    float imageSpriteY = document.getPageSize().getHeight() * 0.60f;
    float imageSpriteX = document.getPageSize().getWidth() * 0.65f;
    imageSprite.setAlignment(Image.UNDERLYING);

    document.add(imageSprite);/*from www .j a v  a2  s  .c  o m*/

    PdfContentByte cb = writer.getDirectContent();
    ColumnText ct = new ColumnText(cb);
    Chunk imageHeader = new Chunk("Images", featureHeaderStyle);
    ct.addText(imageHeader);
    ct.setAlignment(Element.ALIGN_LEFT);
    ct.setSimpleColumn(imageSpriteX, imageSpriteY - imageSprite.getScaledHeight(),
            imageSpriteX + imageSprite.getScaledWidth(), imageSpriteY + imageSprite.getScaledHeight() + 20);
    ct.go();

    ct = new ColumnText(cb);
    Chunk imageFooter = new Chunk("Footer to be set for a figure. Similar to 'image cpation'.",
            FontFactory.getFont(FontFactory.TIMES_ROMAN, 8));
    ct.addText(imageFooter);
    ct.setAlignment(Element.ALIGN_CENTER);
    ct.setSimpleColumn(imageSpriteX, imageSpriteY - 150, imageSpriteX + imageSprite.getScaledWidth(),
            imageSpriteY);
    ct.go();
}

From source file:edu.eci.pdsw.aeci.managedbeans.GenerarPDFbean.java

@PostConstruct
public void init() {

    try {//from w ww  . j  a  v  a2s.  c  om
        //----------------------------------
        nombre = login.getPersonaLog().getFirstName() + " " + login.getPersonaLog().getLastName();

        Carrera = login.getPersonaLog().getProgram().getName();
        periodo = login.getPersonaLog().getPeriod();
        String pe = login.getPersonaLog().getYearGraduate() + " - " + periodo;
        Cedula = login.getPersonaLog().getId();

        Document doc = new Document();
        Paragraph parrafo, parrafo2, parrafo3, parrafo4;
        Image imagenLogo = Image.getInstance("Logo.jpeg");
        Image imagenFirma = Image.getInstance("firmaDigital.jpeg");
        OutputStream out = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(doc, out);

        doc.open();
        imagenLogo.setAlignment(Element.ALIGN_CENTER);
        doc.add(imagenLogo);
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        parrafo = new Paragraph("CERTIFICADO DE AFILIACIN AECI");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        parrafo2 = new Paragraph(
                "La Asociacin de  Egresados de la  Escuela Colombiana de Ingeniera Julio Garavito AECI, con "
                        + "Nit. 830.031.137- 4, certifica que el Ingeniero(a) egresado de la carrera " + Carrera
                        + " Graduado en el periodo " + pe + "," + " " + nombre
                        + ", identificado con la cdula de Ciudadana N" + Cedula + ","
                        + " est afiliado a esta Asociacin y se encuentra al da con su aporte, "
                        + " el cual fue realizado a travs de la consignacin " + Consignacion + " y"
                        + " la factura de venta N " + factura + " del dia " + fechaActual);
        parrafo2.setAlignment(Element.ALIGN_JUSTIFIED);
        doc.add(parrafo2);
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        /** add **/
        parrafo = new Paragraph("Coordialmente");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);

        imagenFirma.setAlignment(Element.ALIGN_CENTER);
        doc.add(imagenFirma);
        parrafo = new Paragraph("JUAN CARLOS ROMERO ORDEZ");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        parrafo = new Paragraph("Director");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        parrafo = new Paragraph("Asociacion de Egresados Escuela Colombiana de Ingeniera Julio Garavito");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));
        parrafo = new Paragraph(
                "AK 45 no 205-59 * Bloque A -piso 2 * Telfonos 6683600 ext 323-Mvil 3124570612 *");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        parrafo = new Paragraph(
                "Correo electronico aeci@escuelaing.edu.co * Facebook Twitter AECI/escuelaing www.aeci.org.co");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        parrafo = new Paragraph("Bogot-Colombia");
        parrafo.setAlignment(Element.ALIGN_CENTER);
        doc.add(parrafo);
        doc.close();
        out.close();

        InputStream in = new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());

        streamedContent = new DefaultStreamedContent(in, "application/pdf");
        //-------
        Map<String, Object> session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        byte[] b = (byte[]) session.get("reportBytes");
        if (b != null) {
            streamedContent = new DefaultStreamedContent(new ByteArrayInputStream(b), "application/pdf");
        }
    } catch (Exception e) {
        System.out.println(Carrera + "mierdaadw");
    }

}

From source file:edu.harvard.mcz.precapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(ArrayList<ContainerLabel> containers) throws PrintFailedException {
    log.debug("Invoked printList ");
    boolean result = false;
    ContainerLabel label = new ContainerLabel();
    if (containers.isEmpty()) {
        log.debug("No labels to print.");
    } else {/*from   www  . java 2s  .  co  m*/
        LabelDefinitionType printDefinition = null;
        LabelDefinitionListType printDefs = PreCaptureSingleton.getInstance().getPrintFormatDefinitionList();
        List<LabelDefinitionType> printDefList = printDefs.getLabelDefinition();
        Iterator<LabelDefinitionType> il = printDefList.iterator();
        while (il.hasNext()) {
            LabelDefinitionType def = il.next();
            if (def.getTitle().equals(PreCaptureSingleton.getInstance().getProperties().getProperties()
                    .getProperty(PreCaptureProperties.KEY_SELECTED_PRINT_DEFINITION))) {
                printDefinition = def;
            }
        }
        if (printDefinition == null) {
            log.error("No selected print format defintion found.");
            //TODO change from message to error handling dialog that allows picking a print format.
            JOptionPane.showMessageDialog(null, "Unable to print.  No print format is selected.");
        } else {

            log.debug(printDefinition.getTitle());
            log.debug(printDefinition.getTextOrentation().toString());

            LabelEncoder encoder = new LabelEncoder(containers.get(0));
            try {
                Image image = encoder.getImage();
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(PreCaptureSingleton.getInstance()
                        .getProperties().getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE)));
                // Convert units in print definition to points (72 points/inch, 28.346456 points/cm)

                int paperWidthPoints = 612; // 8.5"
                int paperHeightPoints = 792; // 11"
                int marginsPoints = 36; // 0.5"
                int labelWidthPoints = 540; // 7.5" 
                int labelHeightPoints = 720; // 10"
                int numColumns = 1; // goes with above

                numColumns = printDefinition.getColumns();
                float relWidthTextCell = printDefinition.getRelWidthTextCell();
                float relWidthBarcodeCell = printDefinition.getRelWidthBarcodeCell();
                log.debug("relWidthTextCell = " + relWidthTextCell);
                log.debug("relWidthBarcodeCell = " + relWidthBarcodeCell);

                if (printDefinition.getUnits().toString().toLowerCase().equals("inches")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 72f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 72f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 72f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 72f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 72f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("cm")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 28.346456f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 28.346456f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 28.346456f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 28.346456f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 28.346456f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("points")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 1f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 1f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 1f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 1f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 1f);
                }

                if (paperWidthPoints == 612 && paperHeightPoints == 792) {
                    document.setPageSize(PageSize.LETTER);
                } else {
                    document.setPageSize(new Rectangle(paperWidthPoints, paperHeightPoints));
                }
                document.setMargins(marginsPoints, marginsPoints, marginsPoints, marginsPoints);
                document.open();

                // Sanity check
                if (paperWidthPoints <= 0) {
                    paperWidthPoints = 612;
                }
                if (paperHeightPoints <= 0) {
                    paperHeightPoints = 792;
                }
                if (marginsPoints < 0) {
                    marginsPoints = 0;
                }
                if (labelWidthPoints <= 0) {
                    labelWidthPoints = 540;
                }
                if (labelHeightPoints <= 0) {
                    labelHeightPoints = 720;
                }
                if (paperWidthPoints + (marginsPoints * 2) < labelWidthPoints) {
                    labelWidthPoints = paperWidthPoints + (marginsPoints * 2);
                    log.debug("Adjusting label width to fit printable page width");
                }
                if (paperHeightPoints + (marginsPoints * 2) < labelHeightPoints) {
                    labelHeightPoints = paperHeightPoints + (marginsPoints * 2);
                    log.debug("Adjusting label height to fit printable page height");
                }

                // calculate how many columns will fit on the paper.
                int columns = (int) Math.floor((paperWidthPoints - (marginsPoints * 2)) / labelWidthPoints);
                // if specified column count is smaller, use the specified.
                if (numColumns < columns) {
                    columns = numColumns;
                    log.debug(
                            "Fewer columns specified in definition than will fit on page, using specified column count of "
                                    + numColumns);
                }

                // define two table cells per column, one for text one for barcode.
                int subCellColumnCount = columns * 2;

                // set the table, with an absolute width and relative widths of the cells in the table;
                PdfPTable table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                // figure out the width of the cells containing the barcodes.
                float ratio = ((float) relWidthBarcodeCell)
                        / (((float) relWidthBarcodeCell) + ((float) relWidthTextCell));
                float barcodeCellWidthPoints = (float) Math.floor(labelWidthPoints * ratio);
                log.debug("Width of barcode cell in points: " + barcodeCellWidthPoints);

                //Rectangle pageSizeRectangle = new Rectangle(paperWidthPoints, paperHeightPoints);
                //table.setWidthPercentage(cellWidthsPoints, pageSizeRectangle);
                //table.setTotalWidth(cellWidthsPoints);

                // Calculate how many cells fit on a page (two cells per label).
                int labelsPerColumn = (int) Math
                        .floor((paperHeightPoints - (marginsPoints * 2)) / labelHeightPoints);
                int cellsPerPage = subCellColumnCount * labelsPerColumn;
                log.debug("Labels per column = " + labelsPerColumn);
                log.debug("Cells per page = " + cellsPerPage);

                Iterator<ContainerLabel> iterLabels = containers.iterator();

                int cellCounter = 0; // counts number of cells filled on a page.
                int counter = 0; // counts number of pre capture label data rows to print (each of which may request more than one copy).

                // TODO: Doesn't fit on page.

                while (iterLabels.hasNext()) {
                    // Loop through all of the container labels found to print 
                    label = iterLabels.next();
                    if (label != null) {
                        log.debug(label);
                        log.debug("Label: " + counter + " " + label.toString());
                        for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                            // For each container label, loop through the number of requested copies 
                            // Generate a text and a barcode cell for each, and add to array for page
                            int toPrintPlus = toPrint + 1; // for pretty counter in log.
                            log.debug("Copy " + toPrintPlus + " of " + label.getNumberToPrint());

                            PdfPCell cell = label.toPDFCell(printDefinition);
                            cell.setFixedHeight(labelHeightPoints);
                            // Colors to illustrate where the cells are on the layout
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell.setBackgroundColor(new BaseColor(255, 255, 30));
                            }

                            PdfPCell cell_barcode = new PdfPCell();
                            cell_barcode.setBorderColor(BaseColor.LIGHT_GRAY);
                            cell_barcode.disableBorderSide(PdfPCell.LEFT);
                            cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                            cell_barcode.setHorizontalAlignment(Element.ALIGN_RIGHT);
                            cell_barcode.setFixedHeight(labelHeightPoints);
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell_barcode.setBackgroundColor(new BaseColor(255, 30, 255));
                            }

                            encoder = new LabelEncoder(label);
                            image = encoder.getImage();
                            image.setAlignment(Image.ALIGN_TOP);
                            //image.setAlignment(Image.ALIGN_LEFT);
                            image.setAlignment(Image.ALIGN_RIGHT);
                            image.scaleToFit(barcodeCellWidthPoints, labelHeightPoints);
                            cell_barcode.addElement(image);

                            table.addCell(cell);
                            table.addCell(cell_barcode);

                            cellCounter = cellCounter + 2; // we've added two cells to the page (two cells per label).
                            log.debug("Cells " + cellCounter + " of " + cellsPerPage + " cells per page.");

                            // If we have hit a full set of labels for the page, add them to the document
                            // in each column, filling left to right
                            if (cellCounter >= cellsPerPage - 1) {
                                log.debug("Page is full");
                                log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                                        + table.getRows().size() + " rows ");
                                // Reset to begin next page
                                cellCounter = 0;
                                table.setLockedWidth(true);
                                document.add(table);
                                log.debug("Adding new page");
                                document.newPage();
                                table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                                log.debug("Setup new table");
                            }
                        } // end loop through toPrint (for a taxon/precapture label data row)
                        counter++; // Increment number of pre capture label data rows.
                    } // end if not null label
                } // end while results has next (for all taxa requested)
                  // get any remaining cells in pairs
                if (cellCounter > 0) {
                    log.debug("Adding remaining cells in partial page");
                    if (cellCounter <= cellsPerPage) {
                        for (int i = cellCounter; i <= cellsPerPage; i++) {
                            PdfPCell emptyCell = new PdfPCell();
                            emptyCell.setBorder(PdfPCell.NO_BORDER);
                            table.addCell(emptyCell);
                        }
                    }
                    log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                            + table.getRows().size() + " rows ");
                    table.setLockedWidth(true);
                    document.add(table);
                }
                document.close();

                // send to printer
                PrintingUtility.sendPDFToPrinter(printDefinition, paperWidthPoints, paperHeightPoints);

                // Check to see if there was content in the document.
                if (counter == 0) {
                    result = false;
                } else {
                    // Printed to pdf ok.
                    result = true;
                }
            } catch (FileNotFoundException e) {
                log.debug(e.getMessage(), e);
                throw new PrintFailedException("File not found.");
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new PrintFailedException("Error building/printing PDF document. " + e.getMessage());
            } catch (OutOfMemoryError e) {
                System.out.println("Out of memory error. " + e.getMessage());
                System.out.println("Failed.  Too many labels.");
                throw new PrintFailedException("Ran out of memory, too many labels at once.");
            } catch (BarcodeCreationException e) {
                System.out.println("BarcodeCreationException. " + e.getMessage());
                System.out.println("Failed.  Couldn't create barcode.");
                throw new PrintFailedException(
                        "Unable to create barcode.  Probably too many characters to encode. " + e.getMessage());
            }
        }
        log.debug("printList Done. Success = " + result);
    }
    return result;
}

From source file:edu.ucue.jparking.srv.ExportOrdenPagoService.java

private void addContent(Document document, String cedula)

        throws DocumentException, UsuarioNoExistenteException, CedulaNoValidaException,
        ContratoNoEstablecidoException, FueraDelDiaDePagoException, BadElementException, IOException,
        UsuarioNoRegistradoEnUnParqueaderoException, ClassNotFoundException, FileNotFoundException,
        ObjectSizeException {//from  ww  w  .ja  v  a2  s .c o m

    document.addTitle("Orden de pago del Parqueadero");
    Paragraph preface = new Paragraph();
    // Lets write a big header
    Paragraph tituloUniversidad = new Paragraph("UNIVERSIDAD DE CUENCA", catFont);
    Paragraph subtituloOrdenPago = new Paragraph("ORDEN DE PAGO", subFont);
    tituloUniversidad.setAlignment(Paragraph.ALIGN_CENTER);
    subtituloOrdenPago.setAlignment(Paragraph.ALIGN_CENTER);
    Image logoU = null;

    logoU = Image.getInstance(getClass().getResource("/edu/ucue/jparking/img/logo_u.png"));
    logoU.scalePercent(10);
    logoU.setAlignment(Image.ALIGN_CENTER);

    OrdenPagoService ops = new OrdenPagoService();
    UsuarioService service = new UsuarioService();
    Usuario u = service.get(cedula);
    OrdenPago orden = ops.getOrdenPago(cedula);
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

    preface.add(tituloUniversidad);
    addEmptyLine(preface, 1);
    preface.add(logoU);
    addEmptyLine(preface, 1);
    preface.add(subtituloOrdenPago);
    addEmptyLine(preface, 2);
    preface.add(new Paragraph(String.format("%s %s", "Fecha:", df.format(Calendar.getInstance().getTime())),
            smallBody));
    preface.add(new Paragraph(String.format("%s %s", "Cdula:", u.getCedula()), smallBody));
    preface.add(
            new Paragraph(String.format("%s %s %s", "Nombre:", u.getNombres(), u.getApellidos()), smallBody));
    preface.add(new Paragraph(String.format("%s %s", "Direccin:", u.getDireccion()), smallBody));
    preface.add(new Paragraph(String.format("%s %s", "Telfono:", u.getTelefono()), smallBody));
    preface.add(new Paragraph(String.format("%s %s", "Tipo de Usuario:", u.getTipoUsuarioString()), smallBody));
    //preface.add(new Paragraph(String.format("%s %s", "Fecha de contrato:", df.format(orden.getFechaEmision().getTime())), smallBody));
    preface.add(new Paragraph(String.format("%s $%.2f", "Valor a pagar:", orden.getCosto()), smallBody));
    /*if(u.estaDebiendo()){
    preface.add(new Paragraph("Estado:           Debe"));
    }else{
    preface.add(new Paragraph("Estado:           Cancelado"));
    }*/
    addEmptyLine(preface, 2);
    preface.add(new Paragraph(String.format("%s ...............................", "Firma:"), smallBody));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph(String.format("%s ..........................", "Autorizado:"), smallBody));
    addEmptyLine(preface, 2);
    preface.add(new Paragraph("Documento generado automticamente por la aplicacin JParking.", footPage));

    document.add(preface);
}

From source file:empguadalupe.Menu.Evaluacion.Menu.Resultado.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    FileOutputStream archivo = null;
    String nombrearchivo = NombreOP.getText() + "_" + CedulaOP.getText();

    try {/*from  w w w.  ja  va 2  s . c om*/
        archivo = new FileOutputStream(nombrearchivo + ".pdf");
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(rootPane, "Cierre la ventana del PDF para poder crear uno nuevo");
        return;
    }
    Document documento = new Document();
    try {
        PdfWriter.getInstance(documento, archivo);
    } catch (DocumentException ex) {

    }
    documento.open();
    try {
        Image foto = Image.getInstance("src\\imgfondo\\thumbGRUPO20EPM20CON20CIERRE202013.jpg");
        foto.scaleToFit(150, 150);
        foto.setAlignment(Chunk.ALIGN_LEFT);
        documento.add(foto);
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {

        documento.add(new Paragraph("RESULTADOS EVALUACION GENERAL", FontFactory.getFont("arial", // fuente
                27, // tamao
                Font.BOLD, BaseColor.BLACK)));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        documento.add(new Paragraph("\r\n\r\n\r\n\r\n"));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("Nombre del Funcionario:   " + NombreOP.getText() + "\r\n\r\n"));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("Cedula del Funcionario:   " + CedulaOP.getText() + "\r\n\r\n"));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("Registro EPM del Funcionario:   " + Registro.getText() + "\r\n\r\n"));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("Nombre del Gestor:" + NombreS.getText() + "\r\n\r\n"));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("\r\n\r\n"));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {

        documento.add(new Paragraph("RESULTADOS ", FontFactory.getFont("arial", // fuente
                17, // tamao
                Font.BOLD, BaseColor.BLACK)));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("\r\n\r\n" + "Arranque ", FontFactory.getFont("arial", // fuente
                15, // tamao
                Font.BOLD, BaseColor.BLACK)));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        documento.add(new Paragraph("Numero de Intentos Negativos:   " + CalificacionA.getText() + "         "
                + "Tiempo:   " + tiempoA));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("\r\n\r\n" + "Paro Normal ", FontFactory.getFont("arial", // fuente
                15, // tamao
                Font.BOLD, BaseColor.BLACK)));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        documento.add(new Paragraph("Numero de Intentos Negativos:   " + CalificacionA1.getText() + "         "
                + "Tiempo:   " + tiempoA1));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("\r\n\r\n" + "Paro Rapido ", FontFactory.getFont("arial", // fuente
                15, // tamao
                Font.BOLD, BaseColor.BLACK)));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        documento.add(new Paragraph("Numero de Intentos Negativos:   " + CalificacionA2.getText() + "         "
                + "Tiempo:   " + tiempoA2));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        documento.add(new Paragraph("\r\n\r\n" + "Paro de Emergencia ", FontFactory.getFont("arial", // fuente
                15, // tamao
                Font.BOLD, BaseColor.BLACK)));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        documento.add(new Paragraph("Numero de Intentos Negativos:   " + CalificacionA3.getText() + "         "
                + "Tiempo:" + tiempoA3));
    } catch (DocumentException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
    documento.close();
    File path = new File(nombrearchivo + ".pdf");
    try {
        Desktop.getDesktop().open(path);
    } catch (IOException ex) {
        Logger.getLogger(Resultado.class.getName()).log(Level.SEVERE, null, ex);
    }
}