Percetakan di Jawa, Bahagian 1

Sebelumnya 1 2 Halaman 2 Halaman 2 dari 2

Model rendering

Terdapat dua model percetakan di Java: Printablepekerjaan dan Pageablepekerjaan.

Alat cetak

Printablepekerjaan adalah lebih mudah daripada dua model percetakan. Model ini hanya menggunakan satu PagePainteruntuk keseluruhan dokumen. Halaman diberikan mengikut urutan, bermula dengan halaman sifar. Semasa halaman terakhir dicetak, anda PagePaintermesti mengembalikan NO_SUCH_PAGEnilainya. Subsistem cetak akan sentiasa meminta agar aplikasi membuat halaman mengikut urutan. Sebagai contoh, jika aplikasi anda diminta untuk membuat halaman lima hingga tujuh, subsistem cetak akan meminta semua halaman hingga halaman ketujuh, tetapi hanya akan mencetak halaman lima, enam, dan tujuh. Sekiranya aplikasi anda memaparkan kotak dialog cetak, jumlah halaman yang akan dicetak tidak akan dipaparkan kerana mustahil untuk mengetahui terlebih dahulu jumlah halaman dalam dokumen menggunakan model ini.

Halaman halaman

Pageablepekerjaan menawarkan lebih banyak fleksibiliti daripada Printablepekerjaan, kerana setiap halaman dalam Pageablepekerjaan dapat menampilkan tata letak yang berbeza. Pageablepekerjaan paling kerap digunakan dengan Books, kumpulan halaman yang boleh mempunyai format yang berbeza. Saya akan menerangkan Bookkelas sebentar lagi.

A Pageablepekerjaan mempunyai ciri-ciri berikut:

  • Setiap halaman boleh mempunyai pelukisnya sendiri. Sebagai contoh, anda boleh menggunakan pelukis untuk mencetak muka depan, pelukis lain untuk mencetak isi kandungan, dan yang ketiga untuk mencetak keseluruhan dokumen.
  • Anda boleh menetapkan format halaman yang berbeza untuk setiap halaman dalam buku. Dalam Pageablepekerjaan, anda boleh mencampurkan halaman potret dan landskap.
  • Subsistem cetak mungkin meminta aplikasi anda mencetak halaman mengikut urutan, dan beberapa halaman mungkin dilangkau jika perlu. Sekali lagi, anda tidak perlu risau tentang perkara ini selagi anda dapat membekalkan mana-mana halaman dalam dokumen anda berdasarkan permintaan.
  • The Pageablepekerjaan tidak perlu tahu berapa banyak laman dalam dokumen itu.

Buku

Juga baru kerana versi 1.2 adalah Bookkelas. Kelas ini membolehkan anda membuat dokumen berbilang halaman. Setiap halaman boleh mempunyai format dan pelukisnya sendiri, memberikan anda fleksibiliti untuk membuat dokumen yang canggih. Oleh kerana Bookkelas menggunakan Pageableantara muka, anda boleh melaksanakan Bookkelas anda sendiri apabila kelas yang disediakan Booktidak mempunyai ciri yang anda perlukan.

A Bookkelas mewakili kumpulan halaman. Semasa mula-mula dibuat, Bookobjek kosong. Untuk menambah halaman, anda hanya menggunakan salah satu daripada dua append()kaedah (lihat penjelasan saya mengenai kelas ini di bahagian API untuk maklumat lebih lanjut). Parameter kaedah ini adalah PageFormatobjek, yang menentukan ciri fizikal halaman, dan PagePainterobjek, yang menerapkan Printableantara muka. Sekiranya anda tidak mengetahui jumlah halaman dalam dokumen anda, cukup berikan UNKNOWN_NUMBER_OF_PAGESnilainya ke append()kaedah tersebut. Sistem pencetak akan mencari jumlah halaman secara automatik dengan memanggil semua pelukis halaman dalam buku sehingga menerima NO_SUCH_PAGEnilai.

Definisi API

Teori dan praktik akan dijumpai di bahagian ini. Pada bahagian sebelumnya, kami belajar tentang struktur halaman, unit pengukuran, dan model rendering. Pada bahagian ini, kita akan melihat API percetakan Java.

Semua kelas yang diperlukan untuk mencetak terletak dalam java.awt.printpakej, yang terdiri daripada tiga antara muka dan empat kelas. Jadual berikut menentukan kelas dan antara muka pakej cetak.

Nama Jenis Penerangan
Paper Kelas Kelas ini menentukan ciri fizikal halaman.
PageFormat Kelas PageFormatmenentukan ukuran dan orientasi halaman. Ini juga menentukan yang Paperakan digunakan ketika membuat halaman.
PrinterJob Kelas

