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:de.tr1.cooperator.manager.web.CreateSubscriberListActionHelper.java

License:Open Source License

/**
 * After the content of the page is written, we put page X / Y
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 *//*from  w w w . j a v a2 s .  c  om*/
public void onEndPage(PdfWriter writer, Document document) {
    int pageN = writer.getPageNumber();
    String text = "" + pageN;
    String separator = " / ";
    float text_len = bf.getWidthPoint(text, 8);
    float sep_len = bf.getWidthPoint(separator, 8);
    cb.beginText();
    cb.setFontAndSize(bf, 8);
    float absMiddle = (document.right() - document.left()) / 2 + document.left();
    cb.setTextMatrix(absMiddle - text_len - (sep_len / 2), 30);
    cb.showText(text);
    cb.setTextMatrix(absMiddle - (sep_len / 2), 30);
    cb.showText(separator);
    cb.endText();
    cb.addTemplate(template, absMiddle + (sep_len / 2), 30);

    // write the headertable
    tHeader.setTotalWidth(document.right() - document.left());
    tHeader.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 20, cb);
}

From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java

License:GNU General Public License

/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)//from w ww . j a v  a2 s .c om
 */
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headertable
    table.setTotalWidth(document.right() - document.left());
    table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 20, cb);
    // compose the footer
    String text = writer.getPageNumber() + " / ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 49;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust - 5, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
    // draw a Rectangle around the page
    cb.setLineWidth(1);
    cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40);
    cb.stroke();
    cb.restoreState();
}

From source file:io.vertigo.dynamo.plugins.export.pdf.PDFAdvancedPageNumberEvents.java

License:Apache License

/** {@inheritDoc} */
@Override// ww  w. j  av  a2s . c  om
public void onEndPage(final PdfWriter writer, final Document document) {
    final int pageN = writer.getPageNumber();
    final String text = pageN + " / ";
    final float len = bf.getWidthPoint(text, 8);
    cb.beginText();
    cb.setFontAndSize(bf, 8);
    final float width = document.getPageSize().getWidth();
    cb.setTextMatrix(width / 2, 30);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(template, width / 2 + len, 30);
}

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

public FileOutputStream createPdfFile(FileOutputStream fileOutputStream,
        Map<String, DocumentContainer> documentsMap, boolean defaultStyle)
        throws MalformedURLException, IOException, DocumentException {

    logger.debug("IN");

    Document document = new Document(PageSize.A4.rotate());
    Rectangle rect = document.getPageSize();
    docWidth = rect.getWidth();/*from   www.j av  a2  s .  c  o m*/
    docHeight = rect.getHeight();

    logger.debug("document size width: " + docWidth + " height: " + docHeight);

    //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf"));
    PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
    document.open();

    int documentsNumber = documentsMap.keySet().size();
    int columnnsNumber = 2;

    if (defaultStyle == true) {
        logger.debug("use default style");
        int cellsCounter = 0;

        PdfPTable table = new PdfPTable(columnnsNumber);
        table.setWidthPercentage(100);

        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            DocumentContainer docContainer = documentsMap.get(label);
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                    table.addCell(img);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    table.addCell("");
                    //                  try {
                    //                     PdfReader reader = new PdfReader(content);
                    //                     PdfImportedPage page = writer.getImportedPage(reader, 1);
                    //                     writer.addPage(page);
                    //                     table.addCell("");
                    //                  } catch (Exception x) {
                    //                     logger.error("Error in inserting image for document " + label, e);
                    //                     logger.error("Error in inserting pdf file for document " + label, x);
                    //                     table.addCell("");
                    //                  }
                }
            }
            cellsCounter++;
        }

        // if cell counter is not pair make it pair
        if (cellsCounter % 2 != 0) {
            table.addCell("");
        }
        document.add(table);

    } else { // ************* NO DEFAULT STYLE *****************
        logger.debug("No default style");

        // I want to calculate total height of scaled heights!!
        //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle);

        // run on all documents
        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            logger.debug("document with label " + label);

            DocumentContainer docContainer = documentsMap.get(label);
            MetadataStyle style = docContainer.getStyle();

            // one table for each image, set at absolute position
            PdfPTable table = new PdfPTable(1);

            // width and height specified for the container by style attribute
            int widthStyle = style.getWidth();
            int heightStyle = style.getHeight();
            logger.debug("style for document width: " + widthStyle + " height: " + heightStyle);

            // width and height for the table scaled to the document size
            int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth);
            int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight);

            logger.debug("table for document width: " + tableWidth + " height: " + tableHeight);

            // x and y position as specified for the container by the style attribute
            int yStyle = style.getY();
            int xStyle = style.getX();
            // width and height scaled to the document size
            int xPos = (calculatePxPos(docWidth, xStyle, videoWidth));
            int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight));
            logger.debug("Table position at x: " + xPos + " y: " + yPos);

            // get the image
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    try {
                        PdfReader reader = new PdfReader(content);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfImportedPage page = writer.getImportedPage(reader, 1);
                        float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight);
                        cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]);
                    } catch (Exception x) {
                        logger.error("Error in inserting image for document " + label, e);
                        logger.error("Error in inserting pdf file for document " + label, x);
                    }
                    continue;
                }

                //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it?
                // if image size is more than double of the container size cut the first part,otherwise scale it
                if (docContainer.getDocumentType().equals("REPORT")) {
                    boolean cutImageWIdth = isToCutWidth(img, tableWidth);
                    boolean cutImageHeight = isToCutHeight(img, tableWidth);

                    if (cutImageWIdth == true || cutImageHeight == true) {
                        logger.debug(
                                "Report will be cut to width " + tableWidth + " and height " + tableHeight);
                        try {
                            img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth,
                                    (int) img.getWidth(), (int) img.getHeight());
                        } catch (Exception e) {
                            logger.error(
                                    "Error in image cut, cutt will be ignored and image will be drawn anyway ",
                                    e);
                        }
                    }
                }

                // this is percentage to resize
                // The image must be size within the cell               
                int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth,
                        tableHeight);
                logger.debug("image will be scaled of percentage " + percToResize);
                img.scalePercent(percToResize);

                PdfPCell cell = new PdfPCell(img);
                cell.setNoWrap(true);
                cell.setFixedHeight(tableHeight);
                cell.setBorderWidth(0);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                //table.setWidthPercentage(tableWidthPerc);
                table.setTotalWidth(tableWidth);
                table.setLockedWidth(true);
            } else {
                // TODO: setALT!
            }
            logger.debug("Add table");
            table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
            logger.debug("Document added");
        }

    }
    document.close();
    logger.debug("OUT");
    return fileOutputStream;
}

