Mencetak di Jawa, Bagian 1

Sebelumnya 1 2 Halaman 2 Halaman 2 dari 2

Model rendering

Ada dua model pencetakan di Java: Printablepekerjaan dan Pageablepekerjaan.

Barang cetakan

Printablepekerjaan lebih sederhana dari kedua model pencetakan. Model ini hanya menggunakan satu PagePainteruntuk seluruh dokumen. Halaman dirender secara berurutan, dimulai dengan halaman nol. Ketika halaman terakhir dicetak, Anda PagePainterharus mengembalikan NO_SUCH_PAGEnilainya. Subsistem cetak akan selalu meminta aplikasi merender halaman secara berurutan. Sebagai contoh, jika aplikasi Anda diminta untuk merender halaman lima hingga tujuh, subsistem cetak akan meminta semua halaman hingga halaman ketujuh, tetapi hanya akan mencetak halaman lima, enam, dan tujuh. Jika aplikasi Anda menampilkan kotak dialog cetak, jumlah total halaman yang akan dicetak tidak akan ditampilkan karena tidak mungkin mengetahui sebelumnya jumlah halaman dalam dokumen yang menggunakan model ini.

Pageable

Pageablepekerjaan menawarkan lebih banyak fleksibilitas daripada Printablepekerjaan, karena setiap halaman dalam Pageablepekerjaan dapat menampilkan tata letak yang berbeda. Pageablepekerjaan paling sering digunakan dengan Books, kumpulan halaman yang dapat memiliki format berbeda. Saya akan menjelaskan Bookkelas sebentar lagi.

Sebuah Pageablepekerjaan memiliki karakteristik sebagai berikut:

  • Setiap halaman bisa memiliki pelukisnya sendiri. Misalnya, Anda bisa menggunakan pelukis untuk mencetak halaman sampul, pelukis lain untuk mencetak daftar isi, dan pelukis ketiga untuk mencetak seluruh dokumen.
  • Anda dapat mengatur format halaman yang berbeda untuk setiap halaman dalam buku tersebut. Dalam Pageablepekerjaan, Anda dapat menggabungkan halaman potret dan lanskap.
  • Subsistem cetak mungkin meminta aplikasi Anda untuk mencetak halaman tidak berurutan, dan beberapa halaman mungkin dilewati jika perlu. Sekali lagi, Anda tidak perlu mengkhawatirkan hal ini selama Anda dapat menyediakan halaman mana pun di dokumen Anda sesuai permintaan.
  • The Pageablepekerjaan tidak perlu tahu berapa banyak halaman dalam dokumen.

Buku

Juga baru karena versi 1.2 adalah Bookkelasnya. Kelas ini memungkinkan Anda membuat dokumen dengan banyak halaman. Setiap halaman dapat memiliki format dan pelukisnya sendiri, memberi Anda fleksibilitas untuk membuat dokumen yang canggih. Karena Bookkelas tersebut mengimplementasikan Pageableantarmuka, Anda dapat mengimplementasikan Bookkelas Anda sendiri jika kelas yang disediakan Booktidak memiliki fitur yang Anda perlukan.

Sebuah Bookkelas merupakan kumpulan halaman. Saat pertama kali dibuat, Bookobjek tersebut kosong. Untuk menambahkan halaman, Anda cukup menggunakan salah satu dari dua append()metode (lihat penjelasan saya tentang kelas ini di bagian API untuk lebih jelasnya). Parameter metode ini adalah PageFormatobjek, yang mendefinisikan karakteristik fisik laman, dan PagePainterobjek, yang mengimplementasikan Printableantarmuka. Jika Anda tidak mengetahui jumlah halaman dalam dokumen Anda, cukup teruskan UNKNOWN_NUMBER_OF_PAGESnilainya ke append()metode. Sistem printer secara otomatis akan mencari jumlah halaman dengan memanggil semua pelukis halaman di dalam buku hingga mendapat NO_SUCH_PAGEnilai.

Definisi API

Teori dan praktik akan bertemu di bagian ini. Di bagian sebelumnya, kita mempelajari tentang struktur halaman, unit pengukuran, dan model rendering. Di bagian ini, kita akan melihat API pencetakan Java.

Semua kelas yang diperlukan untuk mencetak terletak di dalam java.awt.printpaket, yang terdiri dari tiga antarmuka dan empat kelas. Tabel berikut menjelaskan kelas dan antarmuka paket cetak.

Nama Tipe Deskripsi
Paper Kelas Kelas ini menentukan karakteristik fisik halaman.
PageFormat Kelas PageFormatmenentukan ukuran dan orientasi halaman. Ini juga menentukan mana yang Paperakan digunakan saat merender halaman.
PrinterJob Kelas

Kelas ini mengatur pekerjaan cetak. Tanggung jawabnya termasuk membuat pekerjaan cetak, menampilkan kotak dialog cetak bila perlu, dan mencetak dokumen.

