Full introduction to Java Printing Program Design

Source: Internet
Author: User
Tags drawtext print object

Preface

In our actual work, printing is often required. However, due to historical reasons, the printing function provided by Java has always been weak. In fact, the original jdk does not support printing at all. It was not until jdk1.1 that a lightweight printing support was introduced. Therefore, in the previous programs designed using Java/Applet/JSP/Servlet, more complex printing is implemented by calling ActiveX/OCX controls or VB/VC programs, which is very troublesome. In fact, SUN has been committed to improving the Java printing function, and the Java2 Platform has finally begun a robust printing mode, which is fully integrated with the Java2D graphics package. Even more encouraging is that the newly released jdk1.4 provides a complete set of "Java Print Service APIs", which are a positive supplement to the existing printing functions. With this, we can achieve most of the actual application requirements, including printing text, graphics, files, and print preview. This article describes how to design a Java print program to implement these functions through a specific program instance, and analyzes and compares implementation methods of different versions, I hope you can get some useful tips.

  Printing in Java

1. Java printing API

Java printing APIs mainly exist in java. awt. print packages. The classes added by jdk1.4 mainly exist in the javax. print package and its corresponding sub-packages javax. print. event and javax. print. attribute. Javax. the print package mainly contains the printing service-related classes, while javax. print. event contains the definition of the printed event, javax. print. attribute includes the list of available attributes of the Print Service.

2. How to print

To generate a print, you must consider at least two:

A print service object is required. This can be implemented in three ways: java must be implemented in versions earlier than jdk1.4. awt. print. printable interface or through Toolkit. getdefatooltoolkit (). getPrintJob to get the print service object. In jdk1.4, you can use javax. print. printSerivceLookup is used to locate a printing service object.

You need to start a printing job. There are also several implementation methods: Before jdk1.4, you can use java. awt. print. printJob (provided by jdk1.1, which is rarely used now) calls the print or printAll method to start printing. You can also use java. awt. print. the printDialog of PrinterJob displays the print dialog box and starts printing using the print method. In jdk1.4, you can use javax. print. the printDialog of ServiceUI displays the print dialog box, and then calls the print method to start printing.

3. Printer dialog box

3.1 printing dialog box of Printable

Before printing, you can use PrinterJob. printDialog to display a Print dialog box. It gives the user a chance to select the page number range to be printed and allows the user to change the printing settings. It is a local dialog box.

In fact, when printing from a Printable object, the print object does not know how many pages need to be printed. It just keeps calling the print method. As long as the print method returns the Printable. PAGE_EXISTS value, the printing operation will generate printing pages continuously until the print method returns Printable. NO_SUCH_PAGE.

Since the page number is calculated accurately only after the printing is completed, the page number range on the dialog box is not initialized []. We can build a java. awt. print. the Book object is passed to the print object. You can also calculate the number of pages to be printed and pass it to the print object in the specified format so that it can accurately know how many pages to print.

3.2 print ServiceUI dialog box
 
Unlike the Printable dialog box, the default behavior of the printer dialog box that provides ServiceUI in jdk1.4 has been changed using a new API: by default, the dialog box is not displayed. You must use the ServiceUI class to call the printDialog method to create the following Print dialog box.

Java print program design example

1. Print text

1.1 application scenarios

Suppose we need to print a text editing field of a form (which may contain only a few lines or multiple pages) and print up to 54 lines per page. How can this problem be achieved?

1.2 Solution

The basic idea is as follows: first we need to implement the Printable interface, and then calculate the total number of pages to be printed based on the format of up to 54 lines per page. When the button for printing text is clicked, execute the corresponding print action. You can use the drawString method of Graphics2D to print text.

1) Implement the Printable Interface

/* Graphic indicates the Graphic environment for printing. PageFormat indicates the format of the printed page (the page size is measured by points, 1 inch of 1 point, 1/72 is 1 inch. A4 paper is roughly 595 × 842 points); page indicates the page number */

