Example usage for java.awt.print Printable PAGE_EXISTS

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

Introduction

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

Prototype

int PAGE_EXISTS

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

Click Source Link

Document

Returned from #print(Graphics,PageFormat,int) to signify that the requested page was rendered.

Usage

From source file:PrintTest.java

public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
    if (page >= 1)
        return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(pf.getImageableX(), pf.getImageableY());
    g2.draw(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));

    drawPage(g2);/* www  . j a v  a  2  s. c  o  m*/
    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 ww.  ja va  2  s.  co 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:com.floreantpos.jasperreport.engine.print.JRPrinterAWT.java

/**
 *
 *//* w  w  w. java 2  s. c  o m*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (Thread.interrupted()) {
        throw new PrinterException("Current thread interrupted.");
    }

    pageIndex += pageOffset;

    if (pageIndex < 0 || pageIndex >= jasperPrint.getPages().size()) {
        return Printable.NO_SUCH_PAGE;
    }

    try {
        JRGraphics2DExporter exporter = new JRGraphics2DExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, this.jasperPrint);
        exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, graphics);
        exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(pageIndex));
        exporter.exportReport();
    } catch (JRException e) {
        if (log.isDebugEnabled())
            log.debug("Print failed.", e);

        throw new PrinterException(e.getMessage());
    }

    return Printable.PAGE_EXISTS;
}

From source file:BookTest.java

public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
    Graphics2D g2 = (Graphics2D) g;
    if (page > getPageCount(g2, pf))
        return Printable.NO_SUCH_PAGE;
    g2.translate(pf.getImageableX(), pf.getImageableY());

    drawPage(g2, pf, page);/*from  w  w  w . j  ava2s .  c  o m*/
    return Printable.PAGE_EXISTS;
}

From source file:com.alvermont.terraj.util.io.PrintUtilities.java

/**
 * Print the component into a graphics context
 * //from  ww w .j a  v a  2  s.c o m
 * @param g The <code>Graphics</code> object to be used for printing.
 * This should be a <code>Graphics2D</code> instance
 * @param pf The page format to be used
 * @param pageIndex The number of the page being printed
 * @return An indication of whether the page existed. Silly people using
 * magic numbers. Oh well.
 */
public int print(Graphics g, PageFormat pf, int pageIndex) {
    int response = NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    // for faster printing, turn off double buffering
    disableDoubleBuffering(componentToBePrinted);

    Dimension d = componentToBePrinted.getSize(); //get size of document
    double panelWidth = d.width; //width in pixels
    double panelHeight = d.height; //height in pixels
    double pageHeight = pf.getImageableHeight(); //height of printer page
    double pageWidth = pf.getImageableWidth(); //width of printer page
    double scale = pageWidth / panelWidth;

    int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
    // make sure not print empty pages
    if (pageIndex >= totalNumPages) {
        response = NO_SUCH_PAGE;
    } else {
        // shift Graphic to line up with beginning of print-imageable region
        g2.translate(pf.getImageableX(), pf.getImageableY());
        // shift Graphic to line up with beginning of next page to print
        g2.translate(0f, -pageIndex * pageHeight);
        // scale the page so the width fits...
        g2.scale(scale, scale);
        componentToBePrinted.paint(g2); //repaint the page for printing
        enableDoubleBuffering(componentToBePrinted);
        response = Printable.PAGE_EXISTS;
    }

    return response;
}

From source file:com.openbravo.pos.util.JRPrinterAWT411.java

