Sunteți pe pagina 1din 16

System used is

windows 8.1 ,dell

Dialogue box and


jButton and
jRadiobutton,Jlist And
jCombobox,Virtual
Desktop

Event handler
and listeners
,swing and
jframe ,panels,
drivers plugin
Testing of java panel
and Source code
with testing of
software with new
drivers
Software
maintenance New
panel added with
swing componants

A Basic Printing Program


This section explains how to create a basic printing program that displays a print dialog and prints the text
"Hello World" to the selected printer.
Printing task usually consists of two parts:

Job control Creating a print job, associating it with a printer, specifying the number of copies,
and user print dialog interaction.

Page Imaging Drawing content to a page, and managing content that spans pages (pagination).

First create the printer job. The class representing a printer job and most other related classes is located in
the java.awt.print package.

import java.awt.print.*;
PrinterJob job = PrinterJob.getPrinterJob();
Next provide code that renders the content to the page by implementing the Printable interface.

class HelloWorldPrinter
implements Printable { ... }
...
job.setPrintable(new HelloWorldPrinter());
An application typically displays a print dialog so that the user can adjust various options such as number of
copies, page orientation, or the destination printer.

boolean doPrint = job.printDialog();


This dialog appears until the user either approves or cancels printing. The doPrint variable will be true if the
user gave a command to go ahead and print. If the doPrintvariable is false, the user cancelled the print job.
Since displaying the dialog at all is optional, the returned value is purely informational.
If the doPrint variable is true, then the application will request that the job be printed by calling
the PrinterJob.print method.

if (doPrint) {

try {
job.print();
} catch (PrinterException e) {
// The job did not successfully
// complete
}
}
The PrinterException will be thrown if there is problem sending the job to the printer. However, since
the PrinterJob.print method returns as soon as the job is sent to the printer, the user application cannot
detect paper jams or paper out problems. This job control boilerplate is sufficient for basic printing uses.
The Printable interface has only one method:

public int print(Graphics graphics,


PageFormat pf, int page)
throws PrinterException;
The PageFormat class describes the page orientation (portrait or landscape) and its size and imageable area
in units of 1/72nd of an inch. Imageable area accounts for the margin limits of most printers (hardware margin).
The imageable area is the space inside these margins, and in practice if is often further limited to leave space
for headers or footers.
A page parameter is the zero-based page number that will be rendered.
The following code represents the full Printable implementation:

import java.awt.print.*;
import java.awt.*;
public class HelloWorldPrinter
implements Printable {
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
// We have only one page, and 'page'
// is zero-based
if (page > 0) {
return NO_SUCH_PAGE;
}
// User (0,0) is typically outside the
// imageable area, so we must translate
// by the X and Y values in the PageFormat

// to avoid clipping.
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
// Now we perform our rendering
g.drawString("Hello world!", 100, 100);
// tell the caller that this page is part
// of the printed document
return PAGE_EXISTS;
}
}
The complete code for this example is in HelloWorldPrinter.java.
Sending a Graphics instance to the printer is essentially the same as rendering it to the screen. In both cases
you need to perform the following steps:

To draw a test string is as easy as the other operations that were described for drawing to
a Graphics2D.

Printer graphics have a higher resolution, which should be transparent to most code.

The Printable.print() method is called by the printing system, just as


the Component.paint() method is called to paint a Component on the display. The printing
system will call the Printable.print() method for page 0, 1,.. etc until the print() method
returns NO_SUCH_PAGE.

The print() method may be called with the same page index multiple times until the document
is completed. This feature is applied when the user specifies attributes such as multiple copies with
collate option.

The PageFormat's imageable area determines the clip area. Imageable area is also important in
calculating pagination, or how to span content across printed pages, since page breaks are
determined by how much can fit on each page.

Note: A call to the print() method may be skipped for certain page indices if the user has
specified a different page range that does not involve a particular page index

Using Print Setup Dialogs


Traditionally, the user wants to see the page setup and print dialog boxes. From the print dialog you can select
a printer, specify pages to print, and set the number of copies.

An application displays a print dialog when the user presses a button related to the print command, or chooses
an item from the print menu. To display this dialog, call theprintDialog method of the PrinterJob class:

