Example usage for com.itextpdf.text Image scaleToFit

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

Introduction

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

Prototype

public void scaleToFit(final float fitWidth, final float fitHeight) 

Source Link

Document

Scales the image so that it fits a certain width and height.

Usage

From source file:com.bicitools.dao.RutasDAODecorador.java

@Override
public RespuestaJson exportarReporteMetricasUsuario(String usuario, String fechaIni, String fechaFin,
        String archivo) {//from   ww  w  .  j a va  2  s  . co m
    RespuestaJson res = new RespuestaJson();
    res = getRutasDAO().exportarReporteMetricasUsuario(usuario, fechaIni, fechaFin, archivo);

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date fechaUno, fechaDos;
    try {
        fechaUno = formatter.parse(fechaIni);
        fechaDos = formatter.parse(fechaFin);
    } catch (ParseException ex) {
        String inputStr = "01-01-1900 00:00:00";
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        try {
            fechaUno = dateFormat.parse(inputStr);
        } catch (Exception miex) {
            fechaUno = new java.util.Date();
        }
        fechaDos = new java.util.Date();
    }

    Query query = em.createNamedQuery("Ruta.findMetricasByUsuario");
    query.setParameter("usuario", usuario);
    query.setParameter("fechaIni", fechaUno, TemporalType.TIMESTAMP);
    query.setParameter("fechaFin", fechaDos, TemporalType.TIMESTAMP);
    List<Object[]> qresul = query.getResultList();

    if (qresul.size() > 0) {

        try {

            // Se crea el documento
            Document documento = new Document();

            // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
            FileOutputStream ficheroPdf = null;
            //ficheroPdf = new FileOutputStream("/Users/jhony/Documents/Uni Andes/Fabricas/Bicitools/bicitools/reporte.pdf");

            DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_HHmmss");
            Date fechaReporte = new Date();

            ficheroPdf = new FileOutputStream(
                    archivo + "/Reporte_" + usuario + "_" + dateFormat.format(fechaReporte) + ".pdf");

            // Se asocia el documento al OutputStream y se indica que el espaciado entre
            // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
            PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

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

            documento.add(new Paragraph("Reporte de Actividad para " + usuario));
            documento.add(new Paragraph(" "));
            /*documento.add(new Paragraph("Este es el segundo y tiene una fuente rara",
             FontFactory.getFont("arial", // fuente
             22, // tamao
             Font.ITALIC, // estilo
             BaseColor.CYAN)));             // color
             */

            documento.add(new Paragraph("Fecha Inicial: " + fechaUno));
            documento.add(new Paragraph("Fecha Final: " + fechaDos));

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));
            PdfPTable tabla = new PdfPTable(3);
            tabla.addCell("Fecha");
            tabla.addCell("Tiempo");
            tabla.addCell("Distancia");

            int distanciaTotal = 0, tiempoTotal = 0;
            ArrayList<DatosMetricasReportesJson> rta = new ArrayList<>();
            ArrayList<DatosMetricasUsuarioJson> lista = new ArrayList<>();
            DatosMetricasReportesJson salida = new DatosMetricasReportesJson();
            MetricasUsuario total = new MetricasUsuario();
            lista.clear();

            for (Object[] object : qresul) {
                Date fechaSalida = (Date) object[2];

                // Create an instance of SimpleDateFormat used for formatting
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                String reportDate = df.format(fechaSalida);

                tabla.addCell(reportDate);
                tabla.addCell((String) object[1]);
                tabla.addCell((String) object[0]);

                distanciaTotal += Integer.parseInt((String) object[0]);
                tiempoTotal += Integer.parseInt((String) object[1]);

            }

            documento.add(tabla);

            documento.add(new Paragraph(" "));

            documento.add(new Paragraph("Tiempo Total: " + tiempoTotal));
            documento.add(new Paragraph("Distancia Total: " + distanciaTotal));

            documento.add(new Paragraph(" "));
            try {
                Image foto = Image.getInstance(
                        "http://1.bp.blogspot.com/-fV-ThFg9bN0/UCr4VMFrJ-I/AAAAAAAAEYQ/-_vIDIYDLz8/s1600/dibujo-pintar-doki-bicicleta.jpg");
                foto.scaleToFit(100, 100);
                foto.setAlignment(Chunk.ALIGN_CENTER);
                documento.add(foto);
            } catch (Exception e) {
                e.printStackTrace();
            }
            res = ConstruyeRespuesta.construyeRespuestaOk();

            documento.close();
            //res.setDatos(rta);

        } catch (DocumentException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else {
        res = ConstruyeRespuesta.construyeRespuestaFalla("no hay datos " + qresul.size());
    }

    return res;
}

