Example usage for java.awt.print PageFormat getWidth

List of usage examples for java.awt.print PageFormat getWidth

Introduction

In this page you can find the example usage for java.awt.print PageFormat getWidth.

Prototype

public double getWidth() 

Source Link

Document

Returns the width, in 1/72nds of an inch, of the page.

Usage

From source file:BasicPrint.java

public int print(Graphics g, PageFormat pf, int pageIndex) {

    double x = 0;
    double y = 0;
    double w = pf.getWidth();
    double h = pf.getHeight();

    return Printable.NO_SUCH_PAGE;
}

From source file:BookTest.java

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    PageFormat pageFormat = book.getPageFormat(currentPage);

    double xoff; // x offset of page start in window
    double yoff; // y offset of page start in window
    double scale; // scale factor to fit page in window
    double px = pageFormat.getWidth();
    double py = pageFormat.getHeight();
    double sx = getWidth() - 1;
    double sy = getHeight() - 1;
    if (px / py < sx / sy) // center horizontally
    {/*from w  ww. ja  v a2  s.c  om*/
        scale = sy / py;
        xoff = 0.5 * (sx - scale * px);
        yoff = 0;
    } else
    // center vertically
    {
        scale = sx / px;
        xoff = 0;
        yoff = 0.5 * (sy - scale * py);
    }
    g2.translate((float) xoff, (float) yoff);
    g2.scale((float) scale, (float) scale);

    // draw page outline (ignoring margins)
    Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
    g2.setPaint(Color.white);
    g2.fill(page);
    g2.setPaint(Color.black);
    g2.draw(page);

    Printable printable = book.getPrintable(currentPage);
    try {
        printable.print(g2, pageFormat, currentPage);
    } catch (PrinterException e) {
        g2.draw(new Line2D.Double(0, 0, px, py));
        g2.draw(new Line2D.Double(px, 0, 0, py));
    }
}

From source file:JavaWorldPrintExample1.java

/**
 * Method: print/*from   ww w  .j  a  v  a 2s  . com*/
 * <p>
 * 
 * This class is responsible for rendering a page using the provided
 * parameters. The result will be a grid where each cell will be half an
 * inch by half an inch.
 * 
 * @param g
 *            a value of type Graphics
 * @param pageFormat
 *            a value of type PageFormat
 * @param page
 *            a value of type int
 * @return a value of type int
 */
public int print(Graphics g, PageFormat pageFormat, int page) {

    int i;
    Graphics2D g2d;
    Line2D.Double line = new Line2D.Double();

    //--- Validate the page number, we only print the first page
    if (page == 0) {

        //--- Create a graphic2D object a set the default parameters
        g2d = (Graphics2D) g;
        g2d.setColor(Color.black);

        //--- Translate the origin to be (0,0)
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        //--- Print the vertical lines
        for (i = 0; i < pageFormat.getWidth(); i += INCH / 2) {
            line.setLine(i, 0, i, pageFormat.getHeight());
            g2d.draw(line);
        }

        //--- Print the horizontal lines
        for (i = 0; i < pageFormat.getHeight(); i += INCH / 2) {
            line.setLine(0, i, pageFormat.getWidth(), i);
            g2d.draw(line);
        }

        return (PAGE_EXISTS);
    } else
        return (NO_SUCH_PAGE);
}

From source file:be.fedict.eidviewer.gui.printing.IDPrintout.java