Book Kelas

Bookmewakili sebuah dokumen. Sebuah Bookobjek bertindak sebagai kumpulan halaman. Halaman yang termasuk dalam Bookkaleng memiliki format yang identik atau berbeda dan dapat menggunakan pelukis yang berbeda.

Pageable Antarmuka Sebuah Pageableimplementasi merupakan set halaman yang akan dicetak. The Pageableobjek mengembalikan jumlah halaman di set serta PageFormatdan Printableuntuk halaman tertentu. The Bookkelas mengimplementasikan interface ini.
Printable Antarmuka Seorang pelukis halaman harus mengimplementasikan Printableantarmuka. Hanya ada satu metode dalam antarmuka ini print(),.
PrinterGraphics Antarmuka The Graphicsobject yang mengimplementasikan interface ini. PrinterGraphicsmenyediakan getPrinterJob()metode untuk mendapatkan pekerjaan printer yang digunakan dalam proses pencetakan.

Antarmuka halaman

The Pageableantarmuka mencakup tiga metode:

Nama metode Deskripsi
int getNumberOfPages() Mengembalikan jumlah halaman dalam dokumen.
PageFormat getPageFormat(int pageIndex) Menampilkan halaman PageFormatseperti yang ditentukan oleh pageIndex.
Printable getPrintable(int pageIndex) Menampilkan Printableinstance yang bertanggung jawab untuk merender halaman yang ditentukan oleh pageIndex.

Antarmuka yang dapat dicetak

The Printableantarmuka memiliki satu metode dan dua nilai:

Nama Tipe Deskripsi
int print(Graphics graphics, PageFormat pageFormat, int pageIndex) metode

Meminta agar grafik menangani menggunakan format halaman yang diberikan merender halaman yang ditentukan.

NO_SUCH_PAGE Nilai Ini adalah sebuah konstanta. Kembalikan nilai ini untuk menunjukkan bahwa tidak ada lagi halaman untuk dicetak.
PAGE_EXISTS Nilai The print()kembali metode PAGE_EXISTS. Ini menunjukkan bahwa halaman yang diteruskan sebagai parameter ke print()telah dirender dan memang ada.

Setiap pelukis halaman harus mengimplementasikan Printableantarmuka. Karena hanya ada satu metode untuk diterapkan, membuat pelukis halaman mungkin tampak mudah. Namun, ingatlah bahwa kode Anda harus dapat membuat halaman apa pun masuk atau keluar dari urutan.

Ada tiga parameter untuk print(), termasuk Graphics, yang merupakan kelas yang sama yang digunakan untuk menggambar di layar. Karena Graphicskelas mengimplementasikan PrinterGraphicantarmuka, Anda bisa mendapatkan PrinterJobpekerjaan cetak ini. Jika tata letak halaman Anda rumit dan memerlukan beberapa fitur gambar lanjutan, Anda dapat mentransmisikan Graphicsparameter ke Graphics2Dobjek. Anda kemudian akan memiliki akses ke Java 2D API lengkap.

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.

Jean-Pierre Dube adalah konsultan Java independen. Ia mendirikan Infocom pada tahun 1988. Sejak itu, Infocom telah mengembangkan aplikasi kustom di berbagai bidang termasuk manufaktur, manajemen dokumen, dan manajemen saluran listrik berskala besar. Jean-Pierre memiliki pengalaman pemrograman yang luas dalam C, Visual Basic, dan Java; yang terakhir sekarang menjadi bahasa utama untuk semua proyek baru. Ia mendedikasikan seri ini untuk ibunya, yang meninggal saat menulis artikel ini.

Pelajari lebih lanjut tentang topik ini

  • "Mencetak di Jawa," Jean-Pierre Dubé ( JavaWorld )
  • Bagian 1: Kenali diri Anda dengan model pencetakan Java (20 Oktober 2000)
  • Bagian 2: Cetak halaman pertama Anda dan render dokumen yang rumit (1 Desember 2000)
  • Bagian 3: Jean-Pierre Dubé memperkenalkan kerangka kerja cetak yang bekerja di atas Java Print API (5 Januari 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

  • Mungkin buku terbaik tentang Java 2D, buku ini mencakup semua aspek API 2D dan juga menyediakan Graphicskerangka kerja untuk komposisi 2D tingkat lanjut: Grafik API 2D Jawa, Vincent J. Hardy (Prentice Hall, 1999)

    //www.amazon.com/exec/obidos/ASIN/0130142662/javaworld

  • Pengenalan yang sangat baik untuk Java 2D API "Memulai dengan Java 2D," Bill Day ( JavaWorld, Juli 1998)

    //www.javaworld.com/javaworld/jw-07-1998/jw-07-media.html

Kisah ini, "Mencetak di Jawa, Bagian 1" awalnya diterbitkan oleh JavaWorld.