Example usage for java.awt.print Printable NO_SUCH_PAGE

List of usage examples for java.awt.print Printable NO_SUCH_PAGE

Introduction

In this page you can find the example usage for java.awt.print Printable NO_SUCH_PAGE.

Prototype

int NO_SUCH_PAGE

To view the source code for java.awt.print Printable NO_SUCH_PAGE.

Click Source Link

Document

Returned from print to signify that the pageIndex is too large and that the requested page does not exist.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    try {/*from  w ww .j a va  2  s.  c o m*/
        PrinterJob pjob = PrinterJob.getPrinterJob();
        pjob.setJobName("Graphics Demo Printout");
        pjob.setCopies(1);
        pjob.setPrintable(new Printable() {
            public int print(Graphics pg, PageFormat pf, int pageNum) {
                if (pageNum > 0) // we only print one page
                    return Printable.NO_SUCH_PAGE; // ie., end of job

                pg.drawString("www.java2s.com", 10, 10);

                return Printable.PAGE_EXISTS;
            }
        });

        if (pjob.printDialog() == false) // choose printer
            return;
        pjob.print();
    } catch (PrinterException pe) {
        pe.printStackTrace();
    }
}

From source file:BasicPrint.java

public int print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex > 0) {
        return Printable.NO_SUCH_PAGE;
    }//from  w  w  w  .  j  av a  2 s  .c  o m
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    drawGraphics(g2d, pf);
    return Printable.PAGE_EXISTS;
}

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:BasicPrint.java

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

    double ix = pf.getImageableX();
    double iy = pf.getImageableY();
    double iw = pf.getImageableWidth();
    double ih = pf.getImageableHeight();

    return Printable.NO_SUCH_PAGE;
}

From source file:MainClass.java

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
    // pageIndex 0 corresponds to page number 1.
    if (pageIndex >= 1)
        return Printable.NO_SUCH_PAGE;

    PrinterGraphics p = (PrinterGraphics) g;

    System.out.println(p.getPrinterJob().getCopies());
    System.out.println(p.getPrinterJob().getJobName());

    Graphics2D g2 = (Graphics2D) g;

    double w = pf.getImageableWidth();
    double h = pf.getImageableHeight();

    int xo = (int) pf.getImageableX();
    int yo = (int) pf.getImageableY();

    Rectangle2D r = new Rectangle2D.Double(xo, yo, w, h);

    g2.setColor(Color.red);/*  w  ww.j ava2s . com*/
    g2.draw(r);

    Shape s = new Ellipse2D.Double(xo + 4, yo + 4, 32, 32);

    g2.fill(s);

    return Printable.PAGE_EXISTS;
}

From source file:MainClass.java

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
    System.out.println("Page index = " + pageIndex);
    // pageIndex 1 corresponds to page number 2.
    if (pageIndex > 2)
        return Printable.NO_SUCH_PAGE;

    Graphics2D g2 = (Graphics2D) g;

    double w = pf.getImageableWidth();
    double h = pf.getImageableHeight();

    int xo = (int) pf.getImageableX();
    int yo = (int) pf.getImageableY();

    Rectangle2D r = new Rectangle2D.Double(xo, yo, w, h);

    g2.setColor(Color.red);//from   w w  w.j a  v a2s  . c o m
    g2.draw(r);

    return Printable.PAGE_EXISTS;
}

From source file:ImagePrint.java

public int print(Graphics g, PageFormat pf, int pageIndex) {
    Graphics2D g2d = (Graphics2D) g;
    g.translate((int) (pf.getImageableX()), (int) (pf.getImageableY()));
    if (pageIndex == 0) {
        double pageWidth = pf.getImageableWidth();
        double pageHeight = pf.getImageableHeight();
        double imageWidth = printImage.getIconWidth();
        double imageHeight = printImage.getIconHeight();
        double scaleX = pageWidth / imageWidth;
        double scaleY = pageHeight / imageHeight;
        double scaleFactor = Math.min(scaleX, scaleY);
        g2d.scale(scaleFactor, scaleFactor);
        g.drawImage(printImage.getImage(), 0, 0, null);
        return Printable.PAGE_EXISTS;
    }/*from ww  w. j av  a  2s .  c o m*/
    return Printable.NO_SUCH_PAGE;
}

From source file:PrintableComponent.java

/**
 * This is the "callback" method that the PrinterJob will invoke.
 * This method is defined by the Printable interface.
 *//*  w  ww.  jav a 2 s  .  c  o  m*/
public int print(Graphics g, PageFormat format, int pagenum) {
    // The PrinterJob will keep trying to print pages until we return
    // this value to tell it that it has reached the end.
    if (pagenum > 0)
        return Printable.NO_SUCH_PAGE;

    // We're passed a Graphics object, but it can always be cast to Graphics2D
    Graphics2D g2 = (Graphics2D) g;

    // Use the top and left margins specified in the PageFormat Note
    // that the PageFormat methods are poorly named.  They specify
    // margins, not the actual imageable area of the printer.
    g2.translate(format.getImageableX(), format.getImageableY());

    // Tell the component to draw itself to the printer by passing in 
    // the Graphics2D object.  This will not work well if the component
    // has double-buffering enabled.
    c.paint(g2);

    // Return this constant to tell the PrinterJob that we printed the page.
    return Printable.PAGE_EXISTS;
}