public int print(Graphics graphics, PageFormat pageFormat, int pageNumber) throws PrinterException {
    // we only support printing all in one single page
    if (pageNumber > 0)
        return Printable.NO_SUCH_PAGE;

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("width", pageFormat.getWidth()).append("height", pageFormat.getHeight())
            .append("imageableWidth", pageFormat.getImageableWidth())
            .append("imageableHeight", pageFormat.getImageableHeight())
            .append("imageableX", pageFormat.getImageableX()).append("imageableY", pageFormat.getImageableY())
            .append("orientation", pageFormat.getOrientation())
            .append("paper.width", pageFormat.getPaper().getWidth())
            .append("paper.height", pageFormat.getPaper().getHeight())
            .append("paper.imageableWidth", pageFormat.getPaper().getImageableWidth())
            .append("paper.imageableHeight", pageFormat.getPaper().getImageableHeight())
            .append("paper.imageableX", pageFormat.getPaper().getImageableX())
            .append("paper.imageableY", pageFormat.getPaper().getImageableY()).toString());

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("clip.width", graphics.getClipBounds().width)
            .append("clip.height", graphics.getClipBounds().height).append("clip.x", graphics.getClipBounds().x)
            .append("clip.y", graphics.getClipBounds().y).toString());

    // translate graphics2D with origin at top left first imageable location
    Graphics2D graphics2D = (Graphics2D) graphics;
    graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

    // keep imageable width and height as variables for clarity (we use them often)
    float imageableWidth = (float) pageFormat.getImageableWidth();
    float imageableHeight = (float) pageFormat.getImageableHeight();

    // Coat of Arms images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform coatOfArmsTransform = new AffineTransform();
    coatOfArmsTransform.scale(0.5, 0.5);

    // photo images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform photoTransform = new AffineTransform();
    photoTransform.scale(0.5, 0.5);//from   w w  w .j  ava 2  s.c  om
    photoTransform.translate((imageableWidth * 2) - (photo.getWidth(this)), 0);

    // make sure foreground is black, and draw coat of Arms and photo at the top of the page
    // using the transforms to scale them to 72DPI.
    graphics2D.setColor(Color.BLACK);
    graphics2D.drawImage(coatOfArms, coatOfArmsTransform, null);
    graphics2D.drawImage(photo, photoTransform, null);

    // calculate some sizes that need to take into account the scaling of the graphics, to avoid dragging
    // those non-intuitive "/2" further along in the code.
    float headerHeight = (float) (coatOfArms.getHeight(this)) / 2;
    float coatOfArmsWidth = (float) (coatOfArms.getWidth(this)) / 2;
    float photoWidth = (float) (photo.getWidth(this)) / 2;
    float headerSpaceBetweenImages = imageableWidth
            - (coatOfArmsWidth + photoWidth + (SPACE_BETWEEN_ITEMS * 2));

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("headerHeight", headerHeight)
            .append("coatOfArmsWidth", coatOfArmsWidth).append("photoWidth", photoWidth)
            .append("headerSpaceBetweenImages", headerSpaceBetweenImages).toString());

    // get localised strings for card type. We'll take a new line every time a ";" is found in the resource
    String[] cardTypeStr = (bundle.getString("type_" + this.identity.getDocumentType().toString())
            .toUpperCase()).split(";");

    // if a "mention" is present, append it so it appears below the card type string, between brackets

    if (identity.getSpecialOrganisation() != SpecialOrganisation.UNSPECIFIED) {
        String mention = TextFormatHelper.getSpecialOrganisationString(bundle,
                identity.getSpecialOrganisation());
        if (mention != null && !mention.isEmpty()) {
            String[] cardTypeWithMention = new String[cardTypeStr.length + 1];
            System.arraycopy(cardTypeStr, 0, cardTypeWithMention, 0, cardTypeStr.length);
            cardTypeWithMention[cardTypeStr.length] = "(" + mention + ")";
            cardTypeStr = cardTypeWithMention;
        }
    }

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the card type strings
    // stop when a font size is found where they all fit the space between the graphics in an orderly manner
    boolean sizeFound = false;
    int fontSize;
    for (fontSize = TITLE_MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        sizeFound = (ImageUtilities.getTotalStringWidth(graphics2D, cardTypeStr) < headerSpaceBetweenImages)
                && (ImageUtilities.getTotalStringHeight(graphics2D, cardTypeStr) < headerHeight);
    }

    // unless with extremely small papers, a size should always have been found.
    // draw the card type strings, centered, between the images at the top of the page
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize + 1));
        float cardTypeHeight = cardTypeStr.length * ImageUtilities.getStringHeight(graphics2D);
        float cardTypeBaseLine = ((headerHeight - cardTypeHeight) / 2) + ImageUtilities.getAscent(graphics2D);
        float cardTypeLineHeight = ImageUtilities.getStringHeight(graphics2D);

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
                .append("cardTypeHeight", cardTypeHeight).append("cardTypeBaseLine", cardTypeBaseLine)
                .append("cardTypeLineHeight", cardTypeLineHeight).toString());

        for (int i = 0; i < cardTypeStr.length; i++) {
            float left = (coatOfArmsWidth + SPACE_BETWEEN_ITEMS
                    + (headerSpaceBetweenImages - ImageUtilities.getStringWidth(graphics2D, cardTypeStr[i]))
                            / 2);
            float leading = (float) cardTypeLineHeight * i;
            graphics2D.drawString(cardTypeStr[i], left, cardTypeBaseLine + leading);
        }
    }

    // populate idAttributes with all the information from identity and address
    // as well as date printed and some separators
    List<IdentityAttribute> idAttributes = populateAttributeList();

    // draw a horizontal line just below the header (images + card type titles)
    graphics2D.drawLine(0, (int) headerHeight, (int) imageableWidth, (int) headerHeight);

    // calculate how much space is left between the header and the bottom of the imageable area

    headerHeight += 32; // take some distance from header

    float imageableDataHeight = imageableHeight - headerHeight;
    float totalDataWidth = 0, totalDataHeight = 0;
    float labelWidth, widestLabelWidth = 0;
    float valueWidth, widestValueWidth = 0;

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the information in idAttributes into
    // the space between the header and the bottom of the imageable area
    // stop when a font size is found where it all fits in an orderly manner
    sizeFound = false;
    for (fontSize = MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));

        widestLabelWidth = 0;
        widestValueWidth = 0;

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute == SEPARATOR)
                continue;

            labelWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getLabel());
            valueWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getValue());
            if (labelWidth > widestLabelWidth)
                widestLabelWidth = labelWidth;
            if (valueWidth > widestValueWidth)
                widestValueWidth = valueWidth;
        }

        totalDataWidth = widestLabelWidth + SPACE_BETWEEN_ITEMS + widestValueWidth;
        totalDataHeight = ImageUtilities.getStringHeight(graphics2D)
                + (ImageUtilities.getStringHeight(graphics2D) * idAttributes.size());

        if ((totalDataWidth < imageableWidth) && (totalDataHeight < imageableDataHeight))
            sizeFound = true;
    }

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("widestLabelWidth", widestLabelWidth).append("widestValueWidth", widestValueWidth)
            .append("totalDataWidth", totalDataWidth).append("totalDataHeight", totalDataHeight).toString());

    // unless with extremely small papers, a size should always have been found.
    // draw the identity, addess and date printed information, in 2 columns, centered inside the
    // space between the header and the bottom of the imageable area
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        float labelsLeft = (imageableWidth - totalDataWidth) / 2;
        float valuesLeft = labelsLeft + widestLabelWidth + SPACE_BETWEEN_ITEMS;
        float dataLineHeight = ImageUtilities.getStringHeight(graphics2D);
        float dataTop = dataLineHeight + headerHeight + ((imageableDataHeight - totalDataHeight) / 2);
        float lineNumber = 0;

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("labelsLeft", labelsLeft)
                .append("valuesLeft", valuesLeft).append("dataLineHeight", dataLineHeight)
                .append("dataTop", dataTop).toString());

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute != SEPARATOR) // data
            {
                graphics2D.setColor(attribute.isRelevant() ? Color.BLACK : Color.LIGHT_GRAY);
                graphics2D.drawString(attribute.getLabel(), labelsLeft,
                        dataTop + (lineNumber * dataLineHeight));
                graphics2D.drawString(attribute.getValue(), valuesLeft,
                        dataTop + (lineNumber * dataLineHeight));
            } else // separator
            {
                int y = (int) (((dataTop + (lineNumber * dataLineHeight) + (dataLineHeight / 2)))
                        - ImageUtilities.getAscent(graphics2D));
                graphics2D.setColor(Color.BLACK);
                graphics2D.drawLine((int) labelsLeft, y, (int) (labelsLeft + totalDataWidth), y);
            }
            lineNumber++;
        }
    }

    // tell Java printing that all this makes for a page worth printing :-)
    return Printable.PAGE_EXISTS;
}