/**
 *
 *//*from w w  w  . jav a  2s . c  o m*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (Thread.currentThread().isInterrupted()) {
        throw new PrinterException("Current thread interrupted.");
    }

    pageIndex += pageOffset;

    if (pageIndex < 0 || pageIndex >= jasperPrint.getPages().size()) {
        return Printable.NO_SUCH_PAGE;
    }

    try {
        JRGraphics2DExporter exporter = new JRGraphics2DExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, this.jasperPrint);
        exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, graphics);
        exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
        exporter.exportReport();
    } catch (JRException e) {
        if (log.isDebugEnabled()) {
            log.debug("Print failed.", e);
        }

        throw new PrinterException(e.getMessage()); //NOPMD
    }

    return Printable.PAGE_EXISTS;
}

From source file:org.fhaes.fhfilechecker.FrameViewOutput.java

@Override
public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {

    try {//from w w  w  .j av  a2  s. c o m
        // For catching IOException
        if (pageIndex != rememberedPageIndex) {
            // First time we've visited this page
            rememberedPageIndex = pageIndex;
            // If encountered EOF on previous page, done
            if (rememberedEOF) {
                return Printable.NO_SUCH_PAGE;
            }
            // Save current position in input file
            rememberedFilePointer = raf.getFilePointer();
        } else {
            raf.seek(rememberedFilePointer);
        }
        g.setColor(Color.black);
        g.setFont(fnt);
        int x = (int) pf.getImageableX() + 10;
        int y = (int) pf.getImageableY() + 12;
        // Title line
        g.drawString("File: " + fileName + ", page: " + (pageIndex + 1), x, y);
        // Generate as many lines as will fit in imageable area
        y += 36;
        while (y + 12 < pf.getImageableY() + pf.getImageableHeight()) {
            String line = raf.readLine();
            if (line == null) {
                rememberedEOF = true;
                break;
            }
            g.drawString(line, x, y);
            y += 12;
        }
        return Printable.PAGE_EXISTS;
    } catch (Exception e) {
        return Printable.NO_SUCH_PAGE;
    }
}

From source file:com.alvermont.terraj.util.io.ImagePrinter.java

/**
 * Render an image for printing.// ww w  .j  a v a 2  s  . co  m
 *
 * @param graphics The graphics context to print on
 * @param pageFormat The page format being used
 * @param pageIndex The page being printed
 * @throws java.awt.print.PrinterException If there is an error in printing
 * @return An indication of the result of page rendering for this page
 */
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    final Graphics2D g2 = (Graphics2D) graphics;

    // we only expect to be printing 1 page as the image is scaled
    if (pageIndex >= 1) {
        return Printable.NO_SUCH_PAGE;
    }

    // translate the coordinate system to match up the image with 
    // the printable area
    g2.translate(getFormat().getImageableX(), pageFormat.getImageableY());

    final Rectangle componentBounds = new Rectangle(getImage().getWidth(), getImage().getHeight());
    g2.translate(-componentBounds.x, -componentBounds.y);

    // scale the image to fit
    scaleToFit(true);
    g2.scale(getScaleX(), getScaleY());

    // render the image
    g2.drawImage(getImage(), null, 0, 0);

    // done
    return Printable.PAGE_EXISTS;
}

From source file:com.openbravo.pos.util.JRPrinterAWT.java

/**
 *
 */// w  ww.j  a  va 2s  . com
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (Thread.currentThread().isInterrupted()) {
        throw new PrinterException("Current thread interrupted.");
    }

    pageIndex += pageOffset;

    if (pageIndex < 0 || pageIndex >= jasperPrint.getPages().size()) {
        return Printable.NO_SUCH_PAGE;
    }

    try {
        JRGraphics2DExporter exporter = new JRGraphics2DExporter(jasperReportsContext);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, this.jasperPrint);
        exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, graphics);
        exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
        exporter.exportReport();
    } catch (JRException e) {
        if (log.isDebugEnabled()) {
            log.debug("Print failed.", e);
        }

        throw new PrinterException(e.getMessage()); //NOPMD
    }

    return Printable.PAGE_EXISTS;
}

From source file:com.l3.info.magenda.emplois_du_temps.EmploisDuTemps.java

@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    // Par dfaut, retourne NO_SUCH_PAGE => la page n'existe pas
    int code_retour = Printable.NO_SUCH_PAGE;
    System.out.println(pageIndex);
    // Rcuprer l'ensemble des cls de la liste
    for (Semaine sem : value) {
        //sem.get_nbr_page();
    }/*from  ww  w  .j  a  v  a  2s. c  o m*/
    if (value.size() > pageIndex) {
        value.get(pageIndex).paint(graphics);
        // La page est valide
        code_retour = Printable.PAGE_EXISTS;
    }
    // Rcupre la dimension de la zone imprimable
    //double xLeft  = pageFormat.getImageableX();
    //double yTop   = pageFormat.getImageableY();
    //double width  = pageFormat.getImageableWidth();
    //double height = pageFormat.getImageableHeight();

    return code_retour;
}