Example usage for com.lowagie.text Document getPageSize

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

Introduction

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

Prototype


public Rectangle getPageSize() 

Source Link

Document

Gets the pagesize.

Usage

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 {/*from  www. ja  va  2  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 {/* ww  w.  j a v a  2s.co m*/
        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
 *///  ww  w . jav  a 2  s .  c  om
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

/**
 * Genera un NUEVO pdf con la imagen firmada y el pie de firma.
 *///w  ww. ja v  a 2 s  .c o  m
public void generarPdf(String texto, String texto2Linea, 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, texto2Linea, textoQR, codFirma, document, pageSize, false, false);

        // Cerramos el documento
        document.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 {/* w  w w .  ja v a2 s .c om*/
        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:oscar.oscarLab.ca.all.pageUtil.LabPDFCreator.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {//from w  w w.j  a  v a 2s .co m

        Rectangle page = document.getPageSize();
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        int pageNum = document.getPageNumber();
        float width = page.getWidth();
        float height = page.getHeight();

        //add patient name header for every page but the first.
        if (pageNum > 1) {
            cb.beginText();
            cb.setFontAndSize(bf, 8);
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, handler.getPatientName(), 575, height - 30, 0);
            cb.endText();

        }

        //add footer for every page
        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "-" + pageNum + "-", width / 2, 30, 0);
        cb.endText();

        // add promotext as footer if it is enabled
        if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
            cb.beginText();
            cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED),
                    6);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                    OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), width / 2, 19, 0);
            cb.endText();
        }

        // throw any exceptions
    } 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 {//  w ww.jav a  2  s. 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;
    }
}

From source file:sg.edu.nus.util.ReportWriter.java

public static String writeDataArrayToPdf(String userName, ArrayList<String[]> data, String title) {

    String rawFileName = userName + "_report.pdf";

    String fileName = ServerPeer.getReportFolderPath() + "/" + rawFileName;

    int ncol = data.get(0).length;

    Document document = new Document();
    try {/*www .j a v a  2s.  c o  m*/

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        /* Create the font. The font name must exactly match the font name on the client system. */
        Paragraph para = null;

        //         RtfFont embossedFont = new RtfFont("Times New Roman", 12,
        //               RtfFont.STYLE_EMBOSSED);

        // We add one empty line
        para = new Paragraph();
        addEmptyLine(para, 1);
        // Lets write a big header
        para.add(new Paragraph(title, catFont));

        addEmptyLine(para, 1);
        // Will create: Report generated by: _name, _date
        para.add(new Paragraph("Report generated by: " + userName + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                smallBold));
        addEmptyLine(para, 3);

        document.add(para);

        //add header and table content

        Font font8 = FontFactory.getFont(FontFactory.HELVETICA, 12);
        PdfPTable table = null;

        float columnPercentage = (float) (100.0 / ncol);
        float[] columnDefinitionSize = new float[ncol];
        for (int c = 0; c < ncol; c++) {
            columnDefinitionSize[c] = columnPercentage;
        }

        table = new PdfPTable(columnDefinitionSize);
        // table.getDefaultCell().setBorder(0);
        table.setHorizontalAlignment(0);
        float width = document.getPageSize().getWidth();
        table.setTotalWidth(width - 72);
        table.setLockedWidth(true);

        //write header
        String[] arr = data.get(0);
        for (int j = 0; j < ncol; j++) {
            table.addCell(new Phrase(arr[j], subFont));
        }

        //write data
        for (int i = 1; i < data.size(); i++) {
            arr = data.get(i);
            for (int j = 0; j < ncol; j++) {
                table.addCell(new Phrase(arr[j], font8));
            }
        }

        document.add(table);

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();

    return ServerPeer.getWebDownloadAddress() + "/" + rawFileName;
}

From source file:sg.edu.nus.util.ReportWriter.java

public static String writeDataArrayToRtf(String userName, ArrayList<String[]> data, String title) {

    String rawFileName = userName + "_report.rtf";

    String fileName = ServerPeer.getReportFolderPath() + "/" + rawFileName;

    int ncol = data.get(0).length;

    Document document = new Document();
    try {/*from   w  ww.  jav  a2  s . com*/

        RtfWriter2.getInstance(document, new FileOutputStream(fileName));
        document.open();

        Paragraph para = null;

        // We add one empty line
        para = new Paragraph();
        addEmptyLine(para, 1);
        // Lets write a big header
        para.add(new Paragraph(title, catFont));

        addEmptyLine(para, 1);
        // Will create: Report generated by: _name, _date
        para.add(new Paragraph("Report generated by: " + userName + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                smallBold));
        addEmptyLine(para, 3);

        document.add(para);
        //add header and table content

        Font font8 = FontFactory.getFont(FontFactory.HELVETICA, 12);
        PdfPTable table = null;

        float columnPercentage = (float) (100.0 / ncol);
        float[] columnDefinitionSize = new float[ncol];
        for (int c = 0; c < ncol; c++) {
            columnDefinitionSize[c] = columnPercentage;
        }

        table = new PdfPTable(columnDefinitionSize);
        // table.getDefaultCell().setBorder(0);
        table.setHorizontalAlignment(0);
        float width = document.getPageSize().getWidth();
        table.setTotalWidth(width - 72);
        table.setLockedWidth(true);

        //write header
        String[] arr = data.get(0);
        for (int j = 0; j < ncol; j++) {
            table.addCell(new Phrase(arr[j], subFont));
        }

        //write data
        for (int i = 1; i < data.size(); i++) {
            arr = data.get(i);
            for (int j = 0; j < ncol; j++) {
                table.addCell(new Phrase(arr[j], font8));
            }
        }

        document.add(table);

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();

    return ServerPeer.getWebDownloadAddress() + "/" + rawFileName;
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createMapAsPDF(File file, LWMap map) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER.rotate());

    try {/*w  w w . j a  v  a2 s . c o m*/
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        PdfContentByte cb = writer.getDirectContent();
        //  cb.setFontAndSize(arg0, arg1)
        PdfTemplate tp = cb.createTemplate(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70);
        // tp.createGraphicsShapes(arg0, arg1) 

        PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70, getFontMapper(), false, 60.0f);

        Dimension page = new Dimension((int) document.getPageSize().getWidth() - 70,
                (int) document.getPageSize().getHeight() - 70);
        // compute zoom & offset for visible map components
        Point2D.Float offset = new Point2D.Float();
        offset.x = 35;
        offset.y = 35;
        // center vertically only if landscape mode
        //if (format.getOrientation() == PageFormat.LANDSCAPE)
        //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)
        Rectangle2D bounds = map.getBounds();
        double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
        //  System.out.println(scale  + " zoom factor...");
        // set up the DrawContext
        DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                map, false); // todo: absolute links shouldn't be spec'd here

        //    dc.setAntiAlias(true);
        dc.setMapDrawing();
        //   dc.setPDFRender(true);
        //dc.setPrioritizeQuality(false); // why was this low quality?
        dc.setPrintQuality();
        //dc.setAntiAlias(false); // why was this turned off?  was it redundant?

        dc.setClipOptimized(true);
        //   dc.setDraftQuality(true);
        //  dc.setRawDrawing();
        //dc.setClipOptimized(false);

        dc.setInteractive(false);
        dc.setDrawPathways(false);

        // VUE.getActiveMap().draw(dc);
        LWPathway.setShowSlides(false);
        map.drawZero(dc);
        LWPathway.setShowSlides(true);
        g2d.dispose();
        //  document.add(new Paragraph(new Chunk().setAnchor("http://www.cnn.com")));
        cb.addTemplate(tp, 0, 0);
        document.newPage();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}