PrinterJob pj = PrinterJob.getPrinterJob();
...
if (pj.printDialog()) {
try {pj.print();}
catch (PrinterException exc) {
System.out.println(exc);
}
}
...
This method returns true if the user clicked OK to leave the dialog, and false otherwise. The user's choices
in the dialog are constrained based on the number and format of the pages that have been set to
the PrinterJob.
The printDialog method in the above code snippet opens a native print dialog.
The PrintDialogExample.java code example shows how to display a cross-platform print dialog.

You can change the page setup information contained in the PageFormat object by using the page setup
dialog.

To display the page setup dialog, call the pageDialog method of the PrinterJob class.

PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.pageDialog(pj.defaultPage());
The page setup dialog is initialized using the parameter passed to pageDialog. If the user clicks the OK
button in the dialog, the PageFormat instance will be created in accordance with the users selections, and
then returned. If the user cancels the dialog, pageDialog returns the original unchanged PageFormat.
Usually the Java 2D Printing API requires an application to display a print dialog, but in sometimes it's possible
to print without showing any dialog at all. This type of printing is called silent printing. It may be useful in
specific cases, such as, when you need to print a particular database weekly report. In the other cases it is
always recommended to inform the user when a print process is starting.

Printing a Multiple Page Document


You have already learned how to use the Printable interface to print a single page document. However,
documents are usually more than one physical page in length.Pagination is the process of identifying the
location in a document where page breaks and printing accordingly.
In case of printing several graphics images, one per page, use the page index to iterate through these pages
and print one on each page. For example, if several images are represented in the following array:

BufferedImage[] images = new BufferedImage[10];


then use the print() method as shown in the following code fragment:

public int print(Graphics graphics,


PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex < images.length) {
graphics.drawImage(images[pageIndex], 100, 100, null);
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE:
}
}
If the document is continuous, the application must calculate how much content can fit on each page, and
break the page at that point. If text document consists of many lines, then an application must calculate how
many of these lines can fit entirely on a page. The Point class creates a point representing a location in (x,y)
To calculate the height of a single line of text, use the FontMetrics class.

Font font = new Font("Serif", Font.PLAIN, 10);


FontMetrics metrics = graphics.getFontMetrics(font);
int lineHeight = metrics.getHeight();
The PageFormat parameter describes the printable area of the page. In particular, to find the vertical span of
the page use the following code fragment:

double pageHeight = pageFormat.getImageableHeight();


Use the following code fragment to calculate the number of lines that fit on a page and the number of page
breaks:

int linesPerPage = ((int)pageHeight)/lineHeight);


int numBreaks = (textLines.length-1)/linesPerPage;
int[] pageBreaks = new int[numBreaks];
for (int b=0; b < numBreaks; b++) {
pageBreaks[b] = (b+1)*linesPerPage;
}
Use the print() method to calculate the printable area for the following reasons:

Text measurement depends on the FontRenderContext and this is implicit in


the FontMetrics object returned by the printer graphics which is not available except inside
the print() method.

The page format may not be disclosured until printing occurs. Since if the user selected a
landscape mode in the print dialog, then this setting needs to be accounted for.
The PageFormat object passed into the print() method provides this information.

The page break positions are used as represented in the following code fragment:

/* Draw each line that is on this page.


* Increment 'y' position by lineHeight
* for each line.
*/
int y = 0;
int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1];
int end
= (pageIndex == pageBreaks.length)
? textLines.length : pageBreaks[pageIndex];
for (int line=start; line<end; line++) {
y += lineHeight;
g.drawString(textLines[line], 0, y);
}
If a document contains 100 lines and only 48 lines fit on a page, then an application prints 3 pages with page
breaks after 48 and 96 lines of text. The remaining 4 lines are printed on the last page. The complete code for
this example is in PaginationExample.java.
The following simplifying factors are used in the PaginationExample code:

Each page has the same height.

The same font is used.

Working with Print Services and Attributes


From the previous lessons you have learned that the Java 2D printing API supports page imaging, displays
print and page setup dialogs, and specifies printing attributes. Printing services is another key component of
any printing subsystem.

The Java Print Service (JPS) API extends the current Java 2D printing features to offer the following
functionality:

Application discovers printers that cater to its needs by dynamically querying the printer capabilities.

Application extends the attributes included with the JPS API.

Third parties can plug in their own print services with the Service Provider Interface, which print
different formats, including Postscript, PDF, and SVG.

The Java Print Service API consists of four packages:

The javax.print package provides the principal classes and interfaces for the Java Print Service API. It
enables client and server applications to:

Discover and select print services based on their capabilities.

Specify the format of print data.

Submit print jobs to services that support the document type to be printed.

Document Type Specification


The DocFlavor class represents format of the print data, such as JPEG or PostScript.
The DocFlavor format consists of two parts: a MIME type and a representation class name. A MIME type
describes the format, and a document representation class name indicates how the document is delivered to
the printer or output stream. An application uses the DocFlavor and an attribute set to find printers with the
capabilities specified by the attribute set. This code sample demonstrates obtaining an array
ofStreamPrintServiceFactory objects that can return StreamPrintService objects able to convert
a GIF image into PostScript:

DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;


String psMimeType = DocFlavor.BYTE_ARRAY.
POSTSCRIPT.getMimeType();
StreamPrintServiceFactory[] psfactories =
StreamPrintServiceFactory.

lookupStreamPrintServiceFactories(
flavor, psMimeType);

Attribute Definitions
The javax.print.attribute and javax.print.attribute.standard packages define print
attributes which describe the capabilities of a print service, specify the requirements of a print job, and track the
progress of the print job.
For example, if you would like to use A4 paper format and print three copies of your document you will have to
create a set of the following attributes implementing thePrintRequestAttributeSet interface:

PrintRequestAttributeSet attr_set =
new HashPrintRequestAttributeSet();
attr_set.add(MediaSize.ISO_A4);
attr_set.add(new Copies(3));
Then you must pass the attribute set to the print job's print method, along with the DocFlavor.

Print Service Discovery


An application invokes the static methods of the abstract class PrintServiceLookup to locate print
services that have the capabilities to satisfy the application's print request. For example, in order to print two
copies of a double-sided document, the application first needs to find printers that have double-sided printing
capability:

DocFlavor doc_flavor = DocFlavor.INPUT_STREAM.PDF;


PrintRequestAttributeSet attr_set =
new HashPrintRequestAttributeSet();
attr_set.add(new Copies(2));
attr_set.add(Sides.DUPLEX);
PrintService[] service = PrintServiceLookup.
lookupPrintServices(doc_flavor,
attr_set);

Common Use of the API


In conclusion, the Java Print Service API performs the following steps to process a print request:
1.

Chooses a DocFlavor.

2.

Creates a set of attributes.

3.

Locates a print service that can handle the print request as specified by the DocFlavor and the
attribute set.

4.

Creates a Doc object encapsulating the DocFlavor and the actual print data.

5.

Gets a print job, represented by DocPrintJob, from the print service.

6.

Calls the print method of the print job.

Printing the Contents of a User Interface


Another common printing task is to print the contents of a window or a frame, either in whole, or in part. The
window may contain the following components: toolbars, buttons sliders, text labels, scrollable text areas,
images, and other graphical content. All of these components are printed using the following methods of the
Java 2D printing API:

java.awt.Component.print(Graphics g);
java.awt.Component.printAll(Graphics g);
The following figure represents a simple user interface.

The code to create this UI is located in the sample program PrintUIWindow.java.


To print this window, modify the code in the earlier examples which printed text or images. The resulting code
should appear as follows:

public int print(Graphics g, PageFormat pf, int page)


throws PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());

// Print the entire visible contents of a


// java.awt.Frame.
frame.printAll(g);
return PAGE_EXISTS;
}

Printing Support in Swing Components


The PrintUIWindow.java example represented in the previous section demonstrates that the printout is
exactly the same you saw on the screen. This appearance seems reasonable. However, if a window is
scrollable, then the contents that are currently scrolled out of view are not included in the printout. This creates
a dump effect on the printer. This becomes a particular problem when printing large components such as a
Swing table or text components. Components may contain many lines of text which cannot all be entirely visible
on the screen. In this case, print the contents displayed by the component in a manner consistent with the
screen display.
To solve this problem, the Swing table and all text components are printing aware. The following methods
directly provide the use of the Java 2D printing:

javax.swing.JTable.print();

javax.swing.text.JTextComponent.print();

These methods provide a full implementation of printing for their contents. An application doesn't need directly
create a PrinterJob object and implement the Printableinterface. The call of these methods displays a
print dialog and prints the component's data in accordance with the user's selections. There are also additional
methods which provide more options.

S-ar putea să vă placă și