Search in sources :

Example 6 with Printable

use of java.awt.print.Printable in project cytoscape-api by cytoscape.

the class AbstractRenderingEngineTest method testCreatePribtable.

@Test
public void testCreatePribtable() {
    assertNotNull(engine);
    final Printable printable = engine.createPrintable();
    assertNotNull(printable);
}
Also used : Printable(java.awt.print.Printable) Test(org.junit.Test)

Example 7 with Printable

use of java.awt.print.Printable in project jdk8u_jdk by JetBrains.

the class JTextComponent method print.

/**
     * Prints the content of this {@code JTextComponent}. Note: this method
     * blocks until printing is done.
     *
     * <p>
     * Page header and footer text can be added to the output by providing
     * {@code MessageFormat} arguments. The printing code requests
     * {@code Strings} from the formats, providing a single item which may be
     * included in the formatted string: an {@code Integer} representing the
     * current page number.
     *
     * <p>
     * {@code showPrintDialog boolean} parameter allows you to specify whether
     * a print dialog is displayed to the user. When it is, the user
     * may use the dialog to change printing attributes or even cancel the
     * print.
     *
     * <p>
     * {@code service} allows you to provide the initial
     * {@code PrintService} for the print dialog, or to specify
     * {@code PrintService} to print to when the dialog is not shown.
     *
     * <p>
     * {@code attributes} can be used to provide the
     * initial values for the print dialog, or to supply any needed
     * attributes when the dialog is not shown. {@code attributes} can
     * be used to control how the job will print, for example
     * <i>duplex</i> or <i>single-sided</i>.
     *
     * <p>
     * {@code interactive boolean} parameter allows you to specify
     * whether to perform printing in <i>interactive</i>
     * mode. If {@code true}, a progress dialog, with an abort option,
     * is displayed for the duration of printing.  This dialog is
     * <i>modal</i> when {@code print} is invoked on the <i>Event Dispatch
     * Thread</i> and <i>non-modal</i> otherwise. <b>Warning</b>:
     * calling this method on the <i>Event Dispatch Thread</i> with {@code
     * interactive false} blocks <i>all</i> events, including repaints, from
     * being processed until printing is complete. It is only
     * recommended when printing from an application with no
     * visible GUI.
     *
     * <p>
     * Note: In <i>headless</i> mode, {@code showPrintDialog} and
     * {@code interactive} parameters are ignored and no dialogs are
     * shown.
     *
     * <p>
     * This method ensures the {@code document} is not mutated during printing.
     * To indicate it visually, {@code setEnabled(false)} is set for the
     * duration of printing.
     *
     * <p>
     * This method uses {@link #getPrintable} to render document content.
     *
     * <p>
     * This method is thread-safe, although most Swing methods are not. Please
     * see <A
     * HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">
     * Concurrency in Swing</A> for more information.
     *
     * <p>
     * <b>Sample Usage</b>. This code snippet shows a cross-platform print
     * dialog and then prints the {@code JTextComponent} in <i>interactive</i> mode
     * unless the user cancels the dialog:
     *
     * <pre>
     * textComponent.print(new MessageFormat(&quot;My text component header&quot;),
     *     new MessageFormat(&quot;Footer. Page - {0}&quot;), true, null, null, true);
     * </pre>
     * <p>
     * Executing this code off the <i>Event Dispatch Thread</i>
     * performs printing on the <i>background</i>.
     * The following pattern might be used for <i>background</i>
     * printing:
     * <pre>
     *     FutureTask&lt;Boolean&gt; future =
     *         new FutureTask&lt;Boolean&gt;(
     *             new Callable&lt;Boolean&gt;() {
     *                 public Boolean call() {
     *                     return textComponent.print(.....);
     *                 }
     *             });
     *     executor.execute(future);
     * </pre>
     *
     * @param headerFormat the text, in {@code MessageFormat}, to be
     *        used as the header, or {@code null} for no header
     * @param footerFormat the text, in {@code MessageFormat}, to be
     *        used as the footer, or {@code null} for no footer
     * @param showPrintDialog {@code true} to display a print dialog,
     *        {@code false} otherwise
     * @param service initial {@code PrintService}, or {@code null} for the
     *        default
     * @param attributes the job attributes to be applied to the print job, or
     *        {@code null} for none
     * @param interactive whether to print in an interactive mode
     * @return {@code true}, unless printing is canceled by the user
     * @throws PrinterException if an error in the print system causes the job
     *         to be aborted
     * @throws SecurityException if this thread is not allowed to
     *                           initiate a print job request
     *
     * @see #getPrintable
     * @see java.text.MessageFormat
     * @see java.awt.GraphicsEnvironment#isHeadless
     * @see java.util.concurrent.FutureTask
     *
     * @since 1.6
     */
