Example usage for com.itextpdf.text FontFactory getFont

List of usage examples for com.itextpdf.text FontFactory getFont

Introduction

In this page you can find the example usage for com.itextpdf.text FontFactory getFont.

Prototype


public static Font getFont(final String fontname, final float size, final int style, final BaseColor color) 

Source Link

Document

Constructs a Font-object.

Usage

From source file:com.algoboss.erp.util.report.PDFExporter.java

License:Apache License

protected PdfPTable exportPDFTable(FacesContext context, DataTable table, boolean pageOnly,
        boolean selectionOnly, boolean filteredOnly, String encoding) {
    int columnsCount = getColumnsCount(table);
    PdfPTable pdfTable = new PdfPTable(columnsCount);
    this.cellFont = FontFactory.getFont(FontFactory.TIMES, encoding, 7, Font.NORMAL);
    this.facetFont = FontFactory.getFont(FontFactory.TIMES, encoding, 7, Font.BOLD, BaseColor.BLUE);
    this.facetBgColor = BaseColor.LIGHT_GRAY;

    addColumnFacets(table, pdfTable, ColumnType.HEADER);

    if (pageOnly) {
        exportPageOnly(context, table, pdfTable);
    } else if (selectionOnly) {
        exportSelectionOnly(context, table, pdfTable);
    } else if (filteredOnly) {
        exportFilteredOnly(context, table, pdfTable);
    } else {/*from ww  w.  j  a  va 2s  .c om*/
        exportAll(context, table, pdfTable);
    }

    if (table.hasFooterColumn()) {
        addColumnFacets(table, pdfTable, ColumnType.FOOTER);
    }

    table.setRowIndex(-1);

    return pdfTable;
}

From source file:com.base2.kagura.core.ExportHandler.java

License:Apache License

/**
 * Takes the output and transforms it into a PDF file.
 * @param out Output stream.//from   w  w w  . j ava 2 s  .c  o  m
 * @param rows Rows of data from reporting-core
 * @param columns Columns to list on report
 */
public void generatePdf(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
    try {
        Document document = new Document();
        PdfWriter.getInstance(document, out);
        if (columns == null) {
            if (rows.size() > 0)
                return;
            columns = new ArrayList<ColumnDef>(CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
                @Override
                public Object transform(final Object input) {
                    return new ColumnDef() {
                        {
                            setName((String) input);
                        }
                    };
                }
            }));
        }
        if (columns.size() > 14)
            document.setPageSize(PageSize.A1);
        else if (columns.size() > 10)
            document.setPageSize(PageSize.A2);
        else if (columns.size() > 7)
            document.setPageSize(PageSize.A3);
        else
            document.setPageSize(PageSize.A4);
        document.open();
        Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL, BaseColor.BLACK);
        Font headerFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD, BaseColor.BLACK);

        int size = columns.size();
        PdfPTable table = new PdfPTable(size);
        for (ColumnDef column : columns) {
            PdfPCell c1 = new PdfPCell(new Phrase(column.getName(), headerFont));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
        }
        table.setHeaderRows(1);
        if (rows != null)
            for (Map<String, Object> row : rows) {
                for (ColumnDef column : columns) {
                    table.addCell(new Phrase(String.valueOf(row.get(column.getName())), font));
                }
            }
        document.add(table);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.bdaum.zoom.email.internal.job.PdfJob.java

License:Open Source License

