Example usage for com.lowagie.text Document setPageSize

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

Introduction

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

Prototype


public boolean setPageSize(Rectangle pageSize) 

Source Link

Document

Sets the pagesize.

Usage

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

@Override
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //inicializar documento: tamano de pagina, orientacion, margenes
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);
    doc.setPageSize(PageSize.LETTER.rotate());
    doc.setMargins(30, 30, 30, 40);/*from   w  w w.  j  a v  a 2 s  .c  o m*/

    doc.open();

    //crear fonts por defecto
    tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD);
    tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL);

    //definir pie de pagina del lado izquierdo
    String footerText = this.getFooter(); //read it from config.xml or web.xml
    String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm");

    //crear template (objeto interno de IText) y manejador de evento 
    //para imprimir el pie de pagina
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb = docWriter.getDirectContent();
    tpl = cb.createTemplate(20, 14);
    docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate));

    //titulo - lo lee de config.xml por defecto
    reportTitle = getReportTitle();
    Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD));
    t.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.add(t);

    //logo
    img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false));
    img.scalePercent(100);
    float imgY = doc.top() - img.getHeight();
    float imgX = doc.left();
    img.setAbsolutePosition(imgX, imgY);
    doc.add(img);

    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));

    //for each master record print a master/detail section
    MasterDetailReader dataobj = (MasterDetailReader) data;
    Recordset master = dataobj.getRecordset("master");
    master.top();
    while (master.next()) {
        //blank line
        doc.add(new Paragraph(" "));

        //print master section
        doc.add(getGroupMaster(master));

        //print detail section
        doc.add(getGroupDetail(master, dataobj.getDetail(master)));

    }

    //print grand total
    doc.add(new Paragraph(" "));

    doc.close();
    docWriter.close();

}

From source file:ec.edu.chyc.manejopersonal.managebean.PDFCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {
    try {//from  w w  w  . ja  va  2  s .co m
        Document document = new Document();
        if (orientation.equalsIgnoreCase("Landscape")) {
            document.setPageSize(PageSize.A4.rotate());
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        StringTokenizer st = new StringTokenizer(tableId, ",");
        while (st.hasMoreElements()) {
            String tableName = (String) st.nextElement();
            UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                    tableName);
            if (component == null) {
                throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
            }
            if (!(component instanceof DataTable || component instanceof DataList)) {
                throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                        + "\", exporter must target a PrimeFaces DataTable/DataList.");
            }

            if (preProcessor != null) {
                preProcessor.invoke(context.getELContext(), new Object[] { document });
            }

            if (!document.isOpen()) {
                document.open();
            }
            if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {

                Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE,
                        Font.BOLD);
                Paragraph title = new Paragraph(tableTitle, tableTitleFont);
                document.add(title);

                Paragraph preface = new Paragraph();
                addEmptyLine(preface, 3);
                document.add(preface);
            }
            PdfPTable pdf;
            DataList list = null;
            DataTable table = null;
            if (component instanceof DataList) {
                list = (DataList) component;
                pdf = exportPDFTable(context, list, pageOnly, encodingType);
            } else {
                table = (DataTable) component;
                pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable);
            }

            if (pdf != null) {
                document.add(pdf);
            }
            // add a couple of blank lines
            Paragraph preface = new Paragraph();
            addEmptyLine(preface, datasetPadding);
            document.add(preface);

            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { document });
            }
        }
        document.close();

        writePDFToResponse(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:edu.eci.pdsw.g4.bean.control.web.SystemManageBean.java

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();/*from www .jav  a2 s  . c  o m*/
    pdf.setPageSize(PageSize.A4);

    pdf.addTitle("Ficha del Equipo : " + loadTipoEquipo.getNombre_equipo());

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    String logo = externalContext.getRealPath("") + File.separator + "resource" + File.separator
            + "ecijulio.png";

    pdf.add(Image.getInstance(logo));
    pdf.bottom(30);

    pdf.add(new Chunk(
            "Datos del Equipo : " + loadTipoEquipo.getNombre_equipo() + " con Placa No : " + getPlacaficha()));
}