From source file:com.deadormi.servlet.CreaPdfServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w . j a  v  a2 s  . co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String url = request.getQueryString();
    Integer gruppo_id = Integer.parseInt(url.substring(url.indexOf("=") + 1, url.length()));

    List<Utente> iscritti = null;
    List<Post> posts = null;
    Gruppo gruppo = null;
    Utente utente = null;
    String imageUrl = null;
    String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

    try {
        iscritti = UtenteController.getUserByGroupId(request, gruppo_id);
        gruppo = GruppoController.getGruppoById(request, gruppo_id);
    } catch (SQLException ex) {
        log.error(ex);
    }

    // step 1: creation of a document-object
    Document document = new Document();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();

        String incipit = "Report del " + CurrentDate.getCurrentDate() + "\n";
        Paragraph pIncipit = new Paragraph(incipit,
                FontFactory.getFont(FontFactory.HELVETICA, 14, BaseColor.BLACK));
        pIncipit.setAlignment(Element.ALIGN_CENTER);
        pIncipit.setSpacingAfter(10);
        document.add(pIncipit);

        String title = "Gruppo " + gruppo.getNome();
        Paragraph pTitle = new Paragraph(title, FontFactory.getFont(FontFactory.HELVETICA, 18, BaseColor.BLUE));
        pTitle.setAlignment(Element.ALIGN_CENTER);
        pTitle.setSpacingAfter(40);
        document.add(pTitle);

        PdfPCell labelNome = new PdfPCell(new Paragraph("Nome utente"));
        PdfPCell labelNumPost = new PdfPCell(new Paragraph("Num. post"));
        PdfPCell labelData = new PdfPCell(new Paragraph("Data ultimo post"));
        labelNome.setBorder(Rectangle.NO_BORDER);
        labelNumPost.setBorder(Rectangle.NO_BORDER);
        labelData.setBorder(Rectangle.NO_BORDER);

        for (int i = 0; i < iscritti.size(); i++) {
            utente = iscritti.get(i);
            try {
                posts = PostController.getPostByGruppoIdAndUserId(request, gruppo_id, utente.getId_utente());
            } catch (SQLException ex) {
                Logger.getLogger(CreaPdfServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (utente.getNome_avatar() != null) {
                imageUrl = baseUrl + request.getContextPath() + AVATAR_RESOURCE_PATH + "/"
                        + utente.getId_utente() + "_" + utente.getNome_avatar();
                ;
            } else {
                imageUrl = baseUrl + request.getContextPath() + "/res/images/user_avatar.png";
            }
            Image image = Image.getInstance(new URL(imageUrl));
            image.scaleToFit(50, 50);

            PdfPTable table = new PdfPTable(3);

            PdfPCell cellAvatar = new PdfPCell(image);
            cellAvatar.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellAvatar.setBorder(Rectangle.NO_BORDER);
            cellAvatar.setRowspan(3);

            PdfPCell cellNome = new PdfPCell(new Paragraph(utente.getUsername() + ""));
            cellNome.setBorder(Rectangle.NO_BORDER);

            PdfPCell cellNumPost = new PdfPCell(new Paragraph(posts.size() + ""));
            cellNumPost.setBorder(Rectangle.NO_BORDER);

            //L'ultimo  sempre il piu recente siccome la query  ORDER BY data_creazione
            PdfPCell cellData;
            if (posts.size() != 0) {
                cellData = new PdfPCell(new Paragraph(posts.get(posts.size() - 1).getData_creazione()));
            } else {
                cellData = new PdfPCell(new Paragraph("N/A"));

            }
            cellData.setBorder(Rectangle.NO_BORDER);

            PdfPCell cellVoidBottom = new PdfPCell(new Paragraph(" "));
            cellVoidBottom.setBorder(Rectangle.BOTTOM);
            cellVoidBottom.setPaddingBottom(10);
            cellVoidBottom.setColspan(3);

            PdfPCell cellVoidTop = new PdfPCell(new Paragraph(" "));
            cellVoidTop.setBorder(Rectangle.NO_BORDER);
            cellVoidTop.setPaddingTop(10);
            cellVoidTop.setColspan(3);

            table.addCell(cellVoidTop);
            table.addCell(cellAvatar);
            table.addCell(labelNome);
            table.addCell(cellNome);
            table.addCell(labelNumPost);
            table.addCell(cellNumPost);
            table.addCell(labelData);
            table.addCell(cellData);
            table.addCell(cellVoidBottom);

            document.add(table);

        }

        document.close();
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "inline; filename=ahahah.pdf");
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    } catch (DocumentException ex) {
        Logger.getLogger(CreaPdfServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.dexter.fms.mbean.ReportsMBean.java

@SuppressWarnings("unchecked")
public void createPDF(int type, String filename, int pageType) {
    try {/*from ww  w.ja va  2 s  .c om*/
        FacesContext context = FacesContext.getCurrentInstance();
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FMS");
        document.addCreationDate();
        document.addCreator("FMS");
        document.addSubject("Report");
        document.addTitle(getReport_title());

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put("partner", dashBean.getUser().getPartner());
        GeneralDAO gDAO = new GeneralDAO();
        Object pSettingsObj = gDAO.search("PartnerSetting", params);
        PartnerSetting setting = null;
        if (pSettingsObj != null) {
            Vector<PartnerSetting> pSettingsList = (Vector<PartnerSetting>) pSettingsObj;
            for (PartnerSetting e : pSettingsList) {
                setting = e;
            }
        }
        gDAO.destroy();

        PdfPCell c = null;
        if (setting != null && setting.getLogo() != null) {
            Image logoImg = Image.getInstance(setting.getLogo());
            logoImg.scaleToFit(212, 51);
            c = new PdfPCell(logoImg);
        } else
            c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(getReport_title(), font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (getReport_start_dt() != null && getReport_end_dt() != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("From " + getReport_start_dt() + " to " + getReport_end_dt(), font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = exportPDFTable(type);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();
        String fileName = filename + ".pdf";

        writeFileToResponse(context.getExternalContext(), baos, fileName, "application/pdf");

        context.responseComplete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

private void generateLyfeCycleState(Paragraph preface, ResourceBundle bundle) {
    // Table title
    preface.add(new Paragraph(bundle.getString("lifecycle") + " : " + lifeCycleState, BOLD_12));
    addEmptyLine(preface, 1);/* ww  w  .  j  a va2  s .c  o m*/

    PdfPTable lifeCycleTable = new PdfPTable(5);
    lifeCycleTable.setWidthPercentage(100f);
    PdfPCell cell;
    for (Activity activity : workflow.getActivities()) {

        boolean headerRendered = false;

        for (Task task : activity.getTasks()) {

            if (task.isApproved() || task.isRejected()) {

                if (!headerRendered) {
                    // Table head
                    cell = new PdfPCell(new Phrase(activity.getLifeCycleState(), BOLD_12));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    cell.setColspan(5);
                    lifeCycleTable.addCell(cell);

                    cell = new PdfPCell(new Phrase(bundle.getString("lifecycle.task"), BOLD_12));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    lifeCycleTable.addCell(cell);

                    cell = new PdfPCell(new Phrase(bundle.getString("lifecycle.date"), BOLD_12));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    lifeCycleTable.addCell(cell);

                    cell = new PdfPCell(new Phrase(bundle.getString("lifecycle.author"), BOLD_12));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    lifeCycleTable.addCell(cell);

                    cell = new PdfPCell(new Phrase(bundle.getString("lifecycle.comments"), BOLD_12));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    lifeCycleTable.addCell(cell);

                    cell = new PdfPCell(new Phrase(bundle.getString("lifecycle.signature"), BOLD_12));
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    lifeCycleTable.addCell(cell);

                    headerRendered = true;
                }

                // Table body
                cell = new PdfPCell(new Phrase(task.getTitle(), NORMAL_12));
                lifeCycleTable.addCell(cell);

                SimpleDateFormat simpleFormat = new SimpleDateFormat(bundle.getString("date.format"));
                cell = new PdfPCell(new Phrase(simpleFormat.format(task.getClosureDate()), NORMAL_12));
                lifeCycleTable.addCell(cell);

                cell = new PdfPCell(new Phrase(task.getWorker().getName(), NORMAL_12));
                lifeCycleTable.addCell(cell);

                cell = new PdfPCell(new Phrase(task.getClosureComment(), NORMAL_12));
                lifeCycleTable.addCell(cell);

                if (task.getSignature() != null) {
                    try {
                        byte[] imageByte;
                        int indexOfFirstComma = task.getSignature().indexOf(",");
                        String base64 = task.getSignature().substring(indexOfFirstComma + 1,
                                task.getSignature().length());
                        imageByte = DatatypeConverter.parseBase64Binary(base64);
                        Image image = Image.getInstance(imageByte);
                        image.setCompressionLevel(Image.ORIGINAL_NONE);
                        image.scaleToFit(SIGNATURE_SIZE_W, SIGNATURE_SIZE_H);
                        cell = new PdfPCell(image);
                        lifeCycleTable.addCell(cell);
                    } catch (Exception e) {
                        cell = new PdfPCell(new Phrase(bundle.getString("signature.error"), NORMAL_12));
                        lifeCycleTable.addCell(cell);
                    }

                } else {
                    cell = new PdfPCell(new Phrase(""));
                    lifeCycleTable.addCell(cell);
                }

            }
        }

    }

    preface.add(lifeCycleTable);
}

From source file:com.education.freelancer.MainActivity.java

private void setSignatureStamp(PdfStamper stamper, AcroFields acroFields, String signId) {
    String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/";
    String StoredPath = DIRECTORY + signId + ".png";
    AcroFields.FieldPosition f = acroFields.getFieldPositions(signId).get(0);
    int page = f.page;
    Rectangle rect = f.position;/*from w w  w.  j a v  a  2  s.c  om*/
    File imgFile = new File(StoredPath);
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    if (myBitmap == null) {
        return;
    }
    // myBitmap=getResizedBitmap(myBitmap,160);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    Image img = null;
    try {
        img = Image.getInstance(stream.toByteArray());
        img.scaleToFit(rect.getWidth(), rect.getHeight());
        img.setAbsolutePosition(rect.getLeft(), rect.getBottom());
        stamper.getOverContent(page).addImage(img);
        imgFile.delete();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

License:Open Source License

/**
 * This method creates multi page pdf using IText.
 * /*from w w w .  j av a2 s .c o m*/
 * @param batchInstanceThread {@link BatchInstanceThread}
 * @param pages11 {@link String}
 * @param widthOfPdfPage int
 * @param heightOfPdfPage int
 */
public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final String[] pages11,
        final int widthOfPdfPage, final int heightOfPdfPage) {
    if (pages11 != null && pages11.length > 0) {
        this.pages = new String[pages11.length];
        this.pages = pages11.clone();
        batchInstanceThread.add(new AbstractRunnable() {

            @Override
            public void run() {
                String pdf = pages[pages.length - 1];
                Document document = null;
                PdfWriter writer = null;
                RandomAccessFileOrArray randomAccessArray = null;
                try {
                    document = new Document(PageSize.LETTER, 0, 0, 0, 0);
                    writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
                    document.open();
                    int comps = 1;
                    int totalTiffImages = pages.length - 1;
                    int index = 0;
                    while (index < totalTiffImages) {
                        randomAccessArray = new RandomAccessFileOrArray(pages[index]);
                        comps = TiffImage.getNumberOfPages(randomAccessArray);
                        // Conversion statement
                        for (int tiffPageNumber = 0; tiffPageNumber < comps; ++tiffPageNumber) {
                            Image img = TiffImage.getTiffImage(randomAccessArray, tiffPageNumber + 1);
                            img.scaleToFit(widthOfPdfPage, heightOfPdfPage);
                            document.add(img);
                            document.newPage();
                        }
                        index++;
                    }
                } catch (Exception e) {
                    LOGGER.error("Error while creating pdf using iText" + e.getMessage(), e);
                    //pdf = null;
                } finally {
                    try {
                        if (document != null) {
                            document.close();
                        }
                        if (writer != null) {
                            writer.close();
                        }
                        if (randomAccessArray != null) {
                            randomAccessArray.close();
                        }
                    } catch (Exception e) {
                        LOGGER.error("Error while closing I/O streams for write PDF. " + e.getMessage());
                    }
                }
            }
        });
    }
}

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.
 * //w w w  .j av a  2 s  .  co  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.etest.pdfgenerator.InventoryCasesReportPDF.java

public InventoryCasesReportPDF() {
    Document document = null;/*  w w w . j  a va  2s  . c  o  m*/
    Date date = new Date();

    try {
        document = new Document(PageSize.LETTER, 50, 50, 50, 50);
        PdfWriter.getInstance(document, outputStream);
        document.open();

        Font header = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
        Font content = FontFactory.getFont("Times-Roman", 10);
        Font dateFont = FontFactory.getFont("Times-Roman", 8);

        Image img = null;
        try {
            img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png");
            img.scaleToFit(60, 60);
            img.setAbsolutePosition(500, 700);
        } catch (BadElementException | IOException ex) {
            Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex);
        }
        document.add(img);

        Paragraph reportTitle = new Paragraph();
        reportTitle.setAlignment(Element.ALIGN_CENTER);
        reportTitle.add(new Phrase("Inventory of Cases Report", header));
        document.add(reportTitle);

        Paragraph datePrinted = new Paragraph();
        datePrinted.setSpacingAfter(20f);
        datePrinted.setAlignment(Element.ALIGN_CENTER);
        datePrinted.add(
                new Phrase("Date printed: " + new SimpleDateFormat("dd MMMM yyyy").format(date), dateFont));
        document.add(datePrinted);

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 100, 300, 100, 100 });
        table.setSpacingAfter(5f);

        PdfPCell cellOne = new PdfPCell(new Phrase("Subject"));
        cellOne.setBorder(Rectangle.NO_BORDER);
        cellOne.setPaddingLeft(10);
        cellOne.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        cellOne.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellTwo = new PdfPCell(new Phrase("Descriptive Title"));
        cellTwo.setBorder(Rectangle.NO_BORDER);
        cellTwo.setPaddingLeft(10);
        cellTwo.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        cellTwo.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellThree = new PdfPCell(new Phrase("No. of Cases"));
        cellThree.setBorder(Rectangle.NO_BORDER);
        cellThree.setPaddingLeft(10);
        cellThree.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellThree.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellFour = new PdfPCell(new Phrase("No. of Items"));
        cellFour.setBorder(Rectangle.NO_BORDER);
        cellFour.setPaddingLeft(10);
        cellFour.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellFour.setVerticalAlignment(Element.ALIGN_MIDDLE);

        table.addCell(cellOne);
        table.addCell(cellTwo);
        table.addCell(cellThree);
        table.addCell(cellFour);

        table.getDefaultCell().setBorderWidth(0f);
        document.add(table);

        for (InventoryOfCasesReport report : service.getInventoryOfCases()) {
            PdfPTable table2 = new PdfPTable(4);
            table2.setWidthPercentage(100);
            table2.setWidths(new int[] { 100, 300, 100, 100 });
            table2.setSpacingBefore(3f);
            table2.setSpacingAfter(3f);

            if (!service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()).isEmpty()) {
                if (!service
                        .getListOfCellCaseIdBySyllabusId(
                                service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()))
                        .isEmpty()) {
                    PdfPCell cell1 = new PdfPCell(new Paragraph(report.getSubject(), content));
                    cell1.setBorder(0);
                    cell1.setPaddingLeft(10);
                    cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell2 = new PdfPCell(new Paragraph(report.getDescriptiveTitle(), content));
                    cell2.setBorder(0);
                    cell2.setPaddingLeft(10);
                    cell2.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
                    cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell3 = new PdfPCell(new Paragraph(
                            String.valueOf(service.getTotalCellCasesBySyllabus(
                                    service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()))),
                            content));
                    cell3.setBorder(0);
                    cell3.setPaddingLeft(10);
                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell4 = new PdfPCell(new Paragraph(
                            String.valueOf(service.getTotalCellItemsByCellCaseId(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())))),
                            content));
                    cell4.setBorder(0);
                    cell4.setPaddingLeft(10);
                    cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    table2.addCell(cell1);
                    table2.addCell(cell2);
                    table2.addCell(cell3);
                    table2.addCell(cell4);
                    document.add(table2);
                }
            }
        }
    } catch (DocumentException ex) {
        Logger.getLogger(InventoryItemsReportPDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        document.close();
    }
}

From source file:com.etest.pdfgenerator.InventoryItemsReportPDF.java

public InventoryItemsReportPDF() {
    Document document = null;/*from   www .  j  a v a  2  s.  c o  m*/
    Date date = new Date();

    try {
        document = new Document(PageSize.LETTER.rotate(), 50, 50, 50, 50);
        PdfWriter.getInstance(document, outputStream);
        document.open();

        Font header = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
        Font content = FontFactory.getFont("Times-Roman", 10);
        Font dateFont = FontFactory.getFont("Times-Roman", 8);

        Image img = null;
        try {
            img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png");
            img.scaleToFit(60, 60);
            img.setAbsolutePosition(650, 500);
        } catch (BadElementException | IOException ex) {
            Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex);
        }
        document.add(img);

        Paragraph title1 = new Paragraph();
        title1.setAlignment(Element.ALIGN_CENTER);
        title1.add(new Phrase("Inventory of Items Report"));
        document.add(title1);

        Paragraph title2 = new Paragraph();
        title2.setAlignment(Element.ALIGN_CENTER);
        title2.add(new Phrase("Grouped According to the Revised Bloom's Taxonomy"));
        document.add(title2);

        Paragraph datePrinted = new Paragraph();
        datePrinted.setSpacingAfter(20f);
        datePrinted.setAlignment(Element.ALIGN_CENTER);
        datePrinted
                .add(new Phrase("Date printed: " + new SimpleDateFormat("dd MMMM yyyy").format(date), content));
        document.add(datePrinted);

        PdfPTable table = new PdfPTable(8);
        table.setWidthPercentage(100);
        table.setSpacingAfter(5f);

        for (int i = 0; i < tableHeader.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(tableHeader[i], header));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setPaddingLeft(10);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            if (tableHeader[i].equals("Subject")) {
                cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
            } else {
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            }
            table.addCell(cell);
        }

        document.add(table);

        for (InventoryOfCasesReport report : service.getInventoryOfCases()) {
            PdfPTable table2 = new PdfPTable(8);
            table2.setWidthPercentage(100);
            table2.setSpacingBefore(3f);
            table2.setSpacingAfter(3f);

            if (!service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()).isEmpty()) {
                if (!service
                        .getListOfCellCaseIdBySyllabusId(
                                service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()))
                        .isEmpty()) {
                    PdfPCell cell1 = new PdfPCell(new Paragraph(report.getSubject(), content));
                    cell1.setBorder(0);
                    cell1.setPaddingLeft(10);
                    cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell2 = new PdfPCell(
                            new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())),
                                    tq.getBloomsClassId(BloomsClass.Remember.toString()))), content));
                    cell2.setBorder(0);
                    cell2.setPaddingLeft(10);
                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell3 = new PdfPCell(
                            new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())),
                                    tq.getBloomsClassId(BloomsClass.Understand.toString()))), content));
                    cell3.setBorder(0);
                    cell3.setPaddingLeft(10);
                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell4 = new PdfPCell(
                            new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())),
                                    tq.getBloomsClassId(BloomsClass.Apply.toString()))), content));
                    cell4.setBorder(0);
                    cell4.setPaddingLeft(10);
                    cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell5 = new PdfPCell(
                            new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())),
                                    tq.getBloomsClassId(BloomsClass.Analyze.toString()))), content));
                    cell5.setBorder(0);
                    cell5.setPaddingLeft(10);
                    cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell6 = new PdfPCell(
                            new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())),
                                    tq.getBloomsClassId(BloomsClass.Evaluate.toString()))), content));
                    cell6.setBorder(0);
                    cell6.setPaddingLeft(10);
                    cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell7 = new PdfPCell(
                            new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())),
                                    tq.getBloomsClassId(BloomsClass.Create.toString()))), content));
                    cell7.setBorder(0);
                    cell7.setPaddingLeft(10);
                    cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    PdfPCell cell8 = new PdfPCell(new Paragraph(
                            String.valueOf(service.getTotalCellItemsByCellCaseId(
                                    service.getListOfCellCaseIdBySyllabusId(service
                                            .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())))),
                            content));
                    cell8.setBorder(0);
                    cell8.setPaddingLeft(10);
                    cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    table2.addCell(cell1);
                    table2.addCell(cell2);
                    table2.addCell(cell3);
                    table2.addCell(cell4);
                    table2.addCell(cell5);
                    table2.addCell(cell6);
                    table2.addCell(cell7);
                    table2.addCell(cell8);
                    document.add(table2);
                }
            }
        }
    } catch (DocumentException ex) {
        Logger.getLogger(InventoryItemsReportPDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        document.close();
    }
}

