Example usage for com.lowagie.text Rectangle getHeight

List of usage examples for com.lowagie.text Rectangle getHeight

Introduction

In this page you can find the example usage for com.lowagie.text Rectangle getHeight.

Prototype

public float getHeight() 

Source Link

Document

Returns the height of the rectangle.

Usage

From source file:org.silverpeas.core.util.PdfUtil.java

License:Open Source License

/**
 * Gets some document info from a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @return a {@link DocumentInfo} instance.
 */// ww  w.  j ava2  s  .co m
public static DocumentInfo getDocumentInfo(File pdfSource) {
    if (pdfSource == null || !pdfSource.isFile()) {
        throw new SilverpeasRuntimeException(PDF_FILE_ERROR_MSG);
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG);
    }
    PdfReader reader = null;
    try (final InputStream pdfSourceIS = FileUtils.openInputStream(pdfSource)) {
        reader = new PdfReader(pdfSourceIS);
        final DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setNbPages(reader.getNumberOfPages());
        for (int i = 1; i <= documentInfo.getNbPages(); i++) {
            final Rectangle rectangle = reader.getPageSize(i);
            final int maxWidth = Math.round(rectangle.getWidth());
            final int maxHeight = Math.round(rectangle.getHeight());
            if (maxWidth > documentInfo.getMaxWidth()) {
                documentInfo.setMaxWidth(maxWidth);
            }
            if (maxHeight > documentInfo.getMaxHeight()) {
                documentInfo.setMaxHeight(maxHeight);
            }
        }
        return documentInfo;
    } catch (Exception e) {
        SilverLogger.getLogger(PdfUtil.class).error(e);
        throw new SilverpeasRuntimeException("A problem has occurred during the reading of a pdf file", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.silverpeas.core.util.PdfUtil.java

License:Open Source License

/**
 * Add a image under or over content on each page of a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @param imageToAdd the image file/*from w  ww .  j ava 2s. co m*/
 * @param pdfDestination the destination pdf file, with the image under or over content
 * @param isBackground indicates if image is addes under or over the content of the pdf source
 * file
 */
private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination,
        final boolean isBackground) {

    // Verify given arguments
    if (imageToAdd == null || !imageToAdd.isFile()) {
        throw new SilverpeasRuntimeException("The image file doesn't exist");
    } else if (!FileUtil.isImage(imageToAdd.getPath())) {
        throw new SilverpeasRuntimeException("The picture to add is not an image file");
    }

    PdfReader reader = null;
    try {

        // Get a reader of PDF content
        reader = new PdfReader(pdfSource);

        // Obtain the total number of pages
        int pdfNbPages = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, pdfDestination);

        // Load the image
        Image image = Image.getInstance(imageToAdd.getPath());
        float imageWidth = image.getWidth();
        float imageHeigth = image.getHeight();

        // Adding the image on each page of the PDF
        for (int i = 1; i <= pdfNbPages; i++) {

            // Page sizes
            Rectangle rectangle = reader.getPageSize(i);

            // Compute the scale of the image
            float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100));
            image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100)));

            // Setting the image position for the current page
            image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()),
                    computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight()));

            // Adding image
            PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i)
                    : stamper.getOverContent(i);
            imageContainer.addImage(image);
        }

        // End of the treatment : closing the stamper
        stamper.close();

    } catch (Exception e) {
        SilverLogger.getLogger(PdfUtil.class).error(e);
        throw new SilverpeasRuntimeException(
                "A problem has occurred during the adding of an image into a pdf file", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.silverpeas.util.PdfUtil.java

License:Open Source License

/**
 * Add a image under or over content on each page of a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @param imageToAdd the image file/*from   w w  w .jav a  2s  .  c  om*/
 * @param pdfDestination the destination pdf file, with the image under or over content
 * @param isBackground indicates if image is addes under or over the content of the pdf source
 * file
 */
private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination,
        final boolean isBackground) {

    // Verify given arguments
    if (imageToAdd == null || !imageToAdd.isFile()) {
        throw new RuntimeException("The image file doesn't exist");
    } else if (!FileUtil.isImage(imageToAdd.getPath())) {
        throw new RuntimeException("The picture to add is not an image file");
    }

    PdfReader reader = null;
    try {

        // Get a reader of PDF content
        reader = new PdfReader(pdfSource);

        // Obtain the total number of pages
        int pdfNbPages = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, pdfDestination);

        // Load the image
        Image image = Image.getInstance(imageToAdd.getPath());
        float imageWidth = image.getWidth();
        float imageHeigth = image.getHeight();

        // Adding the image on each page of the PDF
        for (int i = 1; i <= pdfNbPages; i++) {

            // Page sizes
            Rectangle rectangle = reader.getPageSize(i);

            // Compute the scale of the image
            float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100));
            image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100)));

            // Setting the image position for the current page
            image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()),
                    computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight()));

            // Adding image
            PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i)
                    : stamper.getOverContent(i);
            imageContainer.addImage(image);
        }

        // End of the treatment : closing the stamper
        stamper.close();

    } catch (Exception e) {
        SilverTrace.error("util", "PdfUtil.stamp", "EX_ERROR_PDF_ADD_WATERWARK", e);
        throw new RuntimeException("A problem has occured during the adding of an image into a pdf file", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.sonar.report.pdf.DefaultPDFReporter.java

License:Open Source License

@Override
protected void printFrontPage(Document frontPageDocument, PdfWriter frontPageWriter)
        throws org.dom4j.DocumentException, ReportException {
    try {/*from   w ww .  j  a va2 s. c om*/
        URL largeLogo;
        if (super.getConfigProperty("front.page.logo").startsWith("http://")) {
            largeLogo = new URL(super.getConfigProperty("front.page.logo"));
        } else {
            largeLogo = this.getClass().getClassLoader()
                    .getResource(super.getConfigProperty("front.page.logo"));
        }
        Image logoImage = Image.getInstance(largeLogo);
        Rectangle pageSize = frontPageDocument.getPageSize();
        float positionX = pageSize.getWidth() / 2f - logoImage.getWidth() / 2f;
        logoImage.setAbsolutePosition(positionX, pageSize.getHeight() - logoImage.getHeight() - 100);
        frontPageDocument.add(logoImage);

        PdfPTable title = new PdfPTable(1);
        title.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        title.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        String projectRow = super.getTextProperty("general.project") + ": " + super.getProject().getName();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dateRow = df.format(super.getProject().getMeasures().getDate());
        String descriptionRow = super.getProject().getDescription();

        title.addCell(new Phrase(projectRow, Style.FRONTPAGE_FONT_1));
        title.addCell(new Phrase(descriptionRow, Style.FRONTPAGE_FONT_2));
        title.addCell(new Phrase(dateRow, Style.FRONTPAGE_FONT_3));
        title.setTotalWidth(
                pageSize.getWidth() - frontPageDocument.leftMargin() - frontPageDocument.rightMargin());
        title.writeSelectedRows(0, -1, frontPageDocument.leftMargin(),
                pageSize.getHeight() - logoImage.getHeight() - 150, frontPageWriter.getDirectContent());

    } catch (IOException e) {
        e.printStackTrace();
    } catch (BadElementException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:org.sonar.report.pdf.Header.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {/*w ww  . java2s  .co  m*/
        Image logoImage = Image.getInstance(logo);
        Rectangle page = document.getPageSize();
        PdfPTable head = new PdfPTable(4);
        head.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        head.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
        head.addCell(logoImage);
        Phrase projectName = new Phrase(project.getName(),
                FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY));
        Phrase phrase = new Phrase("Sonar PDF Report",
                FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY));
        head.getDefaultCell().setColspan(2);
        head.addCell(phrase);
        head.getDefaultCell().setColspan(1);
        head.addCell(projectName);
        head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - 20, writer.getDirectContent());
        head.setSpacingAfter(10);
    } catch (BadElementException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.sonarqube.report.extendedpdf.ExtendedHeader.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    String pageTemplate = "/templates/page.pdf";
    try {//ww w  .  jav a2  s . c  o m
        PdfContentByte cb = writer.getDirectContentUnder();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(pageTemplate));
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        cb.addTemplate(page, 0, 0);

        Font font = FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY);
        Rectangle pageSize = document.getPageSize();
        PdfPTable head = new PdfPTable(1);
        head.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        head.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
        head.getDefaultCell().setBorder(0);
        Phrase projectName = new Phrase(project.getName(), font);
        head.addCell(projectName);
        head.setTotalWidth(pageSize.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(), pageSize.getHeight() - 15,
                writer.getDirectContent());
        head.setSpacingAfter(10);

        PdfPTable foot = new PdfPTable(1);
        foot.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        foot.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        foot.getDefaultCell().setBorder(0);
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase(df.format(project.getMeasures().getDate()), font);
        foot.addCell(projectAnalysisDate);
        foot.setTotalWidth(pageSize.getWidth() - document.leftMargin() - document.rightMargin());
        foot.writeSelectedRows(0, -1, document.leftMargin(), 20, writer.getDirectContent());
        foot.setSpacingBefore(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + pageTemplate);
        e.printStackTrace();
    }
}