From source file:Main.java

/**
 * Prints a <code>Document</code> using a monospaced font, word wrapping on
 * the characters ' ', '\t', '\n', ',', '.', and ';'.  This method is
 * expected to be called from Printable 'print(Graphics g)' functions.
 *
 * @param g The graphics context to write to.
 * @param doc The <code>javax.swing.text.Document</code> to print.
 * @param fontSize the point size to use for the monospaced font.
 * @param pageIndex The page number to print.
 * @param pageFormat The format to print the page with.
 * @param tabSize The number of spaces to expand tabs to.
 *
 * @see #printDocumentMonospaced/*from  w  w  w .j  av  a 2  s. c  o m*/
 */
public static int printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex,
        PageFormat pageFormat, int tabSize) {

    g.setColor(Color.BLACK);
    g.setFont(new Font("Monospaced", Font.PLAIN, fontSize));

    // Initialize our static variables (these are used by our tab expander below).
    tabSizeInSpaces = tabSize;
    fm = g.getFontMetrics();

    // Create our tab expander.
    //RPrintTabExpander tabExpander = new RPrintTabExpander();

    // Get width and height of characters in this monospaced font.
    int fontWidth = fm.charWidth('w'); // Any character will do here, since font is monospaced.
    int fontHeight = fm.getHeight();

    int MAX_CHARS_PER_LINE = (int) pageFormat.getImageableWidth() / fontWidth;
    int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight;

    final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex;

    // The (x,y) coordinate to print at (in pixels, not characters).
    // Since y is the baseline of where we'll start printing (not the top-left
    // corner), we offset it by the font's ascent ( + 1 just for good measure).
    xOffset = (int) pageFormat.getImageableX();
    int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1;

    // A counter to keep track of the number of lines that WOULD HAVE been
    // printed if we were printing all lines.
    int numPrintedLines = 0;

    // Keep going while there are more lines in the document.
    currentDocLineNumber = 0; // The line number of the document we're currently on.
    rootElement = doc.getDefaultRootElement(); // To shorten accesses in our loop.
    numDocLines = rootElement.getElementCount(); // The number of lines in our document.
    while (currentDocLineNumber < numDocLines) {

        // Get the line we are going to print.
        String curLineString;
        Element currentLine = rootElement.getElement(currentDocLineNumber);
        int startOffs = currentLine.getStartOffset();
        try {
            curLineString = doc.getText(startOffs, currentLine.getEndOffset() - startOffs);
        } catch (BadLocationException ble) { // Never happens
            ble.printStackTrace();
            return Printable.NO_SUCH_PAGE;
        }

        // Remove newlines, because they end up as boxes if you don't; this is a monospaced font.
        curLineString = curLineString.replaceAll("\n", "");

        // Replace tabs with how many spaces they should be.
        if (tabSizeInSpaces == 0) {
            curLineString = curLineString.replaceAll("\t", "");
        } else {
            int tabIndex = curLineString.indexOf('\t');
            while (tabIndex > -1) {
                int spacesNeeded = tabSizeInSpaces - (tabIndex % tabSizeInSpaces);
                String replacementString = "";
                for (int i = 0; i < spacesNeeded; i++)
                    replacementString += ' ';
                // Note that "\t" is actually a regex for this method.
                curLineString = curLineString.replaceFirst("\t", replacementString);
                tabIndex = curLineString.indexOf('\t');
            }
        }

        // If this document line is too long to fit on one printed line on the page,
        // break it up into multpile lines.
        while (curLineString.length() > MAX_CHARS_PER_LINE) {

            int breakPoint = getLineBreakPoint(curLineString, MAX_CHARS_PER_LINE) + 1;

            numPrintedLines++;
            if (numPrintedLines > STARTING_LINE_NUMBER) {
                g.drawString(curLineString.substring(0, breakPoint), xOffset, y);
                y += fontHeight;
                if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                    return Printable.PAGE_EXISTS;
            }

            curLineString = curLineString.substring(breakPoint, curLineString.length());

        }

        currentDocLineNumber += 1; // We have printed one more line from the document.

        numPrintedLines++;
        if (numPrintedLines > STARTING_LINE_NUMBER) {
            g.drawString(curLineString, xOffset, y);
            y += fontHeight;
            if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                return Printable.PAGE_EXISTS;
        }

    }

    // Now, the whole document has been "printed."  Decide if this page had any text on it or not.
    if (numPrintedLines > STARTING_LINE_NUMBER)
        return Printable.PAGE_EXISTS;
    return Printable.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);/*  w  ww .java  2s .  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;
}