Kelas ini menguruskan pekerjaan cetak. Tanggungjawabnya termasuk membuat pekerjaan cetak, menampilkan kotak dialog cetak apabila perlu, dan mencetak dokumen.

Book Kelas

Bookmewakili dokumen. A Bookobjek bertindak sebagai kumpulan halaman. Halaman yang disertakan dalam Bookkaleng mempunyai format yang sama atau berbeza dan boleh menggunakan pelukis yang berbeza.

Pageable Antara muka A Pageablepelaksanaan mewakili satu set halaman untuk dicetak. The Pageableobjek mengembalikan jumlah bilangan muka surat pada set serta PageFormatdan Printableuntuk halaman yang ditentukan. The Bookkelas melaksanakan antara muka ini.
Printable Antara muka Pelukis halaman mesti melaksanakan Printableantara muka. Hanya ada satu kaedah di antara muka ini , print().
PrinterGraphics Antara muka The Graphicsobjek melaksanakan antara muka ini. PrinterGraphicsmenyediakan getPrinterJob()kaedah untuk mendapatkan pekerjaan pencetak yang memulakan proses pencetakan.

Antara muka halaman

Antara Pageablemuka merangkumi tiga kaedah:

Nama kaedah Penerangan
int getNumberOfPages() Mengembalikan bilangan halaman dalam dokumen.
PageFormat getPageFormat(int pageIndex) Mengembalikan halaman PageFormatseperti yang ditentukan oleh pageIndex.
Printable getPrintable(int pageIndex) Mengembalikan Printablecontoh yang bertanggungjawab untuk membuat halaman yang ditentukan oleh pageIndex.

Antara muka yang boleh dicetak

Yang Printableantara muka mempunyai satu kaedah dan dua nilai:

Nama Jenis Penerangan
int print(Graphics graphics, PageFormat pageFormat, int pageIndex) Kaedah

Meminta agar grafik mengendalikan menggunakan format halaman yang diberikan menjadikan halaman yang ditentukan.

NO_SUCH_PAGE Nilai Ini adalah pemalar. Kembalikan nilai ini untuk menunjukkan bahawa tidak ada lagi halaman untuk dicetak.
PAGE_EXISTS Nilai The print()kaedah pulangan PAGE_EXISTS. Ini menunjukkan bahawa halaman yang dilewatkan sebagai parameter print()telah diberikan dan memang ada.

Setiap pelukis halaman mesti melaksanakan Printableantara muka. Oleh kerana hanya ada satu kaedah untuk dilaksanakan, membuat pelukis halaman mungkin kelihatan mudah. Walau bagaimanapun, ingat bahawa kod anda mesti dapat membuat halaman dalam atau tidak mengikut urutan.

Terdapat tiga parameter print(), termasuk Graphics, yang merupakan kelas yang sama yang digunakan untuk melukis di layar. Oleh kerana Graphicskelas menggunakan PrinterGraphicantara muka, anda boleh mendapatkan PrinterJobyang mencetak tugas cetak ini. Sekiranya susun atur halaman anda rumit dan memerlukan beberapa ciri gambar lanjutan, anda boleh menghantar Graphicsparameter ke Graphics2Dobjek. Anda kemudian akan mendapat akses ke Java 2D API penuh.

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 perunding bebas Java. Dia mendirikan Infocom pada tahun 1988. Sejak itu, Infocom telah mengembangkan aplikasi khusus dalam bidang termasuk pembuatan, pengurusan dokumen, dan pengurusan talian elektrik berskala besar. Jean-Pierre mempunyai pengalaman pengaturcaraan yang luas di C, Visual Basic, dan Java; yang terakhir sekarang menjadi bahasa utama untuk semua projek baru. Dia mendedikasikan siri ini untuk ibunya, yang meninggal semasa dia menulis artikel ini.

Ketahui lebih lanjut mengenai topik ini

  • "Mencetak di Jawa," Jean-Pierre Dubé ( JavaWorld )
  • Bahagian 1: Kenali model percetakan Java (20 Oktober 2000)
  • Bahagian 2: Cetak halaman pertama anda dan berikan dokumen yang rumit (1 Disember 2000)
  • Bahagian 3: Jean-Pierre Dubé memperkenalkan kerangka cetak yang berfungsi 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 di Java 2D, buku ini merangkumi semua aspek API 2D dan juga menyediakan Graphicskerangka kerja untuk komposisi 2D lanjutan: Java 2D API Graphics, Vincent J. Hardy (Prentice Hall, 1999)

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

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

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

Kisah ini, "Percetakan di Jawa, Bahagian 1" awalnya diterbitkan oleh JavaWorld.