From source file:org.sonarqube.report.extendedpdf.OverviewPDFReporter.java

License:Open Source License

protected void printFrontPage(Document frontPageDocument, PdfWriter frontPageWriter)
        throws org.dom4j.DocumentException, ReportException {
    String frontPageTemplate = "/templates/frontpage.pdf";
    try {//from www  .jav  a  2 s  .com
        PdfContentByte cb = frontPageWriter.getDirectContent();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(frontPageTemplate));
        PdfImportedPage page = frontPageWriter.getImportedPage(reader, 1);
        frontPageDocument.newPage();
        cb.addTemplate(page, 0, 0);

        Project project = getProject();

        Rectangle pageSize = frontPageDocument.getPageSize();
        PdfPTable projectInfo = new PdfPTable(1);
        projectInfo.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        projectInfo.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        projectInfo.getDefaultCell().setBorder(Rectangle.BOTTOM);
        projectInfo.getDefaultCell().setPaddingBottom(10);
        projectInfo.getDefaultCell().setBorderColor(Color.GRAY);
        Font font = FontFactory.getFont(FontFactory.COURIER, 18, Font.NORMAL, Color.LIGHT_GRAY);

        Phrase projectName = new Phrase("Project: " + project.getName(), font);
        projectInfo.addCell(projectName);

        Phrase projectVersion = new Phrase("Version: " + project.getMeasures().getVersion(), font);
        projectInfo.addCell(projectVersion);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase("Analysis Date: " + df.format(project.getMeasures().getDate()),
                font);
        projectInfo.addCell(projectAnalysisDate);

        projectInfo.setTotalWidth(
                pageSize.getWidth() - frontPageDocument.leftMargin() * 2 - frontPageDocument.rightMargin() * 2);
        projectInfo.writeSelectedRows(0, -1, frontPageDocument.leftMargin(), pageSize.getHeight() - 575,
                frontPageWriter.getDirectContent());
        projectInfo.setSpacingAfter(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + frontPageTemplate);
        e.printStackTrace();
    }
}

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * Genera un nuevo pdf con la imagen firmada y el pie de firma.
 * @param url Url desde la que se puede descargar el documeto
 *///from  w  w w  .  j a  va2s. com