From source file:edu.harvard.mcz.imagecapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(List<UnitTrayLabel> taxa) throws PrintFailedException {
    boolean result = false;
    UnitTrayLabel label = new UnitTrayLabel();
    LabelEncoder encoder = new LabelEncoder(label);
    Image image = encoder.getImage();
    int counter = 0;
    try {/*w ww  . j  av  a2  s  . c o  m*/
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("labels.pdf"));
        document.setPageSize(PageSize.LETTER);
        document.open();

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100f);
        //table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        float[] cellWidths = { 30f, 20f, 30f, 20f };
        table.setWidths(cellWidths);

        UnitTrayLabelLifeCycle uls = new UnitTrayLabelLifeCycle();
        if (taxa == null) {
            taxa = uls.findAll();
        }
        Iterator<UnitTrayLabel> i = taxa.iterator();
        PdfPCell cell = null;
        PdfPCell cell_barcode = null;
        // Create two lists of 12 cells, the first 6 of each representing
        // the left hand column of 6 labels, the second 6 of each 
        // representing the right hand column.  
        // cells holds the text for each label, cells_barcode the barcode.
        ArrayList<PdfPCell> cells = new ArrayList<PdfPCell>(12);
        ArrayList<PdfPCell> cells_barcode = new ArrayList<PdfPCell>(12);
        for (int x = 0; x < 12; x++) {
            cells.add(null);
            cells_barcode.add(null);
        }
        int cellCounter = 0;
        while (i.hasNext()) {
            // Loop through all of the taxa (unit tray labels) found to print 
            label = i.next();
            for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                // For each taxon, loop through the number of requested copies 
                // Generate a text and a barcode cell for each, and add to array for page
                log.debug("Label " + toPrint + " of " + label.getNumberToPrint());
                cell = new PdfPCell();
                cell.setBorderColor(Color.LIGHT_GRAY);
                cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                cell.disableBorderSide(PdfPCell.RIGHT);
                cell.setPaddingLeft(3);

                String higherNames = "";
                if (label.getTribe().trim().length() > 0) {
                    higherNames = label.getFamily() + ": " + label.getSubfamily() + ": " + label.getTribe();
                } else {
                    higherNames = label.getFamily() + ": " + label.getSubfamily();
                }
                Paragraph higher = new Paragraph();
                higher.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                higher.add(new Chunk(higherNames));
                cell.addElement(higher);

                Paragraph name = new Paragraph();
                Chunk genus = new Chunk(label.getGenus().trim() + " ");
                genus.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                Chunk species = new Chunk(label.getSpecificEpithet().trim());
                Chunk normal = null; // normal font prefix to preceed specific epithet (nr. <i>epithet</i>)
                if (label.getSpecificEpithet().contains(".") || label.getSpecificEpithet().contains("[")) {
                    if (label.getSpecificEpithet().startsWith("nr. ")) {
                        normal = new Chunk("nr. ");
                        normal.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                        species = new Chunk(label.getSpecificEpithet().trim().substring(4));
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                    } else {
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                    }
                } else {
                    species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                String s = "";
                if (label.getSubspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk subspecies = new Chunk(s + label.getSubspecificEpithet().trim());
                if (label.getSubspecificEpithet().contains(".")
                        || label.getSubspecificEpithet().contains("[")) {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                } else {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                if (label.getInfraspecificRank().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infraRank = new Chunk(s + label.getInfraspecificRank().trim());
                infraRank.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                if (label.getInfraspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infra = new Chunk(s + label.getInfraspecificEpithet().trim());
                infra.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                if (label.getUnNamedForm().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk unNamed = new Chunk(s + label.getUnNamedForm().trim());
                unNamed.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                name.add(genus);
                if (normal != null) {
                    name.add(normal);
                }
                name.add(species);
                name.add(subspecies);
                name.add(infraRank);
                name.add(infra);
                name.add(unNamed);
                cell.addElement(name);

                Paragraph authorship = new Paragraph();
                authorship.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                if (label.getAuthorship() != null && label.getAuthorship().length() > 0) {
                    Chunk c_authorship = new Chunk(label.getAuthorship());
                    authorship.add(c_authorship);
                }
                cell.addElement(authorship);
                //cell.addElement(new Paragraph(" "));
                if (label.getDrawerNumber() != null && label.getDrawerNumber().length() > 0) {
                    Paragraph drawerNumber = new Paragraph();
                    drawerNumber.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                    Chunk c_drawerNumber = new Chunk(label.getDrawerNumber());
                    drawerNumber.add(c_drawerNumber);
                    cell.addElement(drawerNumber);
                } else {
                    if (label.getCollection() != null && label.getCollection().length() > 0) {
                        Paragraph collection = new Paragraph();
                        collection.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                        Chunk c_collection = new Chunk(label.getCollection());
                        collection.add(c_collection);
                        cell.addElement(collection);
                    }
                }

                cell_barcode = new PdfPCell();
                cell_barcode.setBorderColor(Color.LIGHT_GRAY);
                cell_barcode.disableBorderSide(PdfPCell.LEFT);
                cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);

                encoder = new LabelEncoder(label);
                image = encoder.getImage();
                image.setAlignment(Image.ALIGN_TOP);
                cell_barcode.addElement(image);

                cells.add(cellCounter, cell);
                cells_barcode.add(cellCounter, cell_barcode);

                cellCounter++;
                // If we have hit a full set of 12 labels, add them to the document
                // in two columns, filling left column first, then right
                if (cellCounter == 12) {
                    // add a page of 12 cells in columns of two.
                    for (int x = 0; x < 6; x++) {
                        if (cells.get(x) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x));
                            table.addCell(cells_barcode.get(x));
                        }
                        if (cells.get(x + 6) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x + 6));
                            table.addCell(cells_barcode.get(x + 6));
                        }
                    }
                    // Reset to begin next page
                    cellCounter = 0;
                    document.add(table);
                    table = new PdfPTable(4);
                    table.setWidthPercentage(100f);
                    table.setWidths(cellWidths);
                    for (int x = 0; x < 12; x++) {
                        cells.set(x, null);
                        cells_barcode.set(x, null);
                    }
                }
            } // end loop through toPrint (for a taxon)
            counter++;
        } // end while results has next (for all taxa requested)
          // get any remaining cells in pairs
        for (int x = 0; x < 6; x++) {
            if (cells.get(x) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x));
                table.addCell(cells_barcode.get(x));
            }
            if (cells.get(x + 6) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x + 6));
                table.addCell(cells_barcode.get(x + 6));
            }
        }
        // add any remaining cells
        document.add(table);
        try {
            document.close();
        } catch (Exception e) {
            throw new PrintFailedException("No labels to print." + e.getMessage());
        }
        // Check to see if there was content in the document.
        if (counter == 0) {
            result = false;
        } else {
            // Printed to pdf ok.
            result = true;
            // Increment number printed.
            i = taxa.iterator();
            while (i.hasNext()) {
                label = i.next();
                for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                    label.setPrinted(label.getPrinted() + 1);
                }
                label.setNumberToPrint(0);
                try {
                    uls.attachDirty(label);
                } catch (SaveFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("File not found.");
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("Error buiding PDF document.");
    } catch (OutOfMemoryError e) {
        System.out.println("Out of memory error. " + e.getMessage());
        System.out.println("Failed.  Too many labels.");
        throw new PrintFailedException("Ran out of memory, too many labels at once.");
    }
    return result;
}

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * configure le document pdf.// w  ww .j ava2  s.  co  m
 * @param width
 * @param height
 * @param margin
 * @return doc
 */