private void printPage(Document document, int pageNo, MultiStatus status, IProgressMonitor monitor)
        throws DocumentException, IOException {
    if (pageNo > 1)
        document.newPage();//from  www. j  a v  a2 s .  c  o  m
    document.setPageCount(pageNo);
    final Display display = Display.getDefault();
    int pageItem = 0;
    if (!layout.getTitle().isEmpty()) {
        String title = PageProcessor.computeTitle(layout.getTitle(), fileName, now, assets.size(), pageNo,
                pages, collection, meta);
        Paragraph p = new Paragraph(title,
                FontFactory.getFont(FontFactory.HELVETICA, titleSize, Font.BOLD, BaseColor.DARK_GRAY));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(layout.getSubtitle().isEmpty() ? titleLead + upperWaste : titleLead);
        document.add(p);
    }
    if (!layout.getSubtitle().isEmpty()) {
        String subtitle = PageProcessor.computeTitle(layout.getSubtitle(), fileName, now, assets.size(), pageNo,
                pages, collection, meta);
        Paragraph p = new Paragraph(subtitle,
                FontFactory.getFont(FontFactory.HELVETICA, subtitleSize, Font.NORMAL, BaseColor.DARK_GRAY));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(subtitleLead + upperWaste);
        document.add(p);
    }
    IVolumeManager vm = Core.getCore().getVolumeManager();
    PdfPTable table = new PdfPTable(layout.getColumns());
    try (Assetbox box = new Assetbox(null, status, false)) {
        for (int i = 0; i < rows; i++) {
            int ni = i * layout.getColumns();
            for (int j = 0; j < layout.getColumns(); j++) {
                int a = (pageNo - 1) * imagesPerPage + ni + j;
                PdfPCell cell;
                if (a >= assets.size() || monitor.isCanceled())
                    cell = new PdfPCell();
                else {
                    final int dpi = quality == Constants.SCREEN_QUALITY ? SCREENDPI : PRINTERDPI;
                    final int pixelWidth = (int) (imageWidth * dpi / 72);
                    final int pixelHeight = (int) (imageHeight * dpi / 72);
                    Asset asset = assets.get(a);
                    zimage = new ZImage(ImageUtilities.loadThumbnail(display, asset.getJpegThumbnail(), cms,
                            SWT.IMAGE_JPEG, true), null);
                    org.eclipse.swt.graphics.Rectangle bounds = zimage.getBounds();
                    URI uri = vm.findExistingFile(asset, false);
                    if (uri != null) {
                        boolean r = asset.getRotation() % 180 != 0;
                        double w = r ? asset.getHeight() : asset.getWidth();
                        double h = r ? asset.getWidth() : asset.getHeight();
                        double scale = w == 0 || h == 0 ? 1d : Math.min(pixelWidth / w, pixelHeight / h);
                        scale = (scale <= 0.5d) ? 0.5d : 1d;
                        File file = box.obtainFile(uri);
                        if (file != null)
                            try {
                                ZImage hzimage = CoreActivator.getDefault().getHighresImageLoader().loadImage(
                                        null, status, file, asset.getRotation(),
                                        asset.getFocalLengthIn35MmFilm(), null, scale, Double.MAX_VALUE, true,
                                        ImageConstants.SRGB, null, unsharpMask, null, fileWatcher, opId, null);
                                if (hzimage != null) {
                                    zimage.dispose();
                                    zimage = hzimage;
                                }
                            } catch (UnsupportedOperationException e) {
                                // do nothing
                            }
                    }
                    display.syncExec(() -> {
                        int kl = (keyLine > 0) ? (int) Math.max(1, (keyLine * dpi / 144)) : 0;
                        org.eclipse.swt.graphics.Rectangle ibounds = zimage.getBounds();
                        double factor = Math.min((double) pixelWidth / ibounds.width,
                                (double) pixelHeight / ibounds.height);
                        int lw = pixelWidth + 2 * kl;
                        int lh = pixelHeight + 2 * kl;
                        Image newImage = new Image(display, lw, lh);
                        GC gc = new GC(newImage);
                        try {
                            gc.setAntialias(SWT.ON);
                            gc.setInterpolation(SWT.HIGH);
                            gc.setAdvanced(true);
                            gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
                            gc.fillRectangle(0, 0, lw, lh);
                            int width = (int) (ibounds.width * factor + 2 * kl);
                            int height = (int) (ibounds.height * factor + 2 * kl);
                            int xoff = (lw - width) / 2;
                            int yoff = (lh - height) / 2;
                            if (kl > 0) {
                                gc.setBackground(display.getSystemColor(SWT.COLOR_DARK_GRAY));
                                gc.fillRectangle(xoff, yoff, width, height);
                            }
                            zimage.draw(gc, 0, 0, ibounds.width, ibounds.height, xoff + kl, yoff + kl,
                                    width - 2 * kl, height - 2 * kl, ZImage.CROPPED, pixelWidth, pixelHeight,
                                    false);
                        } finally {
                            gc.dispose();
                            zimage.dispose();
                            zimage = new ZImage(newImage, null);
                        }
                    });
                    bounds = zimage.getBounds();
                    File jpegFile = ImageActivator.getDefault().createTempFile("PdfImg", ".jpg"); //$NON-NLS-1$//$NON-NLS-2$
                    tempFiles.add(jpegFile);
                    try (FileOutputStream out = new FileOutputStream(jpegFile)) {
                        zimage.saveToStream(monitor, true, ZImage.UNCROPPED, SWT.DEFAULT, SWT.DEFAULT, out,
                                SWT.IMAGE_JPEG, jpegQuality);
                    }
                    zimage.dispose();
                    com.itextpdf.text.Image pdfImage = com.itextpdf.text.Image.getInstance(jpegFile.getPath());
                    double factor = Math.min(imageWidth / bounds.width, imageHeight / bounds.height);
                    pdfImage.setInterpolation(true);
                    pdfImage.scaleToFit((float) (bounds.width * factor), (float) (bounds.height * factor));
                    cell = new PdfPCell(pdfImage, false);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    monitor.worked(1);
                }
                cell.setFixedHeight((float) imageHeight);
                cell.setBorderWidth(0);
                table.addCell(cell);
            }
            renderCaptions(pageNo, seqNo, pageItem, table, ni, layout.getCaption1());
            renderCaptions(pageNo, seqNo, pageItem, table, ni, layout.getCaption2());
            pageItem += layout.getColumns();
            seqNo += layout.getColumns();
            if (verticalGap > 0 && i < rows - 1)
                for (int j = 0; j < layout.getColumns(); j++) {
                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(verticalGap);
                    cell.setBorderWidth(0);
                    table.addCell(cell);
                }
        }
        table.setWidthPercentage(100f);
        document.add(table);
        if (!layout.getFooter().isEmpty()) {
            String footer = PageProcessor.computeTitle(layout.getFooter(), fileName, now, assets.size(), pageNo,
                    pages, collection, meta);
            Paragraph p = new Paragraph(footer,
                    FontFactory.getFont(FontFactory.HELVETICA, subtitleSize, Font.NORMAL, BaseColor.DARK_GRAY));
            p.setAlignment(Element.ALIGN_CENTER);
            p.setSpacingBefore(upperWaste / 2 + footerLead);
            document.add(p);
        }
    }
}

