Search in sources :

Example 16 with PrinterException

use of java.awt.print.PrinterException in project chuidiang-ejemplos by chuidiang.

the class printJobExample method main.

public static void main(String[] args) {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(new Printable() {

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            return 0;
        }
    });
    boolean top = job.printDialog();
}
Also used : PageFormat(java.awt.print.PageFormat) Printable(java.awt.print.Printable) PrinterException(java.awt.print.PrinterException) PrinterJob(java.awt.print.PrinterJob)

Example 17 with PrinterException

use of java.awt.print.PrinterException in project intellij-community by JetBrains.

the class PrintManager method executePrint.

public static void executePrint(DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return;
    PsiDirectory psiDirectory = null;
    PsiElement psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
    if (psiElement instanceof PsiDirectory) {
        psiDirectory = (PsiDirectory) psiElement;
    }
    PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(dataContext);
    String shortFileName = null;
    String directoryName = null;
    if (psiFile != null || psiDirectory != null) {
        if (psiFile != null) {
            shortFileName = psiFile.getName();
            if (psiDirectory == null) {
                psiDirectory = psiFile.getContainingDirectory();
            }
        }
        if (psiDirectory != null) {
            directoryName = psiDirectory.getVirtualFile().getPresentableUrl();
        }
    }
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    String text = null;
    if (editor != null) {
        if (editor.getSelectionModel().hasSelection()) {
            text = CodeEditorBundle.message("print.selected.text.radio");
        } else {
            text = psiFile == null ? "Console text" : null;
        }
    }
    List<PsiFile> psiFiles = getSelectedPsiFiles(dataContext);
    PrintDialog printDialog = new PrintDialog(shortFileName, directoryName, text, psiFiles.size(), project);
    printDialog.reset();
    if (!printDialog.showAndGet()) {
        return;
    }
    printDialog.apply();
    final PageFormat pageFormat = createPageFormat();
    final BasePainter painter;
    PrintSettings printSettings = PrintSettings.getInstance();
    if (printSettings.getPrintScope() == PrintSettings.PRINT_FILE && psiFiles.size() > 1) {
        painter = new MultiFilePainter(psiFiles, printSettings.EVEN_NUMBER_OF_PAGES);
    } else if (printSettings.getPrintScope() == PrintSettings.PRINT_DIRECTORY) {
        List<PsiFile> filesList = ContainerUtil.newArrayList();
        boolean isRecursive = printSettings.isIncludeSubdirectories();
        addToPsiFileList(psiDirectory, filesList, isRecursive);
        painter = new MultiFilePainter(filesList, printSettings.EVEN_NUMBER_OF_PAGES);
    } else {
        if (psiFile == null && editor == null)
            return;
        TextPainter textPainter = psiFile != null ? initTextPainter(psiFile) : initTextPainter((DocumentEx) editor.getDocument(), project);
        if (textPainter == null)
            return;
        if (printSettings.getPrintScope() == PrintSettings.PRINT_SELECTED_TEXT && editor != null && editor.getSelectionModel().hasSelection()) {
            textPainter.setSegment(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd());
        }
        painter = textPainter;
    }
    final PrinterJob printerJob = PrinterJob.getPrinterJob();
    try {
        printerJob.setPrintable(painter, pageFormat);
        if (!printerJob.printDialog()) {
            return;
        }
    } catch (Exception e) {
        LOG.warn(e);
    }
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    ProgressManager.getInstance().run(new Task.Backgroundable(project, CodeEditorBundle.message("print.progress"), true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            try {
                painter.setProgress(indicator);
                printerJob.print();
            } catch (ProcessCanceledException e) {
                LOG.info("Cancelled");
                printerJob.cancel();
            } catch (PrinterException e) {
                LOG.warn(e);
                String message = ObjectUtils.notNull(e.getMessage(), e.getClass().getName());
                Notifications.Bus.notify(new Notification("Print", CommonBundle.getErrorTitle(), message, NotificationType.ERROR));
            } catch (Exception e) {
                LOG.error(e);
            } finally {
                painter.dispose();
            }
        }
    });
}
Also used : PrinterException(java.awt.print.PrinterException) PrinterException(java.awt.print.PrinterException) Notification(com.intellij.notification.Notification) PrinterJob(java.awt.print.PrinterJob) Project(com.intellij.openapi.project.Project) PageFormat(java.awt.print.PageFormat) ArrayList(java.util.ArrayList) List(java.util.List) Editor(com.intellij.openapi.editor.Editor)

Example 18 with PrinterException

use of java.awt.print.PrinterException 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 19 with PrinterException

use of java.awt.print.PrinterException 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 20 with PrinterException

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

the class PrintJob2D method copyAttributes.

/* From JobAttributes we will copy job name and duplex printing
     * and destination.
     * The majority of the rest of the attributes are reflected
     * attributes.
     *
     * From PageAttributes we copy color, media size, orientation,
     * origin type, resolution and print quality.
     * We use the media, orientation in creating the page format, and
     * the origin type to set its imageable area.
     *
     * REMIND: Interpretation of resolution, additional media sizes.
     */
