use of javax.print.attribute.PrintRequestAttributeSet in project jdk8u_jdk by JetBrains.
the class UnixPrintServiceLookup method getPrintServices.
/*
* If service attributes are specified then there must be additional
* filtering.
*/
public PrintService[] getPrintServices(DocFlavor flavor, AttributeSet attributes) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPrintJobAccess();
}
PrintRequestAttributeSet requestSet = null;
PrintServiceAttributeSet serviceSet = null;
if (attributes != null && !attributes.isEmpty()) {
requestSet = new HashPrintRequestAttributeSet();
serviceSet = new HashPrintServiceAttributeSet();
Attribute[] attrs = attributes.toArray();
for (int i = 0; i < attrs.length; i++) {
if (attrs[i] instanceof PrintRequestAttribute) {
requestSet.add(attrs[i]);
} else if (attrs[i] instanceof PrintServiceAttribute) {
serviceSet.add(attrs[i]);
}
}
}
PrintService[] services = getPrintServices(serviceSet);
if (services.length == 0) {
return services;
}
if (CUPSPrinter.isCupsRunning()) {
ArrayList matchingServices = new ArrayList();
for (int i = 0; i < services.length; i++) {
try {
if (services[i].getUnsupportedAttributes(flavor, requestSet) == null) {
matchingServices.add(services[i]);
}
} catch (IllegalArgumentException e) {
}
}
services = new PrintService[matchingServices.size()];
return (PrintService[]) matchingServices.toArray(services);
} else {
// We only need to compare 1 PrintService because all
// UnixPrintServices are the same anyway. We will not use
// default PrintService because it might be null.
PrintService service = services[0];
if ((flavor == null || service.isDocFlavorSupported(flavor)) && service.getUnsupportedAttributes(flavor, requestSet) == null) {
return services;
} else {
return new PrintService[0];
}
}
}
use of javax.print.attribute.PrintRequestAttributeSet in project jdk8u_jdk by JetBrains.
the class PageDlgStackOverflowTest method main.
public static void main(String[] args) {
PrinterJob job = PrinterJob.getPrinterJob();
if (job == null) {
return;
}
PrintRequestAttributeSet pSet = new HashPrintRequestAttributeSet();
pSet.add(DialogTypeSelection.NATIVE);
job.printDialog(pSet);
try {
job.pageDialog(pSet);
} catch (StackOverflowError e) {
throw new RuntimeException("StackOverflowError is thrown");
}
}
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 tray by qzind.
the class PrintPixel method applyDefaultSettings.
protected PrintRequestAttributeSet applyDefaultSettings(PrintOptions.Pixel pxlOpts, PageFormat page) {
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
// apply general attributes
if (pxlOpts.getColorType() != null) {
attributes.add(pxlOpts.getColorType().getChromatic());
}
if (pxlOpts.isDuplex()) {
attributes.add(Sides.DUPLEX);
}
if (pxlOpts.getOrientation() != null) {
attributes.add(pxlOpts.getOrientation().getAsAttribute());
}
// TODO - set paper thickness
// TODO - set printer tray
// Java prints using inches at 72dpi
final float DENSITY = (float) pxlOpts.getDensity() * pxlOpts.getUnits().as1Inch();
final float CONVERT = pxlOpts.getUnits().toInches() * 72f;
log.trace("DPI: {}\tCNV: {}", DENSITY, CONVERT);
if (DENSITY > 0) {
attributes.add(new PrinterResolution((int) DENSITY, (int) DENSITY, ResolutionSyntax.DPI));
}
// apply sizing and margins
Paper paper = page.getPaper();
float pageX = 0f;
float pageY = 0f;
float pageW = (float) page.getWidth() / CONVERT;
float pageH = (float) page.getHeight() / CONVERT;
// page size
if (pxlOpts.getSize() != null && pxlOpts.getSize().getWidth() > 0 && pxlOpts.getSize().getHeight() > 0) {
pageW = (float) pxlOpts.getSize().getWidth();
pageH = (float) pxlOpts.getSize().getHeight();
paper.setSize(pageW * CONVERT, pageH * CONVERT);
}
// margins
if (pxlOpts.getMargins() != null) {
pageX += pxlOpts.getMargins().left();
pageY += pxlOpts.getMargins().top();
pageW -= (pxlOpts.getMargins().right() + pxlOpts.getMargins().left());
pageH -= (pxlOpts.getMargins().bottom() + pxlOpts.getMargins().top());
}
log.trace("Drawable area: {},{}:{},{}", pageX, pageY, pageW, pageH);
if (pageW > 0 && pageH > 0) {
attributes.add(new MediaPrintableArea(pageX, pageY, pageW, pageH, pxlOpts.getUnits().getMediaSizeUnits()));
paper.setImageableArea(pageX * CONVERT, pageY * CONVERT, pageW * CONVERT, pageH * CONVERT);
page.setPaper(paper);
} else {
log.warn("Could not apply custom size, using printer default");
attributes.add(new MediaPrintableArea(0, 0, (float) page.getWidth() / 72f, (float) page.getHeight() / 72f, PrintOptions.Unit.INCH.getMediaSizeUnits()));
}
log.trace("{}", Arrays.toString(attributes.toArray()));
return attributes;
}
use of javax.print.attribute.PrintRequestAttributeSet in project ofbiz-framework by apache.
the class OutputServices method sendPrintFromScreen.
public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
VisualTheme visualTheme = (VisualTheme) serviceContext.get("visualTheme");
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String printerContentType = (String) serviceContext.remove("printerContentType");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = new HashMap<>();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/postscript";
}
if (UtilValidate.isEmpty(printerContentType)) {
printerContentType = contentType;
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screenfop"), visualTheme.getModelTheme().getScreenRendererLocation("screenfop"));
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
// Print is sent
DocFlavor psInFormat = new DocFlavor.INPUT_STREAM(printerContentType);
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocAttributeSet docAttributeSet = new HashDocAttributeSet();
List<Object> docAttributes = UtilGenerics.checkList(serviceContext.remove("docAttributes"));
if (UtilValidate.isNotEmpty(docAttributes)) {
for (Object da : docAttributes) {
Debug.logInfo("Adding DocAttribute: " + da, module);
docAttributeSet.add((DocAttribute) da);
}
}
Doc myDoc = new SimpleDoc(bais, psInFormat, docAttributeSet);
PrintService printer = null;
// lookup the print service for the supplied printer name
String printerName = (String) serviceContext.remove("printerName");
if (UtilValidate.isNotEmpty(printerName)) {
PrintServiceAttributeSet printServiceAttributes = new HashPrintServiceAttributeSet();
printServiceAttributes.add(new PrinterName(printerName, locale));
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributes);
if (printServices.length > 0) {
printer = printServices[0];
Debug.logInfo("Using printer: " + printer.getName(), module);
if (!printer.isDocFlavorSupported(psInFormat)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale));
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale));
}
} else {
// if no printer name was supplied, try to get the default printer
printer = PrintServiceLookup.lookupDefaultPrintService();
if (printer != null) {
Debug.logInfo("No printer name supplied, using default printer: " + printer.getName(), module);
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotAvailable", locale));
}
PrintRequestAttributeSet praset = new HashPrintRequestAttributeSet();
List<Object> printRequestAttributes = UtilGenerics.checkList(serviceContext.remove("printRequestAttributes"));
if (UtilValidate.isNotEmpty(printRequestAttributes)) {
for (Object pra : printRequestAttributes) {
Debug.logInfo("Adding PrintRequestAttribute: " + pra, module);
praset.add((PrintRequestAttribute) pra);
}
}
DocPrintJob job = printer.createPrintJob();
job.print(myDoc, praset);
} catch (PrintException | IOException | TemplateException | GeneralException | SAXException | ParserConfigurationException e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
Aggregations