public boolean print(final MessageFormat headerFormat, final MessageFormat footerFormat, final boolean showPrintDialog, final PrintService service, final PrintRequestAttributeSet attributes, final boolean interactive) throws PrinterException {
    final PrinterJob job = PrinterJob.getPrinterJob();
    final Printable printable;
    final PrintingStatus printingStatus;
    final boolean isHeadless = GraphicsEnvironment.isHeadless();
    final boolean isEventDispatchThread = SwingUtilities.isEventDispatchThread();
    final Printable textPrintable = getPrintable(headerFormat, footerFormat);
    if (interactive && !isHeadless) {
        printingStatus = PrintingStatus.createPrintingStatus(this, job);
        printable = printingStatus.createNotificationPrintable(textPrintable);
    } else {
        printingStatus = null;
        printable = textPrintable;
    }
    if (service != null) {
        job.setPrintService(service);
    }
    job.setPrintable(printable);
    final PrintRequestAttributeSet attr = (attributes == null) ? new HashPrintRequestAttributeSet() : attributes;
    if (showPrintDialog && !isHeadless && !job.printDialog(attr)) {
        return false;
    }
    /*
         * there are three cases for printing:
         * 1. print non interactively (! interactive || isHeadless)
         * 2. print interactively off EDT
         * 3. print interactively on EDT
         *
         * 1 and 2 prints on the current thread (3 prints on another thread)
         * 2 and 3 deal with PrintingStatusDialog
         */
    final Callable<Object> doPrint = new Callable<Object>() {

        public Object call() throws Exception {
            try {
                job.print(attr);
            } finally {
                if (printingStatus != null) {
                    printingStatus.dispose();
                }
            }
            return null;
        }
    };
    final FutureTask<Object> futurePrinting = new FutureTask<Object>(doPrint);
    final Runnable runnablePrinting = new Runnable() {

        public void run() {
            //disable component
            boolean wasEnabled = false;
            if (isEventDispatchThread) {
                if (isEnabled()) {
                    wasEnabled = true;
                    setEnabled(false);
                }
            } else {
                try {
                    wasEnabled = SwingUtilities2.submit(new Callable<Boolean>() {

                        public Boolean call() throws Exception {
                            boolean rv = isEnabled();
                            if (rv) {
                                setEnabled(false);
                            }
                            return rv;
                        }
                    }).get();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof Error) {
                        throw (Error) cause;
                    }
                    if (cause instanceof RuntimeException) {
                        throw (RuntimeException) cause;
                    }
                    throw new AssertionError(cause);
                }
            }
            getDocument().render(futurePrinting);
            //enable component
            if (wasEnabled) {
                if (isEventDispatchThread) {
                    setEnabled(true);
                } else {
                    try {
                        SwingUtilities2.submit(new Runnable() {

                            public void run() {
                                setEnabled(true);
                            }
                        }, null).get();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } catch (ExecutionException e) {
                        Throwable cause = e.getCause();
                        if (cause instanceof Error) {
                            throw (Error) cause;
                        }
                        if (cause instanceof RuntimeException) {
                            throw (RuntimeException) cause;
                        }
                        throw new AssertionError(cause);
                    }
                }
            }
        }
    };
    if (!interactive || isHeadless) {
        runnablePrinting.run();
    } else {
        if (isEventDispatchThread) {
            (new Thread(runnablePrinting)).start();
            printingStatus.showModal(true);
        } else {
            printingStatus.showModal(false);
            runnablePrinting.run();
        }
    }
    //dialog is hidden if needed.
    try {
        futurePrinting.get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof PrinterAbortException) {
            if (printingStatus != null && printingStatus.isAborted()) {
                return false;
            } else {
                throw (PrinterAbortException) cause;
            }
        } else if (cause instanceof PrinterException) {
            throw (PrinterException) cause;
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            throw new AssertionError(cause);
        }
    }
    return true;
}
Also used : PrinterException(java.awt.print.PrinterException) PrinterException(java.awt.print.PrinterException) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) TextComponentPrintable(sun.swing.text.TextComponentPrintable) Printable(java.awt.print.Printable) PrintingStatus(sun.swing.PrintingStatus)