From source file:PageFormatFactory.java

/**
 * Logs the page format./* w ww. j  a  v a  2 s  .c  o m*/
 *
 * @param pf the page format.
 */
public static void logPageFormat(final PageFormat pf) {
    System.out.println("PageFormat: Width: " + pf.getWidth() + " Height: " + pf.getHeight());
    System.out.println("PageFormat: Image: X " + pf.getImageableX() + " Y " + pf.getImageableY() + " W: "
            + pf.getImageableWidth() + " H: " + pf.getImageableHeight());
    System.out.println("PageFormat: Margins: X " + pf.getImageableX() + " Y " + pf.getImageableY() + " X2: "
            + (pf.getImageableWidth() + pf.getImageableX()) + " Y2: "
            + (pf.getImageableHeight() + pf.getImageableY()));
}

From source file:PageFormatFactory.java

public Insets getPageMargins(final PageFormat format) {

    final int marginLeft = (int) format.getImageableX();
    final int marginRight = (int) (format.getWidth() - format.getImageableWidth() - format.getImageableX());
    final int marginTop = (int) (format.getImageableY());
    final int marginBottom = (int) (format.getHeight() - format.getImageableHeight() - format.getImageableY());
    return new Insets(marginTop, marginLeft, marginBottom, marginRight);
}