From source file:jdbreport.model.io.pdf.itext2.PdfWriter.java

License:Apache License

private int saveSheet(Document document, int listCount, ReportModel model)
        throws DocumentException, IOException, SaveReportException {

    model.updatePages(0);/*from  www  . j  a va  2 s . co  m*/

    ReportPage pageFormat = model.getReportPage();
    Paper paper = pageFormat.getPaper();
    Rectangle pageSize = new Rectangle(Math.round((float) paper.getWidth()),
            Math.round((float) paper.getHeight()));

    if (pageFormat.getOrientation() == ReportPage.LANDSCAPE) {
        pageSize = pageSize.rotate();
    }
    document.setPageSize(pageSize);
    document.setMargins(Math.round((float) pageFormat.getLeftMargin(Units.PT)),
            Math.round((float) pageFormat.getRightMargin(Units.PT)),
            Math.round((float) pageFormat.getTopMargin(Units.PT)),
            Math.round((float) pageFormat.getBottomMargin(Units.PT)));
    Rectangle viewPageSize = new Rectangle(
            document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(),
            document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin());

    if (listCount > 0) {
        document.newPage();
    }
    listCount++;

    //float columnMargin = (float) Units.PT.setXPixels(model.getColumnModel().getColumnMargin());

    ReportPrintable printable = new ReportPrintable(model);
    int pageCount = printable.calcCountPage(model.getReportPage());
    Map<Integer, PageClip> clips = printable.getPageClips();

    int leftCol;
    int topRow;
    int rightCol;
    int bottomRow;

    for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
        PageClip pageClip = clips.get(pageIndex);
        if (pageClip == null)
            break;

        leftCol = pageClip.getLeftCol();
        rightCol = pageClip.getRightCol();

        topRow = pageClip.getTopRow();
        bottomRow = pageClip.getBottomRow();

        int columnCount = rightCol - leftCol;

        float[] widths = new float[columnCount + 1];
        widths[0] = 1;
        for (int c = 0; c < columnCount; c++) {
            ReportColumn column = (ReportColumn) model.getColumnModel().getColumn(leftCol + c);
            widths[c + 1] = (float) Math.round(column.getNativeWidth());
        }

        PdfPTable table = createPdfTable(columnCount + 1, widths, viewPageSize);

        fillTable(model, leftCol, topRow, rightCol, bottomRow, table);

        document.add(table);

        if (pageIndex < clips.size()) {
            document.newPage();
        }

    }
    return listCount;
}

From source file:lt.bsprendimai.ddesk.pdf.PDFTicket.java

License:Apache License