From source file:com.etest.pdfgenerator.ItemAnalysisReportPDF.java

public ItemAnalysisReportPDF(int tqCoverageId) {
    this.tqCoverageId = tqCoverageId;

    Document document = null;/* ww w.  jav  a  2s  .  c  o  m*/
    Date date = new Date();

    try {
        document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter.getInstance(document, outputStream);
        document.open();

        Font header = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
        Font content = FontFactory.getFont("Times-Roman", 10);
        Font dateFont = FontFactory.getFont("Times-Roman", 8);

        Image img = null;
        try {
            img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png");
            img.scaleToFit(60, 60);
            img.setAbsolutePosition(450, 730);
        } catch (BadElementException | IOException ex) {
            Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex);
        }
        document.add(img);

        Paragraph reportTitle = new Paragraph();
        reportTitle.setAlignment(Element.ALIGN_CENTER);
        reportTitle.add(new Phrase("Item Analysis Report", header));
        document.add(reportTitle);

        Paragraph datePrinted = new Paragraph();
        datePrinted.setSpacingAfter(20f);
        datePrinted.setAlignment(Element.ALIGN_CENTER);
        datePrinted.add(
                new Phrase("Date printed: " + new SimpleDateFormat("dd MMMM yyyy").format(date), dateFont));
        document.add(datePrinted);

        Paragraph subject = new Paragraph();
        subject.setAlignment(Element.ALIGN_LEFT);
        subject.add(new Phrase(
                "Subject: " + cs.getCurriculumById(tq.getTQCoverageById(getTqCoverageId()).getCurriculumId())
                        .getSubject().toUpperCase(),
                content));
        document.add(subject);

        Paragraph term = new Paragraph();
        term.setAlignment(Element.ALIGN_LEFT);
        term.add(new Phrase("SY and Semester Administered: 2015-16 2nd Semester", content));
        document.add(term);

        Paragraph type = new Paragraph();
        type.setSpacingAfter(20f);
        type.setAlignment(Element.ALIGN_LEFT);
        type.add(
                new Phrase("Type of Test: " + tq.getTQCoverageById(getTqCoverageId()).getExamTitle(), content));
        document.add(type);

        PdfPTable table = new PdfPTable(5);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 130, 300, 300, 300, 300 });
        //            table.setSpacingAfter(5f);             

        PdfPCell cellOne = new PdfPCell(new Phrase("Item No."));
        cellOne.setBorderWidthTop(1);
        cellOne.setBorderWidthLeft(1);
        cellOne.setBorderWidthRight(1);
        cellOne.setBorderWidthBottom(1);
        cellOne.setPaddingLeft(10);
        cellOne.setPaddingRight(10);
        cellOne.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        cellOne.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellTwo = new PdfPCell(new Phrase("Difficulty"));
        cellTwo.setBorderWidthTop(1);
        cellTwo.setBorderWidthLeft(1);
        cellTwo.setBorderWidthRight(1);
        cellTwo.setBorderWidthBottom(1);
        cellTwo.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellTwo.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellThree = new PdfPCell(new Phrase("Interpretation"));
        cellThree.setBorderWidthTop(1);
        cellThree.setBorderWidthLeft(1);
        cellThree.setBorderWidthRight(1);
        cellThree.setBorderWidthBottom(1);
        cellThree.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellThree.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellFour = new PdfPCell(new Phrase("Discrimination"));
        cellFour.setBorderWidthTop(1);
        cellFour.setBorderWidthLeft(1);
        cellFour.setBorderWidthRight(1);
        cellFour.setBorderWidthBottom(1);
        cellFour.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellFour.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellFive = new PdfPCell(new Phrase("Interpretation"));
        cellFive.setBorderWidthTop(1);
        cellFive.setBorderWidthLeft(1);
        cellFive.setBorderWidthRight(1);
        cellFive.setBorderWidthBottom(1);
        cellFive.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellFive.setVerticalAlignment(Element.ALIGN_MIDDLE);

        table.addCell(cellOne);
        table.addCell(cellTwo);
        table.addCell(cellThree);
        table.addCell(cellFour);
        table.addCell(cellFive);

        table.getDefaultCell().setBorderWidth(0f);
        document.add(table);

        PdfPTable table2 = new PdfPTable(5);
        table2.setWidthPercentage(100);
        table2.setWidths(new int[] { 130, 300, 300, 300, 300 });

        int itemNo = 1;
        for (CellItem ci : cis.getItemAnalysisResult(tqCoverageId)) {
            PdfPCell cell1 = new PdfPCell(new Paragraph(String.valueOf(itemNo), content));
            cell1.setBorderWidthTop(1);
            cell1.setBorderWidthLeft(1);
            cell1.setBorderWidthRight(1);
            cell1.setBorderWidthBottom(1);
            cell1.setPaddingLeft(10);
            cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell2 = new PdfPCell(new Paragraph(String.valueOf(ci.getDifficultIndex()), content));
            cell2.setBorderWidthTop(1);
            cell2.setBorderWidthLeft(1);
            cell2.setBorderWidthRight(1);
            cell2.setBorderWidthBottom(1);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell3 = new PdfPCell(new Paragraph(
                    ItemAnalysisInterpretation.getDifficultyInterpretation(ci.getDifficultIndex()), content));
            cell3.setBorderWidthTop(1);
            cell3.setBorderWidthLeft(1);
            cell3.setBorderWidthRight(1);
            cell3.setBorderWidthBottom(1);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell4 = new PdfPCell(new Paragraph(String.valueOf(ci.getDiscriminationIndex()), content));
            cell4.setBorderWidthTop(1);
            cell4.setBorderWidthLeft(1);
            cell4.setBorderWidthRight(1);
            cell4.setBorderWidthBottom(1);
            cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell5 = new PdfPCell(new Paragraph(
                    ItemAnalysisInterpretation.getDiscriminationInterpretation(ci.getDiscriminationIndex()),
                    content));
            cell5.setBorderWidthTop(1);
            cell5.setBorderWidthLeft(1);
            cell5.setBorderWidthRight(1);
            cell5.setBorderWidthBottom(1);
            cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

            table2.addCell(cell1);
            table2.addCell(cell2);
            table2.addCell(cell3);
            table2.addCell(cell4);
            table2.addCell(cell5);

            itemNo++;
        }
        table.getDefaultCell().setBorderWidth(0f);
        document.add(table2);

    } catch (DocumentException ex) {
        Logger.getLogger(ItemAnalysisReportPDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        document.close();
    }
}