下面列出了怎么用java.awt.print.Printable的API类实例代码及写法,或者点击链接到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;
}
/**
* Print the plot to a printer, represented by the specified graphics
* object.
*
* @param graphics
* The context into which the page is drawn.
* @param format
* The size and orientation of the page being drawn.
* @param index
* The zero based index of the page to be drawn.
* @return PAGE_EXISTS if the page is rendered successfully, or NO_SUCH_PAGE
* if pageIndex specifies a non-existent page.
* @exception PrinterException
* If the print job is terminated.
*/
@Override
public synchronized int print(Graphics graphics, PageFormat format, int index) throws PrinterException {
if (graphics == null) {
return Printable.NO_SUCH_PAGE;
}
// We only print on one page.
if (index >= 1) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D graphics2D = (Graphics2D) graphics;
// Scale the printout to fit the pages.
// Contributed by Laurent ETUR, Schlumberger Riboud Product Center
double scalex = format.getImageableWidth() / getWidth();
double scaley = format.getImageableHeight() / getHeight();
double scale = Math.min(scalex, scaley);
graphics2D.translate((int) format.getImageableX(), (int) format.getImageableY());
graphics2D.scale(scale, scale);
_drawPlot(graphics, true);
return Printable.PAGE_EXISTS;
}
public EPSPrinter(Printable printable, String title,
PrintStream stream,
int x, int y, int wid, int hgt) {
this.printable = printable;
this.epsTitle = title;
this.stream = stream;
llx = x;
lly = y;
urx = llx+wid;
ury = lly+hgt;
// construct a PageFormat with zero margins representing the
// exact bounds of the applet. ie construct a theoretical
// paper which happens to exactly match applet panel size.
Paper p = new Paper();
p.setSize((double)wid, (double)hgt);
p.setImageableArea(0.0,0.0, (double)wid, (double)hgt);
pf = new PageFormat();
pf.setPaper(p);
}
public EPSPrinter(Printable printable, String title,
PrintStream stream,
int x, int y, int wid, int hgt) {
this.printable = printable;
this.epsTitle = title;
this.stream = stream;
llx = x;
lly = y;
urx = llx+wid;
ury = lly+hgt;
// construct a PageFormat with zero margins representing the
// exact bounds of the applet. ie construct a theoretical
// paper which happens to exactly match applet panel size.
Paper p = new Paper();
p.setSize((double)wid, (double)hgt);
p.setImageableArea(0.0,0.0, (double)wid, (double)hgt);
pf = new PageFormat();
pf.setPaper(p);
}
/**
* Returns {@code TextComponentPrintable} to print {@code textComponent}.
*
* @param textComponent {@code JTextComponent} to print
* @param headerFormat the page header, or {@code null} for none
* @param footerFormat the page footer, or {@code null} for none
* @return {@code TextComponentPrintable} to print {@code textComponent}
*/
public static Printable getPrintable(final JTextComponent textComponent,
final MessageFormat headerFormat,
final MessageFormat footerFormat) {
if (textComponent instanceof JEditorPane
&& isFrameSetDocument(textComponent.getDocument())) {
//for document with frames we create one printable per
//frame and merge them with the CompoundPrintable.
List<JEditorPane> frames = getFrames((JEditorPane) textComponent);
List<CountingPrintable> printables =
new ArrayList<CountingPrintable>();
for (JEditorPane frame : frames) {
printables.add((CountingPrintable)
getPrintable(frame, headerFormat, footerFormat));
}
return new CompoundPrintable(printables);
} else {
return new TextComponentPrintable(textComponent,
headerFormat, footerFormat);
}
}
protected PathGraphics(Graphics2D graphics, PrinterJob printerJob,
Printable painter, PageFormat pageFormat,
int pageIndex, boolean canRedraw) {
super(graphics, printerJob);
mPainter = painter;
mPageFormat = pageFormat;
mPageIndex = pageIndex;
mCanRedraw = canRedraw;
}
public int print(Graphics g, PageFormat pf, int index) {
if (index > 0 || image == null) {
return Printable.NO_SUCH_PAGE;
}
((Graphics2D)g).translate(pf.getImageableX(), pf.getImageableY());
int w = image.getWidth(null);
int h = image.getHeight(null);
int iw = (int)pf.getImageableWidth();
int ih = (int)pf.getImageableHeight();
// ensure image will fit
int dw = w;
int dh = h;
if (dw > iw) {
dh = (int)(dh * ( (float) iw / (float) dw)) ;
dw = iw;
}
if (dh > ih) {
dw = (int)(dw * ( (float) ih / (float) dh)) ;
dh = ih;
}
// centre on page
int dx = (iw - dw) / 2;
int dy = (ih - dh) / 2;
g.drawImage(image, dx, dy, dx+dw, dy+dh, 0, 0, w, h, null);
return Printable.PAGE_EXISTS;
}
/**
* The RastePrintJob super class calls this method
* at the end of each page.
*/
protected void endPage(PageFormat format, Printable painter,
int index)
throws PrinterException
{
mPSStream.println(PAGE_RESTORE);
mPSStream.println(SHOWPAGE);
}
/**
* Examine the metrics captured by the
* <code>PeekGraphics</code> instance and
* if capable of directly converting this
* print job to the printer's control language
* or the native OS's graphics primitives, then
* return a <code>PSPathGraphics</code> to perform
* that conversion. If there is not an object
* capable of the conversion then return
* <code>null</code>. Returning <code>null</code>
* causes the print job to be rasterized.
*/
protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
PrinterJob printerJob,
Printable painter,
PageFormat pageFormat,
int pageIndex) {
PSPathGraphics pathGraphics;
PeekMetrics metrics = peekGraphics.getMetrics();
/* If the application has drawn anything that
* out PathGraphics class can not handle then
* return a null PathGraphics.
*/
if (forcePDL == false && (forceRaster == true
|| metrics.hasNonSolidColors()
|| metrics.hasCompositing())) {
pathGraphics = null;
} else {
BufferedImage bufferedImage = new BufferedImage(8, 8,
BufferedImage.TYPE_INT_RGB);
Graphics2D bufferedGraphics = bufferedImage.createGraphics();
boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
pathGraphics = new PSPathGraphics(bufferedGraphics, printerJob,
painter, pageFormat, pageIndex,
canRedraw);
}
return pathGraphics;
}
/**
* Examine the metrics captured by the
* <code>PeekGraphics</code> instance and
* if capable of directly converting this
* print job to the printer's control language
* or the native OS's graphics primitives, then
* return a <code>PSPathGraphics</code> to perform
* that conversion. If there is not an object
* capable of the conversion then return
* <code>null</code>. Returning <code>null</code>
* causes the print job to be rasterized.
*/
protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
PrinterJob printerJob,
Printable painter,
PageFormat pageFormat,
int pageIndex) {
PSPathGraphics pathGraphics;
PeekMetrics metrics = peekGraphics.getMetrics();
/* If the application has drawn anything that
* out PathGraphics class can not handle then
* return a null PathGraphics.
*/
if (forcePDL == false && (forceRaster == true
|| metrics.hasNonSolidColors()
|| metrics.hasCompositing())) {
pathGraphics = null;
} else {
BufferedImage bufferedImage = new BufferedImage(8, 8,
BufferedImage.TYPE_INT_RGB);
Graphics2D bufferedGraphics = bufferedImage.createGraphics();
boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
pathGraphics = new PSPathGraphics(bufferedGraphics, printerJob,
painter, pageFormat, pageIndex,
canRedraw);
}
return pathGraphics;
}
/**
* Print the frame associated with this viewer.
*
* @param gc0 the graphics context.
* @param format page format
* @param pagenumber page index
*/
public int print(Graphics gc0, PageFormat format, int pagenumber) throws PrinterException {
if (pagenumber == 0) {
Graphics2D gc = ((Graphics2D) gc0);
gc.setFont(getFont());
Dimension dim = getContentPane().getSize();
int image_w = dim.width;
int image_h = dim.height;
double paper_x = format.getImageableX() + 1;
double paper_y = format.getImageableY() + 1;
double paper_w = format.getImageableWidth() - 2;
double paper_h = format.getImageableHeight() - 2;
double scale_x = paper_w / image_w;
double scale_y = paper_h / image_h;
double scale = Math.min(scale_x, scale_y);
double shift_x = paper_x + (paper_w - scale * image_w) / 2.0;
double shift_y = paper_y + (paper_h - scale * image_h) / 2.0;
gc.translate(shift_x, shift_y);
gc.scale(scale, scale);
gc.setStroke(new BasicStroke(1.0f));
gc.setColor(Color.BLACK);
getContentPane().paint(gc);
return Printable.PAGE_EXISTS;
} else
return Printable.NO_SUCH_PAGE;
}
/**
* The RastePrintJob super class calls this method
* at the end of each page.
*/
protected void endPage(PageFormat format, Printable painter,
int index)
throws PrinterException
{
mPSStream.println(PAGE_RESTORE);
mPSStream.println(SHOWPAGE);
}
/**
* End a page.
*/
@Override
protected void endPage(PageFormat format, Printable painter,
int index) {
deviceEndPage(format, painter, index);
}
/**
* Examine the metrics captured by the
* <code>PeekGraphics</code> instance and
* if capable of directly converting this
* print job to the printer's control language
* or the native OS's graphics primitives, then
* return a <code>PSPathGraphics</code> to perform
* that conversion. If there is not an object
* capable of the conversion then return
* <code>null</code>. Returning <code>null</code>
* causes the print job to be rasterized.
*/
protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
PrinterJob printerJob,
Printable painter,
PageFormat pageFormat,
int pageIndex) {
PSPathGraphics pathGraphics;
PeekMetrics metrics = peekGraphics.getMetrics();
/* If the application has drawn anything that
* out PathGraphics class can not handle then
* return a null PathGraphics.
*/
if (forcePDL == false && (forceRaster == true
|| metrics.hasNonSolidColors()
|| metrics.hasCompositing())) {
pathGraphics = null;
} else {
BufferedImage bufferedImage = new BufferedImage(8, 8,
BufferedImage.TYPE_INT_RGB);
Graphics2D bufferedGraphics = bufferedImage.createGraphics();
boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
pathGraphics = new PSPathGraphics(bufferedGraphics, printerJob,
painter, pageFormat, pageIndex,
canRedraw);
}
return pathGraphics;
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
if (pageIndex >= 1) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
Double width = pageFormat.getImageableWidth();
Double height = pageFormat.getImageableHeight();
g2d.drawImage(image, 0, 0, width.intValue(), height.intValue(), null, null);
return Printable.PAGE_EXISTS;
}
/**
* The RastePrintJob super class calls this method
* at the end of each page.
*/
protected void endPage(PageFormat format, Printable painter,
int index)
throws PrinterException
{
mPSStream.println(PAGE_RESTORE);
mPSStream.println(SHOWPAGE);
}
public int print(Graphics g, PageFormat pf, int pgIndex) {
if (pgIndex > 0) {
return Printable.NO_SUCH_PAGE;
} else {
// "aware" client code can detect that its been passed a
// PrinterGraphics and could theoretically print
// differently. I think this is more likely useful than
// a problem.
applet.printAll(g);
return Printable.PAGE_EXISTS;
}
}
/**
* Begin a new page.
*/
@Override
protected void startPage(PageFormat format, Printable painter,
int index, boolean paperChanged) {
/* Invalidate any device state caches we are
* maintaining. Win95/98 resets the device
* context attributes to default values at
* the start of each page.
*/
invalidateCachedState();
deviceStartPage(format, painter, index, paperChanged);
}
/**
* Begin a new page.
*/
protected void startPage(PageFormat format, Printable painter,
int index, boolean paperChanged) {
/* Invalidate any device state caches we are
* maintaining. Win95/98 resets the device
* context attributes to default values at
* the start of each page.
*/
invalidateCachedState();
deviceStartPage(format, painter, index, paperChanged);
}
/**
* Begin a new page.
*/
@Override
protected void startPage(PageFormat format, Printable painter,
int index, boolean paperChanged) {
/* Invalidate any device state caches we are
* maintaining. Win95/98 resets the device
* context attributes to default values at
* the start of each page.
*/
invalidateCachedState();
deviceStartPage(format, painter, index, paperChanged);
}
/**
* End a page.
*/
@Override
protected void endPage(PageFormat format, Printable painter,
int index) {
deviceEndPage(format, painter, index);
}
public static void main(String[] args) throws Exception {
PrinterJob printerJob = PrinterJob.getPrinterJob();
printerJob.setPrintable((graphics, pageFormat, pageIndex) -> {
if (pageIndex != 0) {
return Printable.NO_SUCH_PAGE;
} else {
Shape shape = new Rectangle(110, 110, 10, 10);
Rectangle rect = shape.getBounds();
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration().createCompatibleImage(rect.width, rect.height, Transparency.BITMASK);
graphics.drawImage(image, rect.x, rect.y, rect.width, rect.height, null);
return Printable.PAGE_EXISTS;
}
});
File file = null;
try {
HashPrintRequestAttributeSet hashPrintRequestAttributeSet = new HashPrintRequestAttributeSet();
file = File.createTempFile("out", "ps");
file.deleteOnExit();
Destination destination = new Destination(file.toURI());
hashPrintRequestAttributeSet.add(destination);
printerJob.print(hashPrintRequestAttributeSet);
} finally {
if (file != null) {
file.delete();
}
}
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex == 0) {
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}
}
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;
}
@Override
public int print(Graphics pg, PageFormat pf, int pageNum)
throws PrinterException {
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
panel.paint(g2);
return Printable.PAGE_EXISTS;
}
public int print(Graphics g, PageFormat pf, int index) {
if (index > 0 || image == null) {
return Printable.NO_SUCH_PAGE;
}
((Graphics2D)g).translate(pf.getImageableX(), pf.getImageableY());
int w = image.getWidth(null);
int h = image.getHeight(null);
int iw = (int)pf.getImageableWidth();
int ih = (int)pf.getImageableHeight();
// ensure image will fit
int dw = w;
int dh = h;
if (dw > iw) {
dh = (int)(dh * ( (float) iw / (float) dw)) ;
dw = iw;
}
if (dh > ih) {
dw = (int)(dw * ( (float) ih / (float) dh)) ;
dh = ih;
}
// centre on page
int dx = (iw - dw) / 2;
int dy = (ih - dh) / 2;
g.drawImage(image, dx, dy, dx+dw, dy+dh, 0, 0, w, h, null);
return Printable.PAGE_EXISTS;
}
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;
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException
{
if (Thread.interrupted())
{
throw new PrinterException("Current thread interrupted.");
}
if ( pageIndex < 0 || pageIndex >= jasperPrint.getPages().size() )
{
return Printable.NO_SUCH_PAGE;
}
SimpleGraphics2DExporterOutput output = new SimpleGraphics2DExporterOutput();
output.setGraphics2D((Graphics2D)graphics);
exporter.setExporterOutput(output);
grxConfiguration.setPageIndex(pageIndex);
exporter.setConfiguration(grxConfiguration);
try
{
exporter.exportReport();
}
catch (JRException e)
{
throw new PrinterException(e.getMessage()); //NOPMD
}
return Printable.PAGE_EXISTS;
}
public Printable getPrintable(int pgIndex) {
if (pgIndex > 0) {
throw new IndexOutOfBoundsException("pgIndex");
} else {
return printable;
}
}
@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;
}
}