public byte[] writePage() throws Exception {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {//from w  w  w.  java2 s.c o  m
        logo = Image.getInstance(root.getAbsolutePath() + "/logo.gif");
        logo.setAlignment(Image.ALIGN_LEFT);
    } catch (Exception exc) {
        exc.printStackTrace();
    }

    baseArial = BaseFont.createFont(root.getAbsolutePath() + "/objects/arial.ttf", BaseFont.CP1257,
            BaseFont.EMBEDDED);

    Document doc = new Document(PageSize.A4, 56.5354331f, 22.6771654f, 28.3464567f, 25.0f);
    PdfWriter.getInstance(doc, bout);

    doc.open();

    logo.setAbsolutePosition(28.3464567f, doc.getPageSize().height() - logo.height() - 25.0f);
    doc.add(logo);
    Paragraph pg = new Paragraph(sdf.format(new Date()), new Font(baseArial, 10));
    pg.setAlignment(Element.ALIGN_RIGHT);
    doc.add(pg);
    doc.add(new Phrase("\n\n\n"));

    writeClientInfo(doc);
    writeTicketInfo(doc);
    writeJobInfo(doc);
    writeWorkerInfo(doc);

    doc.close();

    return bout.toByteArray();
}

From source file:org.activityinfo.server.report.renderer.itext.ItextChartRenderer.java

License:Open Source License

@Override
public void render(DocWriter writer, Document doc, PivotChartReportElement element) throws DocumentException {

    doc.add(ThemeHelper.elementTitle(element.getTitle()));
    ItextRendererHelper.addFilterDescription(doc, element.getContent().getFilterDescriptions());
    ItextRendererHelper.addDateFilterDescription(doc, element.getFilter().getDateRange());

    if (element.getContent().getData().isEmpty()) {
        Paragraph para = new Paragraph(I18N.CONSTANTS.noData());
        para.setFont(new Font(Font.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 0)));
        doc.add(para);//from   www. j  av  a  2 s  .co  m

    } else {
        float width = doc.getPageSize().getWidth() - doc.rightMargin() - doc.leftMargin();
        float height = (doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin()) / 3f;

        renderImage(writer, doc, element, width, height);
    }
}

From source file:org.activityinfo.server.report.renderer.itext.ItextPivotTableRenderer.java

License:Open Source License

private float[] calcColumnWidths(Document doc, PivotTableData data, List<PivotTableData.Axis> leafColumns) {
    float[] widths = new float[leafColumns.size() + 1];
    float tableWidth = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
    float valueColumnWidth = 47f;

    widths[0] = tableWidth - (leafColumns.size() * valueColumnWidth);
    if (widths[0] < valueColumnWidth) {
        widths[0] = valueColumnWidth;//from  w  ww .j av a2 s.c  o m
    }
    for (int i = 1; i != widths.length; ++i) {
        widths[i] = valueColumnWidth;
    }
    return widths;
}

From source file:org.cyberoam.iview.charts.Chart.java

License:Open Source License

/**
 * This Event handler Method adds Header and Footer in PDF File
 *///from   w  w  w  .  j  ava  2s  . c o m
public void onEndPage(PdfWriter writer, Document document) {
    try {
        if (document.getPageNumber() > 1) {
            String seperator = System.getProperty("file.separator");
            //String path=System.getProperty("catalina.home") +seperator+"webapps" +seperator+"ROOT" + seperator + "images" + seperator;
            String path = InitServlet.contextPath + seperator + "images" + seperator;
            Image imgHead = Image.getInstance(path + "iViewPDFHeader.JPG");
            Image imgFoot = Image.getInstance(path + "iViewPDFFooter.JPG");
            Rectangle page = document.getPageSize();

            PdfPTable head = new PdfPTable(1);
            head.addCell(imgHead);
            head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            head.writeSelectedRows(0, -1, document.leftMargin() - 10,
                    page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

            PdfPTable foot = new PdfPTable(1);
            foot.addCell(imgFoot);
            foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            foot.writeSelectedRows(0, -1, document.leftMargin() - 10, document.bottomMargin() + 24,
                    writer.getDirectContent());
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.dgl.imgstopdf.Main.java

public static void main(String[] args) {
    Document document = new Document();
    ArrayList<String> input;
    String output = ".\\out.pdf";
    try {//from  w ww . j  a va 2s .co  m
        FileOutputStream fos = new FileOutputStream(output);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
        Image image;
        JFileChooser fc = new JFileChooser(".\\");
        fc.setMultiSelectionEnabled(true);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("IMAGES", "jpg", "jpeg", "gif", "png",
                "bmp");
        fc.setFileFilter(filter);
        int userOption = fc.showOpenDialog(null);
        if (userOption == JFileChooser.APPROVE_OPTION) {
            input = new ArrayList<String>();
            for (File f : fc.getSelectedFiles()) {
                input.add(f.getAbsolutePath());
            }
            if (fc.getSelectedFile() != null) {
                input.add(fc.getSelectedFile().getAbsolutePath());
            }
        } else {
            return;
        }
        if (input.size() == 0) {
            return;
        }
        pdfWriter.open();
        document.open();
        for (Object fileName : input.toArray()) {
            image = Image.getInstance((String) fileName);
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin())
                    / image.getWidth()) * 100;
            image.scalePercent(scaler);
            document.add(image);
        }
        document.close();
        pdfWriter.close();
        JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex.toString(), "", JOptionPane.ERROR_MESSAGE);
    }
}