Example usage for com.lowagie.text Document leftMargin

List of usage examples for com.lowagie.text Document leftMargin

Introduction

In this page you can find the example usage for com.lowagie.text Document leftMargin.

Prototype


public float leftMargin() 

Source Link

Document

Returns the left margin.

Usage

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

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {/*from ww w .  java2s .  c  o 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 {/*w  w  w  . j  av a  2 s.co 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 {/*  www  . ja va 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

/**
 * @param texto//from  ww  w.ja va 2  s.  com
 *            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.
 * /*ww  w .  j  a  v  a 2s .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);
    }
}

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

License:Apache License

/**
 * Genera un documento sellado en fichero pdf.
 * /*from   www.  j a va2 s  . c  om*/
 * @param input
 *            Fichero pdf de entrada
 * @param texto
 * @param textoQR
 * @param codFirma
 * @param out
 * @throws ExcepcionErrorInterno
 */
public void firmarPDFSellado(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();

        // Aadimos al documento la imagen de cabecera y de pie
        float altoCabeceraYPie = addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true,
                true);
        altoCabeceraYPie = altoCabeceraYPie + document.topMargin();
        // insertamos la portada del documento que estamos firmando.
        float escala = (pageSize.getHeight() - altoCabeceraYPie) / pageSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage portada = writer.getImportedPage(reader, 1);
        cb.setRGBColorStroke(0xCC, 0xCC, 0xCC);
        cb.transform(AffineTransform.getScaleInstance(escala, escala));
        cb.transform(AffineTransform.getTranslateInstance(document.leftMargin() * 2.5,
                ALTO_ETIQUETA + document.topMargin()));

        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);
    }
}

From source file:org.webguitoolkit.ui.util.export.PDFEvent.java

License:Apache License

public void onEndPage(PdfWriter writer, Document document) {
    TableExportOptions exportOptions = wgtTable.getExportOptions();
    try {//from  w ww. java2 s  .  c  o m
        Rectangle page = document.getPageSize();
        if (exportOptions.isShowDefaultHeader() || StringUtils.isNotEmpty(exportOptions.getHeaderImage())) {
            PdfPTable head = new PdfPTable(3);
            head.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            Paragraph title = new Paragraph(wgtTable.getTitle());
            title.setAlignment(Element.ALIGN_LEFT);
            head.addCell(title);

            Paragraph empty = new Paragraph("");
            head.addCell(empty);
            if (StringUtils.isNotEmpty(exportOptions.getHeaderImage())) {
                try {
                    URL absoluteFileUrl = wgtTable.getPage().getClass()
                            .getResource("/" + exportOptions.getHeaderImage());
                    if (absoluteFileUrl != null) {
                        String path = absoluteFileUrl.getPath();
                        Image jpg = Image.getInstance(path);
                        jpg.scaleAbsoluteHeight(40);
                        jpg.scaleAbsoluteWidth(200);
                        head.addCell(jpg);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    Paragraph noImage = new Paragraph("Image not found!");
                    head.addCell(noImage);
                }
            } else {
                head.addCell(empty);
            }
            head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            head.writeSelectedRows(0, -1, document.leftMargin(),
                    page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());
        }

        if (exportOptions.isShowDefaultFooter() || StringUtils.isNotEmpty(exportOptions.getFooterText())
                || exportOptions.isShowPageNumber()) {
            PdfPTable foot = new PdfPTable(3);
            String footerText = exportOptions.getFooterText() != null ? exportOptions.getFooterText() : "";

            if (!exportOptions.isShowDefaultFooter()) {
                foot.addCell(new Paragraph(footerText));
                foot.addCell(new Paragraph(""));
            } else {
                foot.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                String leftText = "";
                if (StringUtils.isNotEmpty(exportOptions.getFooterText())) {
                    leftText = exportOptions.getFooterText();
                }
                Paragraph left = new Paragraph(leftText);
                left.setAlignment(Element.ALIGN_LEFT);
                foot.addCell(left);

                DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM,
                        TextService.getLocale());
                Date today = new Date();
                String date = df.format(today);
                Paragraph center = new Paragraph(date);
                center.setAlignment(Element.ALIGN_CENTER);
                foot.addCell(center);
            }

            if (exportOptions.isShowPageNumber()) {
                Paragraph right = new Paragraph(
                        TextService.getString("pdf.page@Page:") + " " + writer.getPageNumber());
                right.setAlignment(Element.ALIGN_LEFT);
                foot.addCell(right);

                foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                        writer.getDirectContent());
            } else {
                foot.addCell(new Paragraph(""));
            }
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:questions.tables.AddTableAsHeaderFooter.java

public void onEndPage(PdfWriter writer, Document document) {
    try {//from  w  w w  . j a  v  a2  s  . c o m
        // Header
        headerTable.writeSelectedRows(0, -1, document.leftMargin(),
                document.top() + headerTable.getTotalHeight(), writer.getDirectContent());
        // Footer
        PdfPTable footerTable = new PdfPTable(2);
        PdfPCell cell1 = new PdfPCell(new Phrase("page " + writer.getPageNumber()));
        footerTable.addCell(cell1);
        PdfPCell cell2 = new PdfPCell(Image.getInstance(tpl));
        footerTable.addCell(cell2);
        footerTable.setTotalWidth(document.right() - document.left());
        footerTable.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:s2s.report.Report.java

License:GNU General Public License

public Element prepareImage(Document doc, byte[] fileContent, boolean marginConsider,
        float distanceFromBottomMargin) {
    try {//from   w w  w.j  av  a 2s.  c o  m
        Image img = Image.getInstance(fileContent);

        // Detemino le dimensioni della pagina, margini esclusi.
        float pageWidth = doc.getPageSize().getWidth()
                - (marginConsider ? doc.leftMargin() + doc.topMargin() : 0);
        float pageHeight = doc.getPageSize().getHeight()
                - (marginConsider ? doc.topMargin() + doc.bottomMargin() : 0)
                - (distanceFromBottomMargin > 0 ? distanceFromBottomMargin : 0);

        // Se l'immagine  pi larga e/o pi alta della pagina, 
        // esclusi i margini...
        if (img.getWidth() > pageWidth || img.getHeight() > pageHeight) {

            // Determino le percentuali di riduzione di entrambi le grandezze 
            // dell'immagine (larghezza ed altezza).
            float reducePrecentWidth = (img.getWidth() - pageWidth) > 0 ? (pageWidth * 100) / img.getWidth()
                    : 100;
            float reducePrecentHeight = (img.getHeight() - pageHeight) > 0
                    ? (pageHeight * 100) / img.getHeight()
                    : 100;

            // Determino la percentuale di riduzione
            float ReducePrecent = reducePrecentWidth;
            ReducePrecent = reducePrecentHeight < ReducePrecent ? reducePrecentHeight : ReducePrecent;

            img.scalePercent(ReducePrecent);
        }
        return img;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui l'allegato non sia un immagine
        ex.printStackTrace();
        return null;
    }
}