public void generarImagenPdf(byte[] input, String texto, String url, String textoQR, String codFirma,
        OutputStream out) throws ExcepcionErrorInterno {
    try {
        // Nuevo Documento PDF
        Document document = new Document();

        // Obtenemos el tamao de la pgina
        Rectangle pageSize = document.getPageSize();

        PdfWriter.getInstance(document, out);
        document.open();
        addContent(texto, url, textoQR, codFirma, document, pageSize, true, false);

        // Aadimos imagen original
        Image imagen = Image.getInstance(input);
        imagen.setBorder(10);
        imagen.scaleToFit(500, 500);
        imagen.setAbsolutePosition(50, pageSize.getHeight() - 400);
        document.add(imagen);

        // Cerramos el documento
        document.close();

    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }

}

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * @param texto//from w  w w. j  a v a  2  s .c  o  m
 *            Texto a colocar
 * @param textoQR
 *            Imagen QR a colocar
 * @param codFirma
 *            Cdigo de Firma a generar.
 * @param url Url del servicio de verificacin desde donde se puede descargar el documento.
 * @param document
 *            Documeto destino
 * @param pageSize
 *            Tamao de la pgina
 * @return 
 * @throws BadElementException
 * @throws MalformedURLException
 * @throws IOException
 * @throws DocumentException
 * @throws ExcepcionErrorInterno
 */