private Document configureDocument(final float margin) {

    Document document = new Document();

    document.setPageSize(PageSize.A4.rotate());
    float marginPage = (margin / 2.54f) * 72f;
    document.setMargins(marginPage, marginPage, marginPage, marginPage);

    return document;
}

From source file:fr.univlorraine.mondossierweb.controllers.InscriptionController.java

License:Apache License

/**
 * configure le document pdf.//ww w .  j a v a  2s  .c  om
 * @param width
 * @param height
 * @param margin
 * @return doc
 */
private Document configureDocument() {

    Document document = new Document();

    document.setPageSize(PageSize.A4);
    float marginTop = (MARGIN_TOP / 2.54f) * 72f;
    float marginRight = (MARGIN_RIGHT / 2.54f) * 72f;
    float marginBottom = (MARGIN_BOTTOM / 2.54f) * 72f;
    float marginLeft = (MARGIN_LEFT / 2.54f) * 72f;
    document.setMargins(marginLeft, marginRight, marginTop, marginBottom);

    return document;
}

From source file:gov.noaa.pfel.coastwatch.sgt.SgtUtil.java

License:Open Source License

/**
 * This creates a file to capture the pdf output generated by calls to 
 * graphics2D (e.g., use makeMap)./*from  w  ww . ja v  a2 s  . com*/
 * This will overwrite an existing file.
 * 
 * @param pageSize e.g, PageSize.LETTER or PageSize.LETTER.rotate() (or A4, or, ...)
 * @param width the bounding box width, in 1/144ths of an inch
 * @param height the bounding box height, in 1/144ths of an inch
 * @param outputStream
 * @return an object[] with 0=g2D, 1=document, 2=pdfContentByte, 3=pdfTemplate
 * @throws Exception if trouble
 */
public static Object[] createPdf(com.lowagie.text.Rectangle pageSize, int bbWidth, int bbHeight,
        OutputStream outputStream) throws Exception {
    //currently, this uses itext
    //see the sample program:
    //  file://localhost/C:/programs/iText/examples/com/lowagie/examples/directcontent/graphics2D/G2D.java
    //Document.compress = false; //for test purposes only
    Document document = new Document(pageSize);
    document.addCreationDate();
    document.addCreator("gov.noaa.pfel.coastwatch.SgtUtil.createPdf");

    document.setPageSize(pageSize);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();

    //create contentByte and template and Graphics2D objects
    PdfContentByte pdfContentByte = writer.getDirectContent();
    PdfTemplate pdfTemplate = pdfContentByte.createTemplate(bbWidth, bbHeight);
    Graphics2D g2D = pdfTemplate.createGraphics(bbWidth, bbHeight);

    return new Object[] { g2D, document, pdfContentByte, pdfTemplate };
}