private void copyAttributes(PrintService printServ) {
    attributes = new HashPrintRequestAttributeSet();
    attributes.add(new JobName(docTitle, null));
    PrintService pServ = printServ;
    String printerName = jobAttributes.getPrinter();
    if (printerName != null && printerName != "" && !printerName.equals(pServ.getName())) {
        // Search for the given printerName in the list of PrintServices
        PrintService[] services = PrinterJob.lookupPrintServices();
        try {
            for (int i = 0; i < services.length; i++) {
                if (printerName.equals(services[i].getName())) {
                    printerJob.setPrintService(services[i]);
                    pServ = services[i];
                    break;
                }
            }
        } catch (PrinterException pe) {
        }
    }
    DestinationType dest = jobAttributes.getDestination();
    if (dest == DestinationType.FILE && pServ.isAttributeCategorySupported(Destination.class)) {
        String fileName = jobAttributes.getFileName();
        Destination defaultDest;
        if (fileName == null && (defaultDest = (Destination) pServ.getDefaultAttributeValue(Destination.class)) != null) {
            attributes.add(defaultDest);
        } else {
            URI uri = null;
            try {
                if (fileName != null) {
                    if (fileName.equals("")) {
                        fileName = ".";
                    }
                } else {
                    // defaultDest should not be null.  The following code
                    // is only added to safeguard against a possible
                    // buggy implementation of a PrintService having a
                    // null default Destination.
                    fileName = "out.prn";
                }
                uri = (new File(fileName)).toURI();
            } catch (SecurityException se) {
                try {
                    // '\\' file separator is illegal character in opaque
                    // part and causes URISyntaxException, so we replace
                    // it with '/'
                    fileName = fileName.replace('\\', '/');
                    uri = new URI("file:" + fileName);
                } catch (URISyntaxException e) {
                }
            }
            if (uri != null) {
                attributes.add(new Destination(uri));
            }
        }
    }
    attributes.add(new SunMinMaxPage(jobAttributes.getMinPage(), jobAttributes.getMaxPage()));
    SidesType sType = jobAttributes.getSides();
    if (sType == SidesType.TWO_SIDED_LONG_EDGE) {
        attributes.add(Sides.TWO_SIDED_LONG_EDGE);
    } else if (sType == SidesType.TWO_SIDED_SHORT_EDGE) {
        attributes.add(Sides.TWO_SIDED_SHORT_EDGE);
    } else if (sType == SidesType.ONE_SIDED) {
        attributes.add(Sides.ONE_SIDED);
    }
    MultipleDocumentHandlingType hType = jobAttributes.getMultipleDocumentHandling();
    if (hType == MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_COLLATED_COPIES) {
        attributes.add(SheetCollate.COLLATED);
    } else {
        attributes.add(SheetCollate.UNCOLLATED);
    }
    attributes.add(new Copies(jobAttributes.getCopies()));
    attributes.add(new PageRanges(jobAttributes.getFromPage(), jobAttributes.getToPage()));
    if (pageAttributes.getColor() == ColorType.COLOR) {
        attributes.add(Chromaticity.COLOR);
    } else {
        attributes.add(Chromaticity.MONOCHROME);
    }
    pageFormat = printerJob.defaultPage();
    if (pageAttributes.getOrientationRequested() == OrientationRequestedType.LANDSCAPE) {
        pageFormat.setOrientation(PageFormat.LANDSCAPE);
        attributes.add(OrientationRequested.LANDSCAPE);
    } else {
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        attributes.add(OrientationRequested.PORTRAIT);
    }
    MediaType media = pageAttributes.getMedia();
    MediaSizeName msn = mapMedia(media);
    if (msn != null) {
        attributes.add(msn);
    }
    PrintQualityType qType = pageAttributes.getPrintQuality();
    if (qType == PrintQualityType.DRAFT) {
        attributes.add(PrintQuality.DRAFT);
    } else if (qType == PrintQualityType.NORMAL) {
        attributes.add(PrintQuality.NORMAL);
    } else if (qType == PrintQualityType.HIGH) {
        attributes.add(PrintQuality.HIGH);
    }
}
Also used : Destination(javax.print.attribute.standard.Destination) PageRanges(javax.print.attribute.standard.PageRanges) MediaSizeName(javax.print.attribute.standard.MediaSizeName) JobName(javax.print.attribute.standard.JobName) PrinterException(java.awt.print.PrinterException) URISyntaxException(java.net.URISyntaxException) SunMinMaxPage(sun.print.SunMinMaxPage) URI(java.net.URI) PrintService(javax.print.PrintService) Copies(javax.print.attribute.standard.Copies) File(java.io.File) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet)

Aggregations

PrinterException (java.awt.print.PrinterException)27 PrinterJob (java.awt.print.PrinterJob)15 PageFormat (java.awt.print.PageFormat)11 PrintService (javax.print.PrintService)8 Printable (java.awt.print.Printable)5 StreamPrintService (javax.print.StreamPrintService)5 HashPrintRequestAttributeSet (javax.print.attribute.HashPrintRequestAttributeSet)5 HeadlessException (java.awt.HeadlessException)4 File (java.io.File)4 IOException (java.io.IOException)4 PrintRequestAttributeSet (javax.print.attribute.PrintRequestAttributeSet)4 Container (java.awt.Container)3 ActionEvent (java.awt.event.ActionEvent)3 Paper (java.awt.print.Paper)3 PrintException (javax.print.PrintException)3 AbstractAction (javax.swing.AbstractAction)3 JButton (javax.swing.JButton)3 JFrame (javax.swing.JFrame)3 Graphics2D (java.awt.Graphics2D)2 Rectangle (java.awt.Rectangle)2