Example 8 with Printable

use of java.awt.print.Printable in project jdk8u_jdk by JetBrains.

the class RasterPrinterJob method setAttributes.

/* subclasses may need to pull extra information out of the attribute set
     * They can override this method & call super.setAttributes()
     */
protected void setAttributes(PrintRequestAttributeSet attributes) throws PrinterException {
    /*  reset all values to defaults */
    setCollated(false);
    sidesAttr = null;
    pageRangesAttr = null;
    copiesAttr = 0;
    jobNameAttr = null;
    userNameAttr = null;
    destinationAttr = null;
    collateAttReq = false;
    PrintService service = getPrintService();
    if (attributes == null || service == null) {
        return;
    }
    boolean fidelity = false;
    Fidelity attrFidelity = (Fidelity) attributes.get(Fidelity.class);
    if (attrFidelity != null && attrFidelity == Fidelity.FIDELITY_TRUE) {
        fidelity = true;
    }
    if (fidelity == true) {
        AttributeSet unsupported = service.getUnsupportedAttributes(DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributes);
        if (unsupported != null) {
            throw new PrinterException("Fidelity cannot be satisfied");
        }
    }
    /*
         * Since we have verified supported values if fidelity is true,
         * we can either ignore unsupported values, or substitute a
         * reasonable alternative
         */
    SheetCollate collateAttr = (SheetCollate) attributes.get(SheetCollate.class);
    if (isSupportedValue(collateAttr, attributes)) {
        setCollated(collateAttr == SheetCollate.COLLATED);
    }
    sidesAttr = (Sides) attributes.get(Sides.class);
    if (!isSupportedValue(sidesAttr, attributes)) {
        sidesAttr = Sides.ONE_SIDED;
    }
    pageRangesAttr = (PageRanges) attributes.get(PageRanges.class);
    if (!isSupportedValue(pageRangesAttr, attributes)) {
        pageRangesAttr = null;
    } else {
        if ((SunPageSelection) attributes.get(SunPageSelection.class) == SunPageSelection.RANGE) {
            // get to, from, min, max page ranges
            int[][] range = pageRangesAttr.getMembers();
            // setPageRanges uses 0-based indexing so we subtract 1
            setPageRange(range[0][0] - 1, range[0][1] - 1);
        } else {
            setPageRange(-1, -1);
        }
    }
    Copies copies = (Copies) attributes.get(Copies.class);
    if (isSupportedValue(copies, attributes) || (!fidelity && copies != null)) {
        copiesAttr = copies.getValue();
        setCopies(copiesAttr);
    } else {
        copiesAttr = getCopies();
    }
    Destination destination = (Destination) attributes.get(Destination.class);
    if (isSupportedValue(destination, attributes)) {
        try {
            // Old code (new File(destination.getURI())).getPath()
            // would generate a "URI is not hierarchical" IAE
            // for "file:out.prn" so we use getSchemeSpecificPart instead
            destinationAttr = "" + new File(destination.getURI().getSchemeSpecificPart());
        } catch (Exception e) {
            // paranoid exception
            Destination defaultDest = (Destination) service.getDefaultAttributeValue(Destination.class);
            if (defaultDest != null) {
                destinationAttr = "" + new File(defaultDest.getURI().getSchemeSpecificPart());
            }
        }
    }
    JobSheets jobSheets = (JobSheets) attributes.get(JobSheets.class);
    if (jobSheets != null) {
        noJobSheet = jobSheets == JobSheets.NONE;
    }
    JobName jobName = (JobName) attributes.get(JobName.class);
    if (isSupportedValue(jobName, attributes) || (!fidelity && jobName != null)) {
        jobNameAttr = jobName.getValue();
        setJobName(jobNameAttr);
    } else {
        jobNameAttr = getJobName();
    }
    RequestingUserName userName = (RequestingUserName) attributes.get(RequestingUserName.class);
    if (isSupportedValue(userName, attributes) || (!fidelity && userName != null)) {
        userNameAttr = userName.getValue();
    } else {
        try {
            userNameAttr = getUserName();
        } catch (SecurityException e) {
            userNameAttr = "";
        }
    }
    /* OpenBook is used internally only when app uses Printable.
         * This is the case when we use the values from the attribute set.
         */
    Media media = (Media) attributes.get(Media.class);
    OrientationRequested orientReq = (OrientationRequested) attributes.get(OrientationRequested.class);
    MediaPrintableArea mpa = (MediaPrintableArea) attributes.get(MediaPrintableArea.class);
    if ((orientReq != null || media != null || mpa != null) && getPageable() instanceof OpenBook) {
        /* We could almost(!) use PrinterJob.getPageFormat() except
             * here we need to start with the PageFormat from the OpenBook :
             */
        Pageable pageable = getPageable();
        Printable printable = pageable.getPrintable(0);
        PageFormat pf = (PageFormat) pageable.getPageFormat(0).clone();
        Paper paper = pf.getPaper();
        /* If there's a media but no media printable area, we can try
             * to retrieve the default value for mpa and use that.
             */
        if (mpa == null && media != null && service.isAttributeCategorySupported(MediaPrintableArea.class)) {
            Object mpaVals = service.getSupportedAttributeValues(MediaPrintableArea.class, null, attributes);
            if (mpaVals instanceof MediaPrintableArea[] && ((MediaPrintableArea[]) mpaVals).length > 0) {
                mpa = ((MediaPrintableArea[]) mpaVals)[0];
            }
        }
        if (isSupportedValue(orientReq, attributes) || (!fidelity && orientReq != null)) {
            int orient;
            if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) {
                orient = PageFormat.REVERSE_LANDSCAPE;
            } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) {
                orient = PageFormat.LANDSCAPE;
            } else {
                orient = PageFormat.PORTRAIT;
            }
            pf.setOrientation(orient);
        }
        if (isSupportedValue(media, attributes) || (!fidelity && media != null)) {
            if (media instanceof MediaSizeName) {
                MediaSizeName msn = (MediaSizeName) media;
                MediaSize msz = MediaSize.getMediaSizeForName(msn);
                if (msz != null) {
                    float paperWid = msz.getX(MediaSize.INCH) * 72.0f;
                    float paperHgt = msz.getY(MediaSize.INCH) * 72.0f;
                    paper.setSize(paperWid, paperHgt);
                    if (mpa == null) {
                        paper.setImageableArea(72.0, 72.0, paperWid - 144.0, paperHgt - 144.0);
                    }
                }
            }
        }
        if (isSupportedValue(mpa, attributes) || (!fidelity && mpa != null)) {
            float[] printableArea = mpa.getPrintableArea(MediaPrintableArea.INCH);
            for (int i = 0; i < printableArea.length; i++) {
                printableArea[i] = printableArea[i] * 72.0f;
            }
            paper.setImageableArea(printableArea[0], printableArea[1], printableArea[2], printableArea[3]);
        }
        pf.setPaper(paper);
        pf = validatePage(pf);
        setPrintable(printable, pf);
    } else {
        // for AWT where pageable is not an instance of OpenBook,
        // we need to save paper info
        this.attributes = attributes;
    }
}
Also used : Fidelity(javax.print.attribute.standard.Fidelity) Destination(javax.print.attribute.standard.Destination) JobName(javax.print.attribute.standard.JobName) PrinterException(java.awt.print.PrinterException) OrientationRequested(javax.print.attribute.standard.OrientationRequested) PrintService(javax.print.PrintService) StreamPrintService(javax.print.StreamPrintService) MediaPrintableArea(javax.print.attribute.standard.MediaPrintableArea) PageFormat(java.awt.print.PageFormat) Pageable(java.awt.print.Pageable) Copies(javax.print.attribute.standard.Copies) MediaSize(javax.print.attribute.standard.MediaSize) MediaSizeName(javax.print.attribute.standard.MediaSizeName) Media(javax.print.attribute.standard.Media) JobSheets(javax.print.attribute.standard.JobSheets) PrinterAbortException(java.awt.print.PrinterAbortException) HeadlessException(java.awt.HeadlessException) PrintException(javax.print.PrintException) PrinterException(java.awt.print.PrinterException) IOException(java.io.IOException) AttributeSet(javax.print.attribute.AttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) SheetCollate(javax.print.attribute.standard.SheetCollate) RequestingUserName(javax.print.attribute.standard.RequestingUserName) Paper(java.awt.print.Paper) Printable(java.awt.print.Printable) File(java.io.File)

