下面列出了java.awt.print.PrinterIOException#java.awt.print.PrinterException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi == 0)
token = new StringTokenizer(ta.getText(), "\r\n");
if (!token.hasMoreTokens())
return Printable.NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.setFont(newFont);
double xbeg = pf.getImageableX();
double ywidth = pf.getImageableHeight() + pf.getImageableY();
double y = pf.getImageableY() + incrY;
while (token.hasMoreTokens() && (y < ywidth)) {
String toke = token.nextToken();
g2d.drawString(toke, (int) xbeg, (int) y);
y += incrY;
}
return Printable.PAGE_EXISTS;
}
void print(List<Paper> papers) {
PrinterJob job = PrinterJob.getPrinterJob();
myPapers = papers;
//out("SET PAPER: " + myPapers);
if (job == null) {
return;
}
job.setPrintable(this, Config.getDefault().getPageFormat());
try {
if (job.printDialog()) {
job.print();
}
}
catch (PrinterException e) {
printError(i18n(Printer.class, "ERR_Printer_Problem", e.getLocalizedMessage())); // NOI18N
}
myPapers = null;
}
public int print(final Graphics graphics,
final PageFormat pageFormat, final int pageIndex)
throws PrinterException {
final int retVal =
printDelegatee.print(graphics, pageFormat, pageIndex);
if (retVal != NO_SUCH_PAGE && !isAborted()) {
if (SwingUtilities.isEventDispatchThread()) {
updateStatusOnEDT(pageIndex);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateStatusOnEDT(pageIndex);
}
});
}
}
return retVal;
}
public int print(final Graphics graphics,
final PageFormat pageFormat, final int pageIndex)
throws PrinterException {
final int retVal =
printDelegatee.print(graphics, pageFormat, pageIndex);
if (retVal != NO_SUCH_PAGE && !isAborted()) {
if (SwingUtilities.isEventDispatchThread()) {
updateStatusOnEDT(pageIndex);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateStatusOnEDT(pageIndex);
}
});
}
}
return retVal;
}
private void setPrinterNameAttrib(String printerName) {
PrintService service = this.getPrintService();
if (printerName == null) {
return;
}
if (service != null && printerName.equals(service.getName())) {
return;
} else {
PrintService []services = PrinterJob.lookupPrintServices();
for (int i=0; i<services.length; i++) {
if (printerName.equals(services[i].getName())) {
try {
this.setPrintService(services[i]);
} catch (PrinterException e) {
}
return;
}
}
}
//** END Functions called by native code for querying/updating attributes
}
@Override
protected void setAttributes(PrintRequestAttributeSet attributes)
throws PrinterException {
super.setAttributes(attributes);
if (attributes == null) {
return; // now always use attributes, so this shouldn't happen.
}
Attribute attr = attributes.get(Media.class);
if (attr instanceof CustomMediaTray) {
CustomMediaTray customTray = (CustomMediaTray)attr;
String choice = customTray.getChoiceName();
if (choice != null) {
mOptions = " InputSlot="+ choice;
}
}
}
public int print(final Graphics graphics,
final PageFormat pageFormat, final int pageIndex)
throws PrinterException {
final int retVal =
printDelegatee.print(graphics, pageFormat, pageIndex);
if (retVal != NO_SUCH_PAGE && !isAborted()) {
if (SwingUtilities.isEventDispatchThread()) {
updateStatusOnEDT(pageIndex);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateStatusOnEDT(pageIndex);
}
});
}
}
return retVal;
}
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);
}
}
}
private static void doTest() {
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(Chromaticity.MONOCHROME);
MediaSize isoA5Size = MediaSize.getMediaSizeForName(MediaSizeName.ISO_A5);
float[] size = isoA5Size.getSize(Size2DSyntax.INCH);
Paper paper = new Paper();
paper.setSize(size[0] * 72.0, size[1] * 72.0);
paper.setImageableArea(0.0, 0.0, size[0] * 72.0, size[1] * 72.0);
PageFormat pf = new PageFormat();
pf.setPaper(paper);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new WrongPaperPrintingTest(), job.validatePage(pf));
if (job.printDialog()) {
try {
job.print(aset);
} catch (PrinterException pe) {
throw new RuntimeException(pe);
}
}
}
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);
}
}
}
public int print(final Graphics graphics,
final PageFormat pageFormat, final int pageIndex)
throws PrinterException {
final int retVal =
printDelegatee.print(graphics, pageFormat, pageIndex);
if (retVal != NO_SUCH_PAGE && !isAborted()) {
if (SwingUtilities.isEventDispatchThread()) {
updateStatusOnEDT(pageIndex);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateStatusOnEDT(pageIndex);
}
});
}
}
return retVal;
}
/**
* Associate this PrinterJob with a new PrintService.
*
* Throws <code>PrinterException</code> if the specified service
* cannot support the <code>Pageable</code> and
* <code>Printable</code> interfaces necessary to support 2D printing.
* @param a print service which supports 2D printing.
*
* @throws PrinterException if the specified service does not support
* 2D printing or no longer available.
*/
public void setPrintService(PrintService service)
throws PrinterException {
if (service == null) {
throw new PrinterException("Service cannot be null");
} else if (!(service instanceof StreamPrintService) &&
service.getName() == null) {
throw new PrinterException("Null PrintService name.");
} else {
// Check the list of services. This service may have been
// deleted already
PrinterState prnState = (PrinterState)service.getAttribute(
PrinterState.class);
if (prnState == PrinterState.STOPPED) {
PrinterStateReasons prnStateReasons =
(PrinterStateReasons)service.getAttribute(
PrinterStateReasons.class);
if ((prnStateReasons != null) &&
(prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN)))
{
throw new PrinterException("PrintService is no longer available.");
}
}
if (service.isDocFlavorSupported(
DocFlavor.SERVICE_FORMATTED.PAGEABLE) &&
service.isDocFlavorSupported(
DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
myService = service;
} else {
throw new PrinterException("Not a 2D print service: " + service);
}
}
}
public int print(Graphics graphics,
PageFormat pageFormat,
int pageIndex)
throws PrinterException {
if (pageIndex >= 1) {
return Printable.NO_SUCH_PAGE;
}
this.paint(graphics);
return Printable.PAGE_EXISTS;
}
/**
* Associate this PrinterJob with a new PrintService.
*
* Throws {@code PrinterException} if the specified service
* cannot support the {@code Pageable} and
* {@code Printable} interfaces necessary to support 2D printing.
* @param service print service which supports 2D printing.
*
* @throws PrinterException if the specified service does not support
* 2D printing or no longer available.
*/
public void setPrintService(PrintService service)
throws PrinterException {
if (service == null) {
throw new PrinterException("Service cannot be null");
} else if (!(service instanceof StreamPrintService) &&
service.getName() == null) {
throw new PrinterException("Null PrintService name.");
} else {
// Check the list of services. This service may have been
// deleted already
PrinterState prnState = service.getAttribute(PrinterState.class);
if (prnState == PrinterState.STOPPED) {
PrinterStateReasons prnStateReasons =
service.getAttribute(PrinterStateReasons.class);
if ((prnStateReasons != null) &&
(prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN)))
{
throw new PrinterException("PrintService is no longer available.");
}
}
if (service.isDocFlavorSupported(
DocFlavor.SERVICE_FORMATTED.PAGEABLE) &&
service.isDocFlavorSupported(
DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
myService = service;
} else {
throw new PrinterException("Not a 2D print service: " + service);
}
}
}
@Override
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
if (pageIndex == 0) {
g.setColor(Color.RED);
g.drawRect((int)pf.getImageableX(), (int)pf.getImageableY(),
(int)pf.getImageableWidth(), (int)pf.getImageableHeight());
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}
}
public void run() {
try {
printerJob.print(attributes);
} catch (PrinterException e) {
//REMIND: need to store this away and not rethrow it.
}
/* Close the message queues so that nobody is stuck
* waiting for one.
*/
graphicsToBeDrawn.closeWhenEmpty();
graphicsDrawn.close();
}
@Override
public int print(Graphics g, PageFormat pf, int pi)
throws PrinterException {
System.out.println("pi = " + pi);
g.drawString("Testing", 100, 100);
if (pi == 1)
return NO_SUCH_PAGE;
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
job.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}
@Override
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
if (pageIndex == 0) {
g.setColor(Color.RED);
g.drawRect((int) pf.getImageableX(), (int) pf.getImageableY(),
(int) pf.getImageableWidth() - 1, (int) pf.getImageableHeight() - 1);
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}
}
/**
* Prints the page at the specified index into the specified
* {@link Graphics} context in the specified
* format. A <code>PrinterJob</code> calls the
* <code>Printable</code> interface to request that a page be
* rendered into the context specified by
* <code>graphics</code>. The format of the page to be drawn is
* specified by <code>pageFormat</code>. The zero based index
* of the requested page is specified by <code>pageIndex</code>.
* If the requested page does not exist then this method returns
* NO_SUCH_PAGE; otherwise PAGE_EXISTS is returned.
* The <code>Graphics</code> class or subclass implements the
* {@link PrinterGraphics} interface to provide additional
* information. If the <code>Printable</code> object
* aborts the print job then it throws a {@link PrinterException}.
* @param graphics the context into which the page is drawn
* @param pageFormat the size and orientation of the page being drawn
* @param pageIndex the zero based index of the page to be drawn
* @return PAGE_EXISTS if the page is rendered successfully
* or NO_SUCH_PAGE if <code>pageIndex</code> specifies a
* non-existent page.
* @exception java.awt.print.PrinterException
* thrown when the print job is terminated.
*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
int result;
/* This method will be called by the PrinterJob on a thread other
* that the application's thread. We hold on to the graphics
* until we can rendevous with the application's thread and
* hand over the graphics. The application then does all the
* drawing. When the application is done drawing we rendevous
* again with the PrinterJob thread and release the Graphics
* so that it knows we are done.
*/
/* Add the graphics to the message queue of graphics to
* be rendered. This is really a one slot queue. The
* application's thread will come along and remove the
* graphics from the queue when the app asks for a graphics.
*/
graphicsToBeDrawn.append( (Graphics2D) graphics);
/* We now wait for the app's thread to finish drawing on
* the Graphics. This thread will sleep until the application
* release the graphics by placing it in the graphics drawn
* message queue. If the application signals that it is
* finished drawing the entire document then we'll get null
* returned when we try and pop a finished graphic.
*/
if (graphicsDrawn.pop() != null) {
result = PAGE_EXISTS;
} else {
result = NO_SUCH_PAGE;
}
return result;
}
/**
* Invoked by the RasterPrintJob super class
* this method is called after that last page
* has been imaged.
*/
protected void endDoc() throws PrinterException {
if (mPSStream != null) {
mPSStream.println(EOF_COMMENT);
mPSStream.flush();
if (mDestType != RasterPrinterJob.STREAM) {
mPSStream.close();
}
}
if (mDestType == RasterPrinterJob.PRINTER) {
PrintService pServ = getPrintService();
if (pServ != null) {
mDestination = pServ.getName();
if (isMac) {
PrintServiceAttributeSet psaSet = pServ.getAttributes();
if (psaSet != null) {
mDestination = psaSet.get(PrinterName.class).toString() ;
}
}
}
PrinterSpooler spooler = new PrinterSpooler();
java.security.AccessController.doPrivileged(spooler);
if (spooler.pex != null) {
throw spooler.pex;
}
}
}
/**
* Invoked by the RasterPrintJob super class
* this method is called after that last page
* has been imaged.
*/
protected void endDoc() throws PrinterException {
if (mPSStream != null) {
mPSStream.println(EOF_COMMENT);
mPSStream.flush();
if (mDestType != RasterPrinterJob.STREAM) {
mPSStream.close();
}
}
if (mDestType == RasterPrinterJob.PRINTER) {
PrintService pServ = getPrintService();
if (pServ != null) {
mDestination = pServ.getName();
if (isMac) {
PrintServiceAttributeSet psaSet = pServ.getAttributes();
if (psaSet != null) {
mDestination = psaSet.get(PrinterName.class).toString() ;
}
}
}
PrinterSpooler spooler = new PrinterSpooler();
java.security.AccessController.doPrivileged(spooler);
if (spooler.pex != null) {
throw spooler.pex;
}
}
}
private static void printTest() {
job.setPrintable(new TestCheckSystemDefaultBannerOption());
try {
job.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
protected void validateDestination(String dest) throws PrinterException {
if (dest == null) {
return;
}
// dest is null for Destination(new URI(""))
// because isAttributeValueSupported returns false in setAttributes
// Destination(new URI(" ")) throws URISyntaxException
File f = new File(dest);
try {
// check if this is a new file and if filename chars are valid
if (f.createNewFile()) {
f.delete();
}
} catch (IOException ioe) {
throw new PrinterException("Cannot write to file:"+
dest);
} catch (SecurityException se) {
//There is already file read/write access so at this point
// only delete access is denied. Just ignore it because in
// most cases the file created in createNewFile gets overwritten
// anyway.
}
File pFile = f.getParentFile();
if ((f.exists() &&
(!f.isFile() || !f.canWrite())) ||
((pFile != null) &&
(!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) {
throw new PrinterException("Cannot write to file:"+
dest);
}
}
public void actionPerformed(ActionEvent e) {
try {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(testInstance);
if (job.printDialog()) {
job.print();
}
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
public static void createUI() {
f = new JFrame("LinearGradient Printing Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final LinearGradientPrintingTest gpt = new LinearGradientPrintingTest();
Container c = f.getContentPane();
c.add(BorderLayout.CENTER, gpt);
final JButton print = new JButton("Print");
print.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(gpt);
final boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException ex) {
throw new RuntimeException(ex);
}
}
}
});
c.add(print, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
public void print() throws PrinterException {
stream.println("%!PS-Adobe-3.0 EPSF-3.0");
stream.println("%%BoundingBox: " +
llx + " " + lly + " " + urx + " " + ury);
stream.println("%%Title: " + epsTitle);
stream.println("%%Creator: Java Printing");
stream.println("%%CreationDate: " + new java.util.Date());
stream.println("%%EndComments");
stream.println("/pluginSave save def");
stream.println("mark"); // for restoring stack state on return
job = new PSPrinterJob();
job.epsPrinter = this; // modifies the behaviour of PSPrinterJob
job.mPSStream = stream;
job.mDestType = RasterPrinterJob.STREAM; // prevents closure
job.startDoc();
try {
job.printPage(this, 0);
} catch (Throwable t) {
if (t instanceof PrinterException) {
throw (PrinterException)t;
} else {
throw new PrinterException(t.toString());
}
} finally {
stream.println("cleartomark"); // restore stack state
stream.println("pluginSave restore");
job.endDoc();
}
stream.flush();
}
@Override
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
if (pageIndex == 0) {
g.setColor(Color.RED);
g.drawRect((int)pf.getImageableX(), (int)pf.getImageableY(),
(int)pf.getImageableWidth(), (int)pf.getImageableHeight());
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}
}
/**
* Prints the page at the specified index into the specified
* {@link Graphics} context in the specified
* format. A <code>PrinterJob</code> calls the
* <code>Printable</code> interface to request that a page be
* rendered into the context specified by
* <code>graphics</code>. The format of the page to be drawn is
* specified by <code>pageFormat</code>. The zero based index
* of the requested page is specified by <code>pageIndex</code>.
* If the requested page does not exist then this method returns
* NO_SUCH_PAGE; otherwise PAGE_EXISTS is returned.
* The <code>Graphics</code> class or subclass implements the
* {@link PrinterGraphics} interface to provide additional
* information. If the <code>Printable</code> object
* aborts the print job then it throws a {@link PrinterException}.
* @param graphics the context into which the page is drawn
* @param pageFormat the size and orientation of the page being drawn
* @param pageIndex the zero based index of the page to be drawn
* @return PAGE_EXISTS if the page is rendered successfully
* or NO_SUCH_PAGE if <code>pageIndex</code> specifies a
* non-existent page.
* @exception java.awt.print.PrinterException
* thrown when the print job is terminated.
*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
int result;
/* This method will be called by the PrinterJob on a thread other
* that the application's thread. We hold on to the graphics
* until we can rendevous with the application's thread and
* hand over the graphics. The application then does all the
* drawing. When the application is done drawing we rendevous
* again with the PrinterJob thread and release the Graphics
* so that it knows we are done.
*/
/* Add the graphics to the message queue of graphics to
* be rendered. This is really a one slot queue. The
* application's thread will come along and remove the
* graphics from the queue when the app asks for a graphics.
*/
graphicsToBeDrawn.append( (Graphics2D) graphics);
/* We now wait for the app's thread to finish drawing on
* the Graphics. This thread will sleep until the application
* release the graphics by placing it in the graphics drawn
* message queue. If the application signals that it is
* finished drawing the entire document then we'll get null
* returned when we try and pop a finished graphic.
*/
if (graphicsDrawn.pop() != null) {
result = PAGE_EXISTS;
} else {
result = NO_SUCH_PAGE;
}
return result;
}
public void print() throws PrinterException {
stream.println("%!PS-Adobe-3.0 EPSF-3.0");
stream.println("%%BoundingBox: " +
llx + " " + lly + " " + urx + " " + ury);
stream.println("%%Title: " + epsTitle);
stream.println("%%Creator: Java Printing");
stream.println("%%CreationDate: " + new java.util.Date());
stream.println("%%EndComments");
stream.println("/pluginSave save def");
stream.println("mark"); // for restoring stack state on return
job = new PSPrinterJob();
job.epsPrinter = this; // modifies the behaviour of PSPrinterJob
job.mPSStream = stream;
job.mDestType = RasterPrinterJob.STREAM; // prevents closure
job.startDoc();
try {
job.printPage(this, 0);
} catch (Throwable t) {
if (t instanceof PrinterException) {
throw (PrinterException)t;
} else {
throw new PrinterException(t.toString());
}
} finally {
stream.println("cleartomark"); // restore stack state
stream.println("pluginSave restore");
job.endDoc();
}
stream.flush();
}