From source file:com.bdaum.zoom.email.internal.job.PdfJob.java

License:Open Source License

private void renderCaptions(int pageNo, int seqNo, int pageItem, PdfPTable table, int ni, String caption) {
    if (!caption.isEmpty()) {
        for (int j = 0; j < layout.getColumns(); j++) {
            int a = (pageNo - 1) * imagesPerPage + ni + j;
            PdfPCell cell;// w  w  w  .  j  a  v  a2 s .  c  om
            if (a >= assets.size())
                cell = new PdfPCell();
            else {
                String cc = PageProcessor.computeCaption(caption, Constants.PI_ALL, assets.get(a), collection,
                        seqNo + j + 1, pageItem + j + 1);
                Paragraph p = new Paragraph(cc,
                        FontFactory.getFont(FontFactory.HELVETICA, fontSize, Font.NORMAL, BaseColor.DARK_GRAY));
                p.setSpacingBefore(0);
                cell = new PdfPCell(p);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            }
            cell.setBorderWidth(0);
            table.addCell(cell);
        }
    }
}

From source file:com.bdaum.zoom.ui.internal.dialogs.ExhibitionEditDialog.java

License:Open Source License

private void writeDocument(Document document, File targetFile) {
    boolean frame = detailTabfolder.getSelectionIndex() == 1;
    try (FileOutputStream out = new FileOutputStream(targetFile)) {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();/*from w w w.j  a v  a 2s .com*/
        writer.setPageEvent(new PdfPageEventHelper() {
            int pageNo = 0;
            com.itextpdf.text.Font ffont = new com.itextpdf.text.Font(
                    com.itextpdf.text.Font.FontFamily.HELVETICA, 9, com.itextpdf.text.Font.NORMAL,
                    BaseColor.DARK_GRAY);

            @Override
            public void onEndPage(PdfWriter w, Document d) {
                PdfContentByte cb = w.getDirectContent();
                Phrase footer = new Phrase(String.valueOf(++pageNo), ffont);
                ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer,
                        (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom(), 0);
            }
        });
        String tit = NLS.bind(Messages.ExhibitionEditDialog_exhibition_name, nameField.getText());
        Paragraph p = new Paragraph(tit,
                FontFactory.getFont(FontFactory.HELVETICA, 14, com.itextpdf.text.Font.BOLD, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(8);
        document.add(p);
        String subtitle = NLS.bind(Messages.ExhibitionEditDialog_image_list, Constants.DFDT.format(new Date()),
                frame ? Messages.ExhibitionEditDialog_image_sizes : Messages.ExhibitionEditDialog_frame_sizes);
        p = new Paragraph(subtitle,
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(14);
        document.add(p);
        p = new Paragraph(descriptionField.getText(),
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(10);
        document.add(p);
        p = new Paragraph(infoField.getText(),
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(10);
        document.add(p);
        IDbManager db = Core.getCore().getDbManager();
        List<Wall> walls = current.getWall();
        Wall[] sortedWalls = walls.toArray(new Wall[walls.size()]);
        Arrays.sort(sortedWalls, new Comparator<Wall>() {
            public int compare(Wall o1, Wall o2) {
                return o1.getLocation().compareToIgnoreCase(o2.getLocation());
            }
        });
        for (Wall wall : sortedWalls) {
            p = new Paragraph(wall.getLocation(), FontFactory.getFont(FontFactory.HELVETICA, 12,
                    com.itextpdf.text.Font.BOLD, BaseColor.BLACK));
            p.setAlignment(Element.ALIGN_LEFT);
            p.setSpacingAfter(12);
            document.add(p);
            PdfPTable table = new PdfPTable(7);
            // table.setBorderWidth(1);
            // table.setBorderColor(new Color(224, 224, 224));
            // table.setPadding(5);
            // table.setSpacing(0);
            table.setWidths(new int[] { 8, 33, 13, 13, 20, 13, 20 });
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_No, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_title, Element.ALIGN_LEFT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_xpos, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_height, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_size, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_dpi, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader("", Element.ALIGN_LEFT)); //$NON-NLS-1$
            // table.endHeaders();
            List<ExhibitImpl> exhibits = new ArrayList<ExhibitImpl>();
            for (String exhibitId : wall.getExhibit()) {
                ExhibitImpl exhibit = db.obtainById(ExhibitImpl.class, exhibitId);
                if (exhibit != null)
                    exhibits.add(exhibit);
            }
            Collections.sort(exhibits, new Comparator<ExhibitImpl>() {
                public int compare(ExhibitImpl e1, ExhibitImpl e2) {
                    return ((Exhibit) e1).getX() - ((Exhibit) e2).getX();
                }
            });
            int no = 1;
            for (ExhibitImpl exhibit : exhibits) {
                int tara = computeTara(frame, exhibit);
                table.addCell(createTableCell(String.valueOf(no++), Element.ALIGN_RIGHT));
                table.addCell(createTableCell(exhibit.getTitle(), Element.ALIGN_LEFT));
                af.setMaximumFractionDigits(2);
                af.setMinimumFractionDigits(2);
                String x = af.format((exhibit.getX() - tara) / 1000d);
                table.addCell(createTableCell(NLS.bind("{0} m", x), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                String y = af.format((exhibit.getY() + tara) / 1000d);
                table.addCell(createTableCell(NLS.bind("{0} m", y), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                af.setMaximumFractionDigits(1);
                af.setMinimumFractionDigits(1);
                String h = af.format((exhibit.getHeight() + 2 * tara) / 10d);
                int width = exhibit.getWidth();
                String w = af.format((width + 2 * tara) / 10d);
                table.addCell(createTableCell(NLS.bind("{0} x {1} cm", w, h), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                AssetImpl asset = dbManager.obtainAsset(exhibit.getAsset());
                if (asset != null) {
                    int pixels = asset.getWidth();
                    double dpi = pixels * 25.4d / width;
                    table.addCell(createTableCell(String.valueOf((int) dpi), Element.ALIGN_RIGHT));
                } else
                    table.addCell(""); //$NON-NLS-1$
                table.addCell(createTableCell(exhibit.getSold() ? Messages.ExhibitionEditDialog_sold : "", //$NON-NLS-1$
                        Element.ALIGN_LEFT));
            }
            document.add(table);
        }
        document.close();
    } catch (DocumentException e) {
        UiActivator.getDefault().logError(Messages.ExhibitionEditDialog_internal_error_writing_pdf, e);
    } catch (IOException e) {
        UiActivator.getDefault().logError(Messages.ExhibitionEditDialog_io_error_writing_pdf, e);
    }
}

From source file:com.bdaum.zoom.ui.internal.dialogs.ExhibitionEditDialog.java

License:Open Source License

private static PdfPCell createTableHeader(String header, int alignment) {
    PdfPCell cell = new PdfPCell(new Paragraph(header,
            FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.BOLD, BaseColor.BLACK)));
    cell.setBorderColor(new BaseColor(224, 224, 224));
    cell.setBorderWidth(1);//from  ww  w  . j a v a2s.c om
    cell.setPadding(5);
    cell.setHorizontalAlignment(alignment);
    return cell;
}

From source file:com.bdaum.zoom.ui.internal.dialogs.ExhibitionEditDialog.java

License:Open Source License

private static PdfPCell createTableCell(String value, int alignment) {
    PdfPCell cell = new PdfPCell(new Paragraph(value,
            FontFactory.getFont(FontFactory.HELVETICA, 9, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK)));
    cell.setBorderColor(new BaseColor(224, 224, 224));
    cell.setBorderWidth(1);//from w  ww .jav a2 s . c  o m
    cell.setPadding(5);
    cell.setHorizontalAlignment(alignment);
    return cell;
}

From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java

License:Open Source License

/**
 * The <code>addImageToPdf</code> method is used to add image to pdf and make it searchable by adding image text in invisible mode
 * w.r.t parameter 'isPdfSearchable' passed.
 * /*from   w w  w.  j av  a  2  s.  c  o m*/
 * @param pdfWriter {@link PdfWriter} writer of pdf in which image has to be added
 * @param htmlUrl {@link HocrPage} corresponding html file for fetching text and coordinates
 * @param imageUrl {@link String} url of image to be added in pdf
 * @param isPdfSearchable true for searchable pdf else otherwise
 * @param widthOfLine
 */
private void addImageToPdf(PdfWriter pdfWriter, HocrPage hocrPage, String imageUrl, boolean isPdfSearchable,
        final int widthOfLine) {
    if (null != pdfWriter && null != imageUrl && imageUrl.length() > 0) {
        try {
            LOGGER.info("Adding image" + imageUrl + " to pdf using iText");
            Image pageImage = Image.getInstance(imageUrl);
            float dotsPerPointX = pageImage.getDpiX() / PDF_RESOLUTION;
            float dotsPerPointY = pageImage.getDpiY() / PDF_RESOLUTION;
            PdfContentByte pdfContentByte = pdfWriter.getDirectContent();

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);

            pageImage.setAbsolutePosition(0, 0);

            // Add image to pdf
            pdfWriter.getDirectContentUnder().addImage(pageImage);
            pdfWriter.getDirectContentUnder().add(pdfContentByte);

            // If pdf is to be made searchable
            if (isPdfSearchable) {
                LOGGER.info("Adding invisible text for image: " + imageUrl);
                float pageImagePixelHeight = pageImage.getHeight();
                Font defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

                // Fetch text and coordinates for image to be added
                Map<String, int[]> textCoordinatesMap = getTextWithCoordinatesMap(hocrPage, widthOfLine);
                Set<String> ketSet = textCoordinatesMap.keySet();

                // Add text at specific location
                for (String key : ketSet) {
                    int[] coordinates = textCoordinatesMap.get(key);
                    float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                    float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;
                    pdfContentByte.beginText();

                    // To make text added as invisible
                    pdfContentByte.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                    pdfContentByte.setLineWidth(Math.round(bboxWidthPt));

                    // Ceil is used so that minimum font of any text is 1
                    // For exception of unbalanced beginText() and endText()
                    if (bboxHeightPt > 0.0) {
                        pdfContentByte.setFontAndSize(defaultFont.getBaseFont(),
                                (float) Math.ceil(bboxHeightPt));
                    } else {
                        pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), 1);
                    }
                    float xCoordinate = (float) (coordinates[0] / dotsPerPointX);
                    float yCoordinate = (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY);
                    pdfContentByte.moveText(xCoordinate, yCoordinate);
                    pdfContentByte.showText(key);
                    pdfContentByte.endText();
                }
            }
            pdfContentByte.closePath();
        } catch (BadElementException badElementException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + badElementException.toString());
        } catch (DocumentException documentException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + documentException.toString());
        } catch (MalformedURLException malformedURLException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + malformedURLException.toString());
        } catch (IOException ioException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + ioException.toString());
        }
    }
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void GeneraPDF(ResultSet Resultados) throws Exception {

    ResultSetMetaData metaData = Resultados.getMetaData();
    Object[] Columnas = new Object[metaData.getColumnCount()];

    String encabezado = "Reportes del Sistema Administrativo" + "\n" + "REGISTROS ACTUALES EN AL BASE DE DATOS"
            + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n";
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));

    Font fuente = new Font(Font.getFamily("ARIAL"), 12, Font.BOLD);

    String choro = "Reporte por fecha de los modulos\n" + "de catalogo" + "\n" + "Systema Administrativo" + "\n"
            + "\n" + "\n" + "\n";

    Image imagen = Image.getInstance(System.getProperty("user.dir") + "/Image/logo.png");
    imagen.setAlignment(Image.TEXTWRAP);

    try {//from  w  ww  . ja  va  2  s  .  c  om
        Paragraph linea = new Paragraph(encabezado, fuente);
        Phrase para = new Phrase(choro);
        Paragraph fecha = new Paragraph(date + "\n" + "\n");

        PdfPTable tabla = new PdfPTable(Columnas.length);
        tabla.setWidthPercentage(100);

        //Document documento = new Document(PageSize.LETTER);
        Document documento = new Document(PageSize.A4.rotate(), 50, 50, 100, 72);
        File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
        if (!Dir.exists()) {
            Dir.mkdirs();
        }

        String file = System.getProperty("user.dir") + "/Reportes/" + metaData.getTableName(1) + " " + date
                + ".pdf";

        PdfWriter.getInstance(documento, new FileOutputStream(file));

        documento.open();
        documento.add(imagen);
        documento.add(linea);
        documento.add(para);
        documento.add(fecha);

        for (int x = 0; x < Columnas.length; x++) {
            PdfPCell Celda = new PdfPCell(new Paragraph(metaData.getColumnName(x + 1),
                    FontFactory.getFont("arial", 9, Font.BOLD, BaseColor.RED)));
            Celda.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabla.addCell(Celda);
        }

        while (Resultados.next()) {
            for (int x = 0; x < Columnas.length; x++) {
                //if(Resultados.getObject(x+1).getClass().getSimpleName().equals("Integer"))
                PdfPCell Celda = new PdfPCell(new Paragraph(String.valueOf(Resultados.getObject(x + 1)),
                        FontFactory.getFont("arial", 9, BaseColor.BLACK)));
                Celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabla.addCell(Celda);
            }
        }

        documento.add(tabla);
        documento.close();
    } catch (DocumentException e) {
        Log.SaveLog(e.toString());
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        Log.SaveLog(e.toString());
        JOptionPane.showMessageDialog(null, e.getMessage(), "error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.miraflorescarwash.controller.PdfController.java

private void crearPdfLavadasPendientes(Document doc, List<Lavada> lavadas) {
    Paragraph parrafo;/*from w  ww  .ja  v  a  2 s  .  co m*/
    PdfPTable tabla;
    String txt;
    PdfPCell cell;
    Phrase frase;
    String fuente;
    int i;
    JFreeChart chart;
    int w, h;
    int pos;
    pos = 0;
    w = h = 500;

    fuente = "arial";
    if (lavadas.isEmpty()) {
        return;
    }
    try {
        //

        // Se abre el documento.
        doc.open();

        txt = "Miraflores Car Wash";
        parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 10, Font.BOLD, BaseColor.BLACK));
        parrafo.setAlignment(Element.ALIGN_LEFT);
        doc.add(parrafo);

        txt = "Lavadas Pendientes";
        parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 30, Font.BOLD, BaseColor.BLACK));
        parrafo.setAlignment(Element.ALIGN_CENTER);

        doc.add(parrafo);
        LineSeparator ls = new LineSeparator();
        doc.add(new Chunk(ls));

        tabla = new PdfPTable(3);

        frase = new Phrase("Id", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE));
        cell = new PdfPCell(frase);
        cell.setBackgroundColor(BaseColor.RED);
        tabla.addCell(cell);

        frase = new Phrase("Fecha", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE));
        cell = new PdfPCell(frase);
        cell.setBackgroundColor(BaseColor.RED);
        tabla.addCell(cell);

        frase = new Phrase("Placa de Carro", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE));
        cell = new PdfPCell(frase);
        cell.setBackgroundColor(BaseColor.RED);
        tabla.addCell(cell);

        frase = new Phrase("Modelo de Carro", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE));
        cell = new PdfPCell(frase);
        cell.setBackgroundColor(BaseColor.RED);
        tabla.addCell(cell);

        frase = new Phrase("Cliente", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE));
        cell = new PdfPCell(frase);
        cell.setBackgroundColor(BaseColor.RED);
        tabla.addCell(cell);

        i = 1;

        for (Lavada lavada : lavadas) {

            if (i % 2 == 0) {
                cell = new PdfPCell();
                cell.setBackgroundColor(new BaseColor(244, 119, 119));

                frase = new Phrase(lavada.getId() + "");
                cell.setPhrase(frase);
                tabla.addCell(cell);

                frase = new Phrase(lavada.getFechaLavado() + "");
                cell.setPhrase(frase);
                tabla.addCell(cell);

                frase = new Phrase(lavada.getCarro().getPlaca());
                cell.setPhrase(frase);
                tabla.addCell(cell);

                frase = new Phrase(lavada.getCarro().getModelo().getNombre());
                cell.setPhrase(frase);
                tabla.addCell(cell);

                frase = new Phrase(lavada.getCarro().getCliente().getApellidos() + ", "
                        + lavada.getCarro().getCliente().getNombres());
                cell.setPhrase(frase);
                tabla.addCell(cell);

            } else {
                tabla.addCell(lavada.getId() + "");
                tabla.addCell(lavada.getFechaLavado() + "");
                tabla.addCell(lavada.getCarro().getPlaca());
                tabla.addCell(lavada.getCarro().getModelo().getNombre());
                tabla.addCell(lavada.getCarro().getCliente().getApellidos() + ", "
                        + lavada.getCarro().getCliente().getNombres());
            }
            i++;
        }
        doc.add(tabla);

        doc.close();
    } catch (DocumentException ex) {

    }
}