Example 9 with Printable

use of java.awt.print.Printable in project jdk8u_jdk by JetBrains.

the class WPathGraphics method redrawRegion.

/**
     * Have the printing application redraw everything that falls
     * within the page bounds defined by <code>region</code>.
     */
@Override
public void redrawRegion(Rectangle2D region, double scaleX, double scaleY, Shape savedClip, AffineTransform savedTransform) throws PrinterException {
    WPrinterJob wPrinterJob = (WPrinterJob) getPrinterJob();
    Printable painter = getPrintable();
    PageFormat pageFormat = getPageFormat();
    int pageIndex = getPageIndex();
    /* Create a buffered image big enough to hold the portion
         * of the source image being printed.
         */
    BufferedImage deepImage = new BufferedImage((int) region.getWidth(), (int) region.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    /* Get a graphics for the application to render into.
         * We initialize the buffer to white in order to
         * match the paper and then we shift the BufferedImage
         * so that it covers the area on the page where the
         * caller's Image will be drawn.
         */
    Graphics2D g = deepImage.createGraphics();
    ProxyGraphics2D proxy = new ProxyGraphics2D(g, wPrinterJob);
    proxy.setColor(Color.white);
    proxy.fillRect(0, 0, deepImage.getWidth(), deepImage.getHeight());
    proxy.clipRect(0, 0, deepImage.getWidth(), deepImage.getHeight());
    proxy.translate(-region.getX(), -region.getY());
    /* Calculate the resolution of the source image.
         */
    float sourceResX = (float) (wPrinterJob.getXRes() / scaleX);
    float sourceResY = (float) (wPrinterJob.getYRes() / scaleY);
    /* The application expects to see user space at 72 dpi.
         * so change user space from image source resolution to
         *  72 dpi.
         */
    proxy.scale(sourceResX / DEFAULT_USER_RES, sourceResY / DEFAULT_USER_RES);
    proxy.translate(-wPrinterJob.getPhysicalPrintableX(pageFormat.getPaper()) / wPrinterJob.getXRes() * DEFAULT_USER_RES, -wPrinterJob.getPhysicalPrintableY(pageFormat.getPaper()) / wPrinterJob.getYRes() * DEFAULT_USER_RES);
    /* NB User space now has to be at 72 dpi for this calc to be correct */
    proxy.transform(new AffineTransform(getPageFormat().getMatrix()));
    proxy.setPaint(Color.black);
    painter.print(proxy, pageFormat, pageIndex);
    g.dispose();
    /* We need to set the device clip using saved information.
         * savedClip intersects the user clip with a clip that restricts
         * the GDI rendered area of our BufferedImage to that which
         * may correspond to a rotate or shear.
         * The saved device transform is needed as the current transform
         * is not likely to be the same.
         */
    if (savedClip != null) {
        deviceClip(savedClip.getPathIterator(savedTransform));
    }
    /* Scale the bounding rectangle by the scale transform.
         * Because the scaling transform has only x and y
         * scaling components it is equivalent to multiplying
         * the x components of the bounding rectangle by
         * the x scaling factor and to multiplying the y components
         * by the y scaling factor.
         */
    Rectangle2D.Float scaledBounds = new Rectangle2D.Float((float) (region.getX() * scaleX), (float) (region.getY() * scaleY), (float) (region.getWidth() * scaleX), (float) (region.getHeight() * scaleY));
    /* Pull the raster data from the buffered image
         * and pass it along to GDI.
         */
    ByteComponentRaster tile = (ByteComponentRaster) deepImage.getRaster();
    wPrinterJob.drawImage3ByteBGR(tile.getDataStorage(), scaledBounds.x, scaledBounds.y, scaledBounds.width, scaledBounds.height, 0f, 0f, deepImage.getWidth(), deepImage.getHeight());
}
Also used : Rectangle2D(java.awt.geom.Rectangle2D) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) ProxyGraphics2D(sun.print.ProxyGraphics2D) PageFormat(java.awt.print.PageFormat) ByteComponentRaster(sun.awt.image.ByteComponentRaster) AffineTransform(java.awt.geom.AffineTransform) Printable(java.awt.print.Printable) ProxyGraphics2D(sun.print.ProxyGraphics2D)