From source file:gov.utah.health.uper.reports.Registration.java

/**
 * Set up spacing on page/*from  ww w.  jav  a  2 s .  c om*/
 * @param document
 */
private void setUpPage(Document document) {
    document.setPageSize(PageSize.NOTE);
    //left, right, top, bottom
    document.setMargins(100, 100, 100, 100);
    document.open();

}

From source file:it.eng.spagobi.engines.exporters.ChartExporter.java

License:Mozilla Public License

/** check if the image has to be turned or resize
 * /*from  w  w  w.ja v a  2  s.  c  o  m*/
 * @param document
 * @param jpg
 * @return if the image has been turned
 */

public void changeLayout(Document pdfDocument, Image jpg, float width, float height) {
    logger.debug("IN");
    // if width is more than 600 and height is not more it suffices to turn the image of the chart
    if (width > MAX_WIDTH && !(height > MAX_WIDTH) && !(width > MAX_HEIGHT)) {
        pdfDocument.setPageSize(PageSize.LETTER.rotate());
        logger.debug("pdf rotation");
    } else {
        // otherwise the chart needs to be scaled (if width > height also turn!)
        // SCALED WITH turning
        if (width > height) {
            pdfDocument.setPageSize(PageSize.LETTER.rotate());
            // calculate wich size is to reduce most:
            float percentageToReduceHeight = 0;
            float percentageToReduceWidth = 0;
            if (height > MAX_WIDTH) {
                percentageToReduceHeight = (height * 100) / MAX_WIDTH;
            }
            if (width > MAX_HEIGHT) {
                percentageToReduceWidth = (width * 100) / MAX_HEIGHT;
            }
            float percToReduce = percentageToReduceHeight > percentageToReduceWidth ? percentageToReduceHeight
                    : percentageToReduceWidth;
            float percToScale = percToReduce - 100;
            //                  float newHeight = height - ((height/100)*percToReduce);
            //            float newWidth = width - ((width/100)*percToReduce);
            logger.debug("pdf scale of percentage " + percToScale);
            jpg.scalePercent(percToScale);

            logger.debug("pdf rotation and scaling");
        } else {
            // SCALED WITHOUT turning
            // calculate wich size is to reduce most:
            float percentageToReduceHeight = 0;
            float percentageToReduceWidth = 0;
            if (height > MAX_HEIGHT) {
                percentageToReduceHeight = (height * 100) / MAX_HEIGHT;
            }
            if (width > MAX_WIDTH) {
                percentageToReduceWidth = (width * 100) / MAX_WIDTH;
            }
            float percToReduce = percentageToReduceHeight > percentageToReduceWidth ? percentageToReduceHeight
                    : percentageToReduceWidth;
            float percToScale = percToReduce - 100;
            //                  float newHeight = height - ((height/100)*percToReduce);
            //            float newWidth = width - ((width/100)*percToReduce);
            logger.debug("pdf scale of percentage " + percToScale);
            jpg.scalePercent(percToScale);
            logger.debug("pdf scaling");
        }
    }
    logger.debug("OUT");
}

From source file:javaaxp.xps2pdf.service.impl.PDFConverterImpl.java

License:Open Source License

@Override
public void covertToPDF(OutputStream ouput) throws XPSError {
    try {/*from w w w . j a  v  a 2  s .com*/
        int firstPage = fPageController.getXPSAccess().getPageAccess(0).getFirstPageNum();
        int lastPage = fPageController.getXPSAccess().getPageAccess(0).getLastPageNum();

        Document document = new Document();
        document.setPageCount(lastPage - firstPage + 1);
        document.setPageSize(PageSize.LETTER);
        PdfWriter writer = PdfWriter.getInstance(document, ouput);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        for (int i = firstPage; i < 1; i++) {
            System.out.println("Converting page " + i);
            fPageController.setPage(i);
            PdfTemplate tp = cb.createTemplate((float) fPageController.getPage().getWidth(),
                    (float) fPageController.getPage().getHeight());
            Graphics g = tp.createGraphics((float) fPageController.getPage().getWidth(),
                    (float) fPageController.getPage().getHeight());
            JComponent toReturn = fPageViewer.getPageRenderer().getRendererComponent();
            toReturn.paint(g);
            cb.addTemplate(tp, 0, 0);
            document.newPage();
        }
        document.close();
    } catch (DocumentException e) {
        //rethrow
    }
}