Public int print (Graphics g, PageFormat pf, int page) throws PrinterException {
Graphics2D g2 = (Graphics2D) g;
G2.setPaint (Color. black); // set the print Color to black.
If (page> = PAGES) // when the print page number is greater than the total number of PAGES to be printed, the printing process ends.
Return Printable. NO_SUCH_PAGE;
G2.translate (pf. getImageableX (), pf. getImageableY (); // convert coordinates to determine the print Boundary
DrawCurrentPageText (g2, pf, page); // print the current page text
Return Printable. PAGE_EXISTS; // If a page is printed, continue printing.
}

/* Print the specific text of the specified page number */
Private void drawCurrentPageText (Graphics2D g2, PageFormat pf, int page ){
String s = getDrawText (printStr) [page]; // obtain the content of the text to be printed on the current page.
// Obtain the default font and corresponding size
FontRenderContext context = g2.getFontRenderContext ();
Font f = area. getFont ();
String drawText;
Float ascent = 16; // specify the character lattice
Int k, I = f. getSize (), lines = 0;
While (s. length ()> 0 & lines <54) // each page is limited to 54 rows
{
K = s. indexOf (\\\\\\\\\\\\\\\\\\\\\); // obtain the location of each carriage return
If (k! =-1) // There Is A carriage return.
{
Lines + = 1; // calculate the number of rows
DrawText = s. substring (0, k); // obtain each line of text
G2.drawString (drawText, 0, ascent); // print each line of text and shift the text at the same time.
If (s. substring (k + 1). length ()> 0 ){
S = s. substring (k + 1); // extract unprinted text
Ascent + = I;
}
}
Else // The carriage return does not exist.
{
Lines + = 1; // calculate the number of rows
DrawText = s; // obtain each line of text
G2.drawString (drawText, 0, ascent); // print each line of text and shift the text at the same time.
S = ""; // text ended
}
}
}

/* Save the printed target text as a string array by page */
Public String [] getDrawText (String s ){
String [] drawText = new String [PAGES]; // initializes an array based on the number of PAGES
For (int I = 0; I <PAGES; I ++)
DrawText [I] = ""; // array element Initialization is an empty string
Int k, suffix = 0, lines = 0;
While (s. length ()> 0 ){
If (lines <54) // when one page is insufficient
{
K = s. indexOf (\\\\\\\\\\\\\\\\\\\\\\);
If (k! =-1) // There Is A carriage return.
{
Lines + = 1; // accumulate the number of rows
// Calculate the specific text content of the page and store it to the corresponding array element
DrawText [suffix] = drawText [suffix] + s. substring (0, k + 1 );
If (s. substring (k + 1). length ()> 0)
S = s. substring (k + 1 );
}
Else
{
Lines + = 1; // accumulate the number of rows
// Store text content to corresponding array elements
DrawText [suffix] = drawText [suffix] + s;
S = "";
}
}
Else // when the page is full
{
Lines = 0; // The number of rows is cleared.
Suffix ++; // Add 1 to the array subscript
}
}
Return drawText;
}


2) calculate the total number of pages to be printed

Public int getPagesCount (String curStr ){
Int page = 0;
Int position, count = 0;
String str = curStr;
While (str. length ()> 0) // The text has not been calculated.
{
Position = str. indexOf (\\\\\\\\\\\\\\\\\\\\); // calculates the location of the carriage return.
Count + = 1; // count the number of rows
If (position! =-1)
Str = str. substring (position + 1); // extract uncomputed text
Else
Str = ""; // The text has been calculated
}
If (count> 0)
Page = count/54 + 1; // divide the total number of rows by 54 to obtain the total number of pages
Return page; // return the total number of pages to be printed.
}


Use a previous version of jdk1.4 to implement the print action button monitoring and complete the specific print operations.

Private void printTextAction (){
PrintStr = area. getText (). trim (); // obtain the target text to be printed.
If (printStr! = Null & printStr. length ()> 0) // when the printed content is not empty
{
PAGES = getPagesCount (printStr); // obtain the total number of printed PAGES
PrinterJob myPrtJob = PrinterJob. getPrinterJob (); // get the default print job
PageFormat pageFormat = myPrtJob. defaultPage (); // obtain the default print page format
MyPrtJob. setPrintable (this, pageFormat); // set the printing job
If (myPrtJob. printDialog () // display the Print dialog box
{
Try {
MyPrtJob. print (); // print each page
}
Catch (PrinterException p

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.