Example 10 with Printable

use of java.awt.print.Printable in project jdk8u_jdk by JetBrains.

the class ImageableAreaTest method printWithJavaPrintDialog.

private static void printWithJavaPrintDialog() {
    final JTable table = createAuthorTable(42);
    Printable printable = table.getPrintable(JTable.PrintMode.NORMAL, new MessageFormat("Author Table"), new MessageFormat("Page - {0}"));
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);
    boolean printAccepted = job.printDialog();
    if (printAccepted) {
        try {
            job.print();
            closeFrame();
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : MessageFormat(java.text.MessageFormat) JTable(javax.swing.JTable) Printable(java.awt.print.Printable) PrinterException(java.awt.print.PrinterException) PrinterJob(java.awt.print.PrinterJob)

Aggregations

Printable (java.awt.print.Printable)11 PageFormat (java.awt.print.PageFormat)6 PrinterException (java.awt.print.PrinterException)6 BufferedImage (java.awt.image.BufferedImage)4 PrintRequestAttributeSet (javax.print.attribute.PrintRequestAttributeSet)4 Graphics2D (java.awt.Graphics2D)3 AffineTransform (java.awt.geom.AffineTransform)3 Rectangle2D (java.awt.geom.Rectangle2D)3 PrinterJob (java.awt.print.PrinterJob)3 HashPrintRequestAttributeSet (javax.print.attribute.HashPrintRequestAttributeSet)3 HeadlessException (java.awt.HeadlessException)2 Paper (java.awt.print.Paper)2 PrinterAbortException (java.awt.print.PrinterAbortException)2 File (java.io.File)2 IOException (java.io.IOException)2 MessageFormat (java.text.MessageFormat)2 PrintException (javax.print.PrintException)2 PrintService (javax.print.PrintService)2 Copies (javax.print.attribute.standard.Copies)2 MediaPrintableArea (javax.print.attribute.standard.MediaPrintableArea)2