use of javax.print.attribute.PrintRequestAttributeSet 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("My text component header"),
* new MessageFormat("Footer. Page - {0}"), 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<Boolean> future =
* new FutureTask<Boolean>(
* new Callable<Boolean>() {
* 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;
}
use of javax.print.attribute.PrintRequestAttributeSet in project jdk8u_jdk by JetBrains.
the class RasterPrinterJob method printDialog.
/**
* Presents the user a dialog for changing properties of the
* print job interactively.
* @returns false if the user cancels the dialog and
* true otherwise.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public boolean printDialog() throws HeadlessException {
if (GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(new Copies(getCopies()));
attributes.add(new JobName(getJobName(), null));
boolean doPrint = printDialog(attributes);
if (doPrint) {
JobName jobName = (JobName) attributes.get(JobName.class);
if (jobName != null) {
setJobName(jobName.getValue());
}
Copies copies = (Copies) attributes.get(Copies.class);
if (copies != null) {
setCopies(copies.getValue());
}
Destination dest = (Destination) attributes.get(Destination.class);
if (dest != null) {
try {
mDestType = RasterPrinterJob.FILE;
mDestination = (new File(dest.getURI())).getPath();
} catch (Exception e) {
mDestination = "out.prn";
PrintService ps = getPrintService();
if (ps != null) {
Destination defaultDest = (Destination) ps.getDefaultAttributeValue(Destination.class);
if (defaultDest != null) {
mDestination = (new File(defaultDest.getURI())).getPath();
}
}
}
} else {
mDestType = RasterPrinterJob.PRINTER;
PrintService ps = getPrintService();
if (ps != null) {
mDestination = ps.getName();
}
}
}
return doPrint;
}
use of javax.print.attribute.PrintRequestAttributeSet 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;
}
}
use of javax.print.attribute.PrintRequestAttributeSet in project jdk8u_jdk by JetBrains.
the class RasterPrinterJob method pageDialog.
/**
* return a PageFormat corresponding to the updated attributes,
* or null if the user cancelled the dialog.
*/
public PageFormat pageDialog(final PrintRequestAttributeSet attributes) throws HeadlessException {
if (GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
DialogTypeSelection dlg = (DialogTypeSelection) attributes.get(DialogTypeSelection.class);
// Check for native, note that default dialog is COMMON.
if (dlg == DialogTypeSelection.NATIVE) {
PrintService pservice = getPrintService();
PageFormat pageFrmAttrib = attributeToPageFormat(pservice, attributes);
setParentWindowID(attributes);
PageFormat page = pageDialog(pageFrmAttrib);
clearParentWindowID();
// page object and as per spec, we should return null in that case.
if (page == pageFrmAttrib) {
return null;
}
updateAttributesWithPageFormat(pservice, page, attributes);
return page;
}
final GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
Rectangle bounds = gc.getBounds();
int x = bounds.x + bounds.width / 3;
int y = bounds.y + bounds.height / 3;
PrintService service = (PrintService) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
PrintService service = getPrintService();
if (service == null) {
ServiceDialog.showNoPrintService(gc);
return null;
}
return service;
}
});
if (service == null) {
return null;
}
if (onTop != null) {
attributes.add(onTop);
}
ServiceDialog pageDialog = new ServiceDialog(gc, x, y, service, DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributes, (Frame) null);
pageDialog.show();
if (pageDialog.getStatus() == ServiceDialog.APPROVE) {
PrintRequestAttributeSet newas = pageDialog.getAttributes();
Class amCategory = SunAlternateMedia.class;
if (attributes.containsKey(amCategory) && !newas.containsKey(amCategory)) {
attributes.remove(amCategory);
}
attributes.addAll(newas);
return attributeToPageFormat(service, attributes);
} else {
return null;
}
}
use of javax.print.attribute.PrintRequestAttributeSet in project jdk8u_jdk by JetBrains.
the class ImageableAreaTest method printWithoutPrintDialog.
private static void printWithoutPrintDialog() {
final JTable table = createAuthorTable(42);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
try {
boolean printAccepted = table.print(JTable.PrintMode.FIT_WIDTH, new MessageFormat("Author Table"), new MessageFormat("Page - {0}"), false, pras, false);
closeFrame();
if (!printAccepted) {
throw new RuntimeException("User cancels the printer job!");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Aggregations