From source file:lu.fisch.unimozer.Diagram.java

public void printDiagram() {
    // print preview takes a lot of memory (don't know why)
    // so it is a good idea to sugest to the JVM to clean up the heap
    System.gc();// w  w  w  .j a  v a2s.c o  m
    printOptions = PrintOptions.showModal(frame, "Print options");
    if (printOptions.OK == true) {
        this.deselectAll();
        this.cleanAll();
        this.repaint();

        if (printOptions.getJob() == PrintOptions.JOB_PREVIEW) {
            PrintPreview pp = new PrintPreview(frame, this);
            pp.setLocation(Math.round((frame.getWidth() - pp.getWidth()) / 2 + frame.getLocation().x),
                    (frame.getHeight() - pp.getHeight()) / 2 + frame.getLocation().y);
            pp.setVisible(true);
        } else {
            try {
                // Use default printer, no dialog
                PrinterJob prnJob = PrinterJob.getPrinterJob();

                // get the default page format
                PageFormat pf0 = prnJob.defaultPage();
                // clone it
                PageFormat pf1 = (PageFormat) pf0.clone();
                Paper p = pf0.getPaper();
                // set to zero margin
                p.setImageableArea(0, 0, pf0.getWidth(), pf0.getHeight());
                pf1.setPaper(p);
                // let the printer validate it
                PageFormat pf2 = prnJob.validatePage(pf1);
                //prnJob.pageDialog(prnJob.defaultPage());

                prnJob.setPrintable(this, pf2);
                if (prnJob.printDialog()) {
                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    prnJob.print();
                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                }
            } catch (PrinterException ex) {
                ex.printStackTrace();
                System.err.println("Printing error: " + ex.toString());
            }
        }
    }
    System.gc();
}

From source file:org.pentaho.reporting.engine.classic.core.modules.gui.base.PreviewPane.java