private static float addContent(String texto, String url, String textoQR, String codFirma, Document document,
        Rectangle pageSize, boolean completo, boolean isSellado) throws BadElementException,
        MalformedURLException, IOException, DocumentException, ExcepcionErrorInterno {

    Image imagenCabezera = null;
    float widthCabecera = 0;
    float heightCabecera = 0;
    if (!isSellado) {
        // Recuperamos la imagen de cabecera
        imagenCabezera = Image.getInstance(QRCodeUtil.class.getResource(IMAGE_CABECERA));
        // Colocamos la imagen en la zona superior de la pgina
        imagenCabezera.setAbsolutePosition(0, pageSize.getHeight() - imagenCabezera.getHeight());
        heightCabecera = imagenCabezera.getHeight();
        widthCabecera = imagenCabezera.getWidth();
    }

    // Recuperamos el pie de firma
    Image imagenQR = Image.getInstance(QRCodeUtil.getInstance().generate(texto, url, textoQR, codFirma));

    float rescalado = pageSize.getWidth() / (widthCabecera + document.leftMargin() + document.rightMargin());
    float sizeCabecera = 0;
    if (rescalado < 1f && !isSellado) {
        // Requiere rescalado, la imagen es mayor que la pgina.
        imagenCabezera.scalePercent(rescalado * 100);
        sizeCabecera = rescalado * imagenCabezera.getHeight();
    }

    float sizeCabecerayPie = HEIGHT_QR_CODE_PDF + sizeCabecera + document.bottomMargin() + document.topMargin()
            + SPACE_SEPARACION;
    // float escaleQR = HEIGHT_QR_CODE_PDF / (imagenQR.getHeight() + 5);
    float escaleQR = (pageSize.getWidth() - document.leftMargin() - document.rightMargin())
            / (imagenQR.getWidth() + 6);

    // imagen.setSpacingAfter(120);
    if (!isSellado) {
        document.add(imagenCabezera);
    }
    // Aadimos una caja de texto si estamos mostrando el contenido del
    // fichero firmado.
    if (completo) {
        // Aadimos el espacio ocupado por la imagen
        Paragraph p = new Paragraph("");
        p.setSpacingAfter(heightCabecera * rescalado);
        document.add(p);

        // Aadimos una tabla con borde donde colocar el documento.
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorderWidth(10);
        PdfPCell celda = new PdfPCell();
        celda.setFixedHeight(pageSize.getHeight() - sizeCabecerayPie);
        table.addCell(celda);
        table.setSpacingAfter(SPACE_SEPARACION);
        document.add(table);
    }

    if (completo) {
        // La imagen la colocamos justo debajo
        imagenQR.setAbsolutePosition(document.leftMargin(),
                escaleQR * HEIGHT_QR_CODE_PDF - SPACE_SEPARACION * 2);
    } else {
        imagenQR.setAbsolutePosition(document.leftMargin(), pageSize.getHeight() - sizeCabecerayPie);
    }
    imagenQR.scalePercent(escaleQR * 100);
    document.add(imagenQR);

    return sizeCabecerayPie;
}

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * Genera un justificante de firma de un fichero pdf de entrada.
 * //  w  w w  . j  a v  a2s. c  o  m
 * @param input
 *            Fichero pdf de entrada
 * @param texto
 * @param textoQR
 * @param codFirma
 * @param out
 * @throws ExcepcionErrorInterno
 */
public void firmarPDF(InputStream input, String texto, String texto2Line, String textoQR, String codFirma,
        OutputStream out) throws ExcepcionErrorInterno {
    // leemos el pdf utilizando iText.
    try {
        // Recuperamos el documento original
        PdfReader reader = new PdfReader(input);

        // Obtenemos el tamao de la pgina
        Rectangle pageSize = reader.getPageSize(1);

        // Creamos un nuevo documento del mismo tamao que el original
        Document document = new Document(pageSize);

        // creo una instancia para escritura en el documento
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();

        // insertamos la portada del documento que estamos firmando.
        float escala = (pageSize.getHeight() - 350) / pageSize.getHeight();

        // Aadimos al documento la imagen de cabecera y de pie
        addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, false);

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage portada = writer.getImportedPage(reader, 1);
        cb.setRGBColorStroke(0xCC, 0xCC, 0xCC);
        cb.transform(AffineTransform.getTranslateInstance(document.leftMargin(), 210));
        cb.transform(AffineTransform.getScaleInstance(escala, escala));
        cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy);
        document.close();
        out.close();
    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }
}