Stampa in Java, parte 1
Modelli di rendering
Esistono due modelli di stampa in Java: Printable
lavori e Pageable
lavori.
Stampabili
Printable
i lavori sono i più semplici dei due modelli di stampa. Questo modello ne utilizza solo uno PagePainter
per l'intero documento. Il rendering delle pagine viene eseguito in sequenza, a partire dalla pagina zero. Quando viene stampata l'ultima pagina, è PagePainter
necessario restituire il NO_SUCH_PAGE
valore. Il sottosistema di stampa richiederà sempre che l'applicazione effettui il rendering delle pagine in sequenza. Ad esempio, se all'applicazione viene richiesto di eseguire il rendering delle pagine da cinque a sette, il sottosistema di stampa richiederà tutte le pagine fino alla settima, ma stamperà solo le pagine cinque, sei e sette. Se l'applicazione visualizza una finestra di dialogo di stampa, il numero totale di pagine da stampare non verrà visualizzato poiché è impossibile conoscere in anticipo il numero di pagine nel documento utilizzando questo modello.
Pageabili
Pageable
i lavori offrono maggiore flessibilità rispetto ai Printable
lavori, poiché ogni pagina di un Pageable
lavoro può presentare un layout diverso. Pageable
i lavori vengono spesso utilizzati con Book
s, una raccolta di pagine che può avere formati diversi. Spiegherò la Book
classe tra un momento.
Un Pageable
lavoro ha le seguenti caratteristiche:
- Ogni pagina può avere il proprio pittore. Ad esempio, potresti avere un pittore implementato per stampare la copertina, un altro pittore per stampare il sommario e un terzo per stampare l'intero documento.
- Puoi impostare un formato di pagina diverso per ogni pagina del libro. In un
Pageable
lavoro, puoi combinare pagine verticali e orizzontali. - Il sottosistema di stampa potrebbe richiedere all'applicazione di stampare pagine fuori sequenza e alcune pagine potrebbero essere ignorate se necessario. Di nuovo, non devi preoccuparti di questo fintanto che puoi fornire qualsiasi pagina del tuo documento su richiesta.
- Il
Pageable
lavoro non ha bisogno di sapere quante pagine ci sono nel documento.
Libri
Un'altra novità dalla versione 1.2 è la Book
classe. Questa classe ti consente di creare documenti di più pagine. Ogni pagina può avere il proprio formato e il proprio pittore, offrendoti la flessibilità di creare documenti sofisticati. Poiché la Book
classe implementa l' Pageable
interfaccia, è possibile implementare la propria Book
classe quando la Book
classe fornita non dispone delle funzionalità richieste.
Una Book
classe rappresenta una raccolta di pagine. Quando viene creato per la prima volta, l' Book
oggetto è vuoto. Per aggiungere pagine, è sufficiente utilizzare uno dei due append()
metodi (vedere la mia spiegazione di questa classe nella sezione API per maggiori dettagli). I parametri di questo metodo sono l' PageFormat
oggetto, che definisce le caratteristiche fisiche della pagina, e un PagePainter
oggetto, che implementa l' Printable
interfaccia. Se non conosci il numero di pagine nel tuo documento, passa semplicemente il UNKNOWN_NUMBER_OF_PAGES
valore al append()
metodo. Il sistema di stampa troverà automaticamente il numero di pagine chiamando tutti i pittori di pagine nel libro fino a quando non riceve un NO_SUCH_PAGE
valore.
Definizione API
Teoria e pratica si incontreranno in questa sezione. Nelle sezioni precedenti abbiamo appreso della struttura della pagina, delle unità di misura e dei modelli di rendering. In questa sezione, esamineremo l'API di stampa Java.
Tutte le classi richieste per la stampa si trovano nel java.awt.print
pacchetto, che è composto da tre interfacce e quattro classi. Le seguenti tabelle definiscono le classi e le interfacce del pacchetto di stampa.
Nome | genere | Descrizione |
Paper |
Classe | Questa classe definisce le caratteristiche fisiche della pagina. |
PageFormat |
Classe | PageFormat definisce le dimensioni e l'orientamento della pagina. Definisce anche quale Paper utilizzare durante il rendering di una pagina. |
PrinterJob |
Classe | Questa classe gestisce il lavoro di stampa. Le sue responsabilità includono la creazione di un lavoro di stampa, la visualizzazione di una finestra di dialogo di stampa quando necessario e la stampa del documento. |
Book |
Classe |
|
Pageable |
Interfaccia | Pageable Un'implementazione rappresenta un insieme di pagine da stampare. L' Pageable oggetto restituisce il numero totale di pagine nell'insieme, nonché PageFormat e Printable per una pagina specificata. La Book classe implementa questa interfaccia. |
Printable |
Interfaccia | Un disegnatore di pagine deve implementare l' Printable interfaccia. C'è solo un metodo in questa interfaccia, print() . |
PrinterGraphics |
Interfaccia | L' Graphics oggetto implementa questa interfaccia. PrinterGraphics fornisce il getPrinterJob() metodo per ottenere il lavoro di stampa che ha creato un'istanza del processo di stampa. |
Interfaccia paginabile
L' Pageable
interfaccia include tre metodi:
Nome del metodo | Descrizione |
int getNumberOfPages() |
Restituisce il numero di pagine nel documento. |
PageFormat getPageFormat(int pageIndex) |
Restituisce la pagina PageFormat come specificato da pageIndex . |
Printable getPrintable(int pageIndex) |
Restituisce l' Printable istanza responsabile del rendering della pagina specificata da pageIndex . |
Interfaccia stampabile
L' Printable
interfaccia presenta un metodo e due valori:
Nome | genere | Descrizione |
int print(Graphics graphics, PageFormat pageFormat, int pageIndex) |
Metodo | Richiede che la grafica gestisca utilizzando il formato di pagina specificato il rendering della pagina specificata. |
NO_SUCH_PAGE |
Valore | Questa è una costante. Restituire questo valore per indicare che non ci sono più pagine da stampare. |
PAGE_EXISTS |
Valore | Il print() metodo ritorna PAGE_EXISTS . Indica che la pagina passata come parametro print() è stata renderizzata ed esiste. |
Ogni disegnatore di pagine deve implementare l' Printable
interfaccia. Poiché esiste un solo metodo da implementare, la creazione di pittori di pagine può sembrare facile. Tuttavia, ricorda che il tuo codice deve essere in grado di eseguire il rendering di qualsiasi pagina dentro o fuori sequenza.
Ci sono tre parametri per print()
, incluso Graphics
, che è la stessa classe usata per disegnare sullo schermo. Poiché la Graphics
classe implementa l' PrinterGraphic
interfaccia, è possibile ottenere PrinterJob
ciò che ha istanziato questo lavoro di stampa. Se il layout della pagina è complesso e richiede alcune funzionalità di disegno avanzate, è possibile eseguire il cast del Graphics
parametro su un Graphics2D
oggetto. Avrai quindi accesso all'API 2D Java completa.
Before you start using the Graphics
object, note that the coordinates are not translated to the top left corner of the printable area. Refer to Figure 3 to find the location of the default origin.
(0, 0) appears at the top left corner of the printer margins. To print a 1-by-1-inch rectangle, 1 inch from both top and left margins, you would use the following code:
1: public int print (Graphics graphics, PageFormat pageFormat, int pageIndex) { 2: Graphics2D graphics2D = (Graphics2D) graphics; 3: Rectangle2D.Double rectangle = new Rectangle2D.Double (); 4: rectangle.setRect (pageFormat.getImageableX () + 72, 5: pageFormat.getImageableY () + 72, 6: 72, 7: 72); 8: graphics2D.draw (rectangle); 9: return (PAGE_EXISTS); }
From the previous example, we see that we must manually translate the origin of the rectangle so that it prints at the top of the printable area as in Figure 1. To simplify the code, we could translate the coordinates once and use (0, 0) as the origin of the printable area. By modifying the previous example, we get:
1: public int print (Graphics graphics, PageFormat pageFormat, int pageIndex) { 2: Graphics2D graphics2D = (Graphics2D) graphics; 3: graphics2D.translate (pageFormat.getImageableX (), pageFormat.getImageableY ()); 4: Rectangle2D.Double rectangle = new Rectangle2D.Double (); 5: rectangle.setRect (72, 72, 72, 72); 6: graphics2D.draw (rectangle); 7: return (PAGE_EXISTS); 8: }
Using the translate()
method in line 3, we can translate the coordinates and set our origin (0, 0) at the top of the printable area. From this point on, our code will be simplified.
PrinterGraphics interface
The PrinterGraphics
interface consists of one method:
Method name | Description |
PrinterJob getPrinterJob() |
Returns the PrinterJob for this rendering request and is implemented by the Graphics class |
Paper class
Eight methods make up the Paper
class:
Method name | Description |
double getHeight() |
This method returns the page's physical height in points (1 inch = 72 points). For example, if you are printing on a letter-size page, the return value will be 792 points, or 11 inches. |
double getImageableHeight() |
This method returns the page's imageable height. The imageable height is the height of the print area that you may draw on. See Figure 1 for a graphical view of the imageable area. |
double getImageableWidth() |
This method returns a page's imageable width (the width of the print area that you may draw on). See Figure 1 for a graphical view of the imageable area. |
double getImageableX() |
This method returns the x origin of the imageable area. Since there is no support for margins, the return value represents the left margin. |
double getImageableY() |
This method returns the y origin of the imageable area. The value returned from this method is equivalent to the top margin. |
double getWidth() |
This method returns the page's physical width in points. If you print on a letter-size paper, the width is 8.5 inches, or 612 points. |
void setImageableArea(double x, double y, double width, double height) |
This method sets the imageable area and specifies the margins on the page. Actually, the API provides no method to set the margins explicitly; you have to calculate them yourself. |
void setSize(double width, double height) |
This method sets the physical page size. To define an 8.5-by-11-inch sheet, you would supply 612 and 792 points. Note that the default size is LETTER . |
Before we move on to the next section, remember that the Paper
class defines the page's physical characteristics. The PageFormat
class represents all the page's characteristics, such as page orientation, size, and the paper type. This class is always passed as a parameter to the Printable
interface's print()
method. Use Paper
to obtain the imageable area location, size, and page orientation along with a transformation matrix.
PageFormat class
The PageFormat
consists of 12 methods:
Method name | Description |
double getHeight() |
This method returns the page's physical height in points (1 inch = 72 points). If your page measures 8.5 by 11 inches, then the return value will be 792 points, or 11 inches. |
double getImageableHeight() |
This method returns the page's imageable height, which is the height of the print area on which you may draw. See Figure 1 for a graphical view of the imageable area. |
double getImageableWidth() |
This method returns the page's imageable width -- the width of the print area on which you may draw. Figure 1 illustrates a graphical view of the imageable area. |
double getImageableX() |
This method returns the x origin of the imageable area. |
double getImageableY() |
This method returns the imageable area's y origin. |
double getWidth() |
This method returns the page's physical width in points. If you print on letter-sized paper, the width is 8.5 inches, or 612 points. |
double getHeight() |
This method returns the page's physical height in points. For example, letter-sized paper is 11 inches in height, or 792 points. |
double[] getMatrix() |
This method returns a transformation matrix that translates user space into the requested page orientation. The return value is in the format required by the AffineTransform constructor. |
int getOrientation() |
This method returns the orientation of the page as either PORTRAIT or LANDSCAPE . |
void setOrientation(int orientation) |
This method sets the orientation of the page, using the constants PORTRAIT and LANDSCAPE . |
Paper getPaper() |
This method returns the Paper object associated with the page format. Refer to the previous section for a description of the Paper class. |
void setPaper(Paper paper) |
This method sets the Paper object that will be used by the PageFormat class. PageFormat must have access to the physical page characteristics to complete this task. |
This concludes the description of the page classes. The next class that we will study is the PrinterJob
.
PrinterJob class
The PrinterJob
class controls the printing process. It can both instantiate and control a print job. Below you will find a definition of the class:
Method name | Description |
abstract void cancel() |
This method cancels the current print job. You can validate the cancellation with the isCancel() method. |
abstract boolean isCancelled() |
This method returns true if the job is cancelled. |
PageFormat defaultPage() |
This method returns the default page format for the PrinterJob . |
abstract PageFormat defaultPage(PageFormat page) |
This method clones the PageFormat passed in parameters and modifies the clone to create the default PageFormat . |
abstract int getCopies() |
This method returns the number of copies that the print job will print. |
abstract void setCopies(int copies) |
This method sets the number of copies that the job will print. Note that if you show a print dialog box, users can alter the number of copies (see the pageDialog method). |
abstract String getJobName() |
This method returns the job name. |
static PrinterJob getPrinterJob() |
This method creates and returns a new PrinterJob . |
abstract String getUserName() |
This method returns the user name associated with the print job. |
abstract PageFormat pageDialog(PageFormat page) |
This method displays a dialog that allows the user to modify the PageFormat . The PageFormat , passed in parameters, sets the fields of the dialog. If the user cancels the dialog, then the original PageFormat will be returned. But if the user accepts the parameters, then a new PageFormat will be created and returned. Since it will not show the same parameters on all operating systems, you must be careful when using the pageDialog . |
abstract void setPageable(Pageable document) |
This method queries the document to obtain the total number of pages. The Pageable will also return the PageFormat and the Printable object for each page. See the definition of the Pageable interface for more information. |
abstract void setPrintable(Printable painter) |
This method sets the Painter object that will render the pages to be printed. A Painter object is an object that implements the Printable class and its print() method. |
abstract void setPrintable(Printable painter, PageFormat format) |
This method completes the same tasks as abstract void setPrintable(Printable painter) , except that you supply the PageFormat that the Painter will use. As indicated in the definition of the Printable interface, the print() method passes a PageFormat object as the first parameter. |
abstract void print() |
This method prints the document. It actually calls the print() method of the Painter previously assigned to this print job. |
abstract void setJobName(String jobName) |
This method sets the name of the print job. |
abstract boolean printDialog() |
This method displays a print dialog box that allows the user to change the print parameters. Note that this interaction's result will not be returned to your program. Instead, it will be passed to the peer operating system. |
abstract PageFormat validatePage(PageFormat page) |
This method will validate the PageFormat passed in parameters. If the printer cannot use the PageFormat that you supplied, then a new one that conforms to the printer will be returned. |
Book class
Seven methods make up the Book
class:
>
Method name | Description |
void append(Printable painter, PageFormat page) |
This method appends a page to the Book . The painter and the PageFormat for that page are passed in parameters. |
void append(Printable painter, PageFormat page, int numPages) |
This method completes the same tasks as void append(Printable painter, PageFormat page) , except that you specify the number of pages. |
int getNumberOfPages() |
This method returns the number of pages currently in the Book . |
PageFormat getPageFormat(int pageIndex) |
This method returns the PageFormat object for a given page. |
Printable getPrintable(int pageIndex) |
This method returns the painter for a given page. |
void setPage(int pageIndex, Printable painter, PageFormat page) |
This method sets the painter and the PageFormat for a given page already in the book. |
The printing recipe
The recipe for printing is very simple. First, create a PrinterJob
object:
PrinterJob printJob = PrinterJob.getPrinterJob ();
Next, using the setPrintable()
method of the PrinterJob
, assign the Painter
object to the PrinterJob
. Note that a Painter
object is one that implements the Printable
interface.
printJob.setPrintable (Painter);
Or you could set the PageFormat
along with the Painter
:
printJob.setPrintable (Painter, pageFormat);
Finally, the Painter
object must implement the print()
method:
public int print (Graphics g, PageFormat pageFormat, int page)
Here the first parameter is the graphics handle that you will use to render the page, the pageFormat
is the format that will be used for the current page, and the last parameter is the page number that must be rendered.
That's all there is to it -- for simple printing, that is.
Introduction to the framework
The print framework that we will build in this series will be completely independent of the Java printing API. It will allow for greater flexibility in producing different outputs. Its structure will allow you to create documents, pages, and print objects. You will be able to add print objects to a page while adding pages to a document. By using this structure, you will be able to easily implement export features to PDF or HTML files, or print directly to the printer using the print API. But the main goal of the framework is to simplify the creation of printed documents. When you print using the print API, you only end up with a graphic canvas to draw on. It fails to address the concepts of paragraphs, images, drawings, graphics, tables, or running headers and footers. Because you must compute the (x, y) origin, the width and height of the printable area, setting margins is a chore. Our print framework will address all of these weaknesses.
Conclusion
We covered a lot of ground in this first part. We looked at measurement units, the structure of page, the two rendering models (Pageable
and Printable
), and Books
, and we concluded with a detailed explanation of the printing API. Next month, we'll focus primarily on code, as we will be putting everything into practice. We will also look at the issues that arise when printing on multiple platforms. Looking ahead to Part 3, I will explain in detail the design and implementation of the framework.
Ulteriori informazioni su questo argomento
- "Stampa in Java", Jean-Pierre Dubé ( JavaWorld )
- Parte 1: familiarizzare con il modello di stampa Java (20 ottobre 2000)
- Parte 2: stampa la tua prima pagina ed esegui il rendering di documenti complessi (1 dicembre 2000)
- Parte 3: Jean-Pierre Dubé introduce il framework di stampa che funziona su Java Print API (5 gennaio 2001)
- Part 4: Code the print framework
- (February 2, 2001)
- Part 5: Discover the print framework's support classes
- (March 2, 2001)
- You will find tons of books covering Java AWT, but none will cover this subject to the extent of this book. If you're writing GUIs, you must have this book next to your computer: Graphic Java 2, Mastering The JFCAWT, Volume 1, David M. Geary (Prentice Hall, 1998)
//www.amazon.com/exec/obidos/ASIN/0130796662/javaworld
- This book was helpful when Java 1.1 came out, and was the first to talk about printing in Java: Migrating from Java 1.0 to Java 1.1, Daniel I. Joshi and Pavel A. Vorobiev (Ventana Communications Group, 1997)
//www.amazon.com/exec/obidos/ASIN/1566046866/javaworld
- Probabilmente il miglior libro su Java 2D, questo libro copre tutti gli aspetti dell'API 2D e fornisce anche un
Graphics
framework per composizioni 2D avanzate: Java 2D API Graphics, Vincent J. Hardy (Prentice Hall, 1999)//www.amazon.com/exec/obidos/ASIN/0130142662/javaworld
- Un'eccellente introduzione all'API Java 2D "Getting Started with Java 2D", Bill Day ( JavaWorld, luglio 1998)
//www.javaworld.com/javaworld/jw-07-1998/jw-07-media.html
Questa storia, "Stampa in Java, parte 1" è stata originariamente pubblicata da JavaWorld.