protected void initializeFromReport() {
    final PageDefinition pageDefinition = reportJob.getPageDefinition();
    if (pageDefinition.getPageCount() > 0) {
        final PageFormat pageFormat = pageDefinition.getPageFormat(0);
        pageDrawable.setDefaultWidth((int) pageFormat.getWidth());
        pageDrawable.setDefaultHeight((int) pageFormat.getHeight());
    }// w w w.  j av a2s  .  co  m

    if (reportJob.getTitle() == null) {
        setTitle(messages.getString("PreviewPane.EMPTY_TITLE")); //$NON-NLS-1$
    } else {
        setTitle(messages.getString("PreviewPane.PREVIEW_TITLE", reportJob.getTitle())); //$NON-NLS-1$
    }

    final Configuration configuration = reportJob.getConfiguration();
    setIconTheme(PreviewPaneUtilities.createIconTheme(configuration));

    performInitialization(configuration);

    if (deferredRepagination == false) {
        startPagination();
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.parser.bundle.layout.PageDefinitionReadHandler.java

/**
 * Handles the page format./*  w  ww. jav a2  s.  c o m*/
 *
 * @param atts
 *          the attributes.
 * @throws SAXException
 *           if a parser error occurs or the validation failed.
 * @noinspection SuspiciousNameCombination
 */
private PageFormat configurePageSizeAndMargins(final Attributes atts, PageFormat format) throws SAXException {
    // (1) Grab the existing default ...
    float defTopMargin = (float) format.getImageableY();
    float defBottomMargin = (float) (format.getHeight() - format.getImageableHeight() - format.getImageableY());
    float defLeftMargin = (float) format.getImageableX();
    float defRightMargin = (float) (format.getWidth() - format.getImageableWidth() - format.getImageableX());

    // (2) Now configure the new paper-size
    format = configurePageSize(format, atts);

    // (3) Reconfigure margins as requested
    defTopMargin = ParserUtil.parseFloat(atts.getValue(getUri(), "margin-top"), defTopMargin);
    defBottomMargin = ParserUtil.parseFloat(atts.getValue(getUri(), "margin-bottom"), defBottomMargin);
    defLeftMargin = ParserUtil.parseFloat(atts.getValue(getUri(), "margin-left"), defLeftMargin);
    defRightMargin = ParserUtil.parseFloat(atts.getValue(getUri(), "margin-right"), defRightMargin);

    final Paper p = format.getPaper();
    switch (format.getOrientation()) {
    case PageFormat.PORTRAIT:
        PageFormatFactory.getInstance().setBorders(p, defTopMargin, defLeftMargin, defBottomMargin,
                defRightMargin);
        break;
    case PageFormat.REVERSE_LANDSCAPE:
        PageFormatFactory.getInstance().setBorders(p, defLeftMargin, defBottomMargin, defRightMargin,
                defTopMargin);
        break;
    case PageFormat.LANDSCAPE:
        PageFormatFactory.getInstance().setBorders(p, defRightMargin, defTopMargin, defLeftMargin,
                defBottomMargin);
        break;
    default:
        // will not happen..
        throw new IllegalArgumentException("Unexpected paper orientation.");
    }

    format.setPaper(p);
    return format;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.parser.ext.readhandlers.PageReadHandler.java

/**
 * Handles the page format.//from w w  w  .  j ava2  s. com
 *
 * @param atts
 *          the attributes.
 * @throws SAXException
 *           if a parser error occurs or the validation failed.
 * @noinspection SuspiciousNameCombination
 */
private void handlePageFormat(final Attributes atts) throws SAXException {
    final MasterReport report = (MasterReport) getRootHandler()
            .getHelperObject(ReportParserUtil.HELPER_OBJ_REPORT_NAME);

    // grab the default page definition ...
    PageFormat format = report.getPageDefinition().getPageFormat(0);
    float defTopMargin = (float) format.getImageableY();
    float defBottomMargin = (float) (format.getHeight() - format.getImageableHeight() - format.getImageableY());
    float defLeftMargin = (float) format.getImageableX();
    float defRightMargin = (float) (format.getWidth() - format.getImageableWidth() - format.getImageableX());

    format = createPageFormat(format, atts);

    defTopMargin = ParserUtil.parseFloat(atts.getValue(getUri(), PageReadHandler.TOPMARGIN_ATT), defTopMargin);
    defBottomMargin = ParserUtil.parseFloat(atts.getValue(getUri(), PageReadHandler.BOTTOMMARGIN_ATT),
            defBottomMargin);
    defLeftMargin = ParserUtil.parseFloat(atts.getValue(getUri(), PageReadHandler.LEFTMARGIN_ATT),
            defLeftMargin);
    defRightMargin = ParserUtil.parseFloat(atts.getValue(getUri(), PageReadHandler.RIGHTMARGIN_ATT),
            defRightMargin);

    final Paper p = format.getPaper();
    switch (format.getOrientation()) {
    case PageFormat.PORTRAIT:
        PageFormatFactory.getInstance().setBorders(p, defTopMargin, defLeftMargin, defBottomMargin,
                defRightMargin);
        break;
    case PageFormat.LANDSCAPE:
        // right, top, left, bottom
        PageFormatFactory.getInstance().setBorders(p, defRightMargin, defTopMargin, defLeftMargin,
                defBottomMargin);
        break;
    case PageFormat.REVERSE_LANDSCAPE:
        PageFormatFactory.getInstance().setBorders(p, defLeftMargin, defBottomMargin, defRightMargin,
                defTopMargin);
        break;
    default:
        // will not happen..
        throw new IllegalArgumentException("Unexpected paper orientation.");
    }

    format.setPaper(p);
    pageFormat = format;
}