Java printing program design

xiaoxiao2021-03-06  39

1 Introduction

In our practical work, print function often needs to be implemented. However, due to historical reasons, Java provides printing functionality has been relatively weak. In fact, the initial JDK does not support print until JDK1.1 introduces very lightweight print support. Therefore, in the previous program designed by Java / Applet / JSP / Servlet, more complex printing is made by calling an ActiveX / OCX control or VB / VC program. In fact, Sun also has been committed to the improvement of Java printing, and the Java2 platform finally has a robust print mode, which is integrated with the Java2D graphics package. More encouraging, the newly released JDK1.4 provides a complete "Java Print Service API", which is a positive supplement to existing print features. With it, we can achieve most practical applications, including print text, graphics, files, and print previews. This article will explain how to design a Java print program through a specific program example to implement these functions, and analyze the different versions of implementation methods. I hope that you can get some useful tips.

2 Print in Java

2.1 Java Print API

Java's printing API mainly exists in a java.awt.print package. The new class of JDK1.4 is mainly present in the Javax.Print package and its corresponding subcaps javax.print.event and javax.print.attribute. The Javax.Print package mainly contains related classes of the print service, while javax.print.event contains the definition of the print event, Javax.print.attribute, includes a list of available properties of the print service.

2.2 How to implement print

To produce a print, at least two: need a print service object. This can be implemented in three ways: the version before JDK1.4, you must implement the java.awt.print.printable interface or through Toolkit.getDefaultToolkit (). GetPrintJob to get the print service object; you can Locate a print service object by javax.print.printserivcelookup. Need to start a print job. This also has several implementation methods: You can start printing in java.awt.print.printJob before JDK1.4, now it is rarely used. You can also pass Java.aw. .print.printerjob's PrintDialog Displays the print dialog box and then starts printing by the Print method; in JDK1.4, you can display the print dialog through the Javax.Print.Serviceui's PrintDialog, and then call the print method to start a print job.

2.3 Printer Dialog

2.3.1 Printable print dialog

Before you start printing, you can display a print dialog with PrinterJob.PrintDialog. It gives the user a chance to select the range range that should be printed and can be used to change the print settings. It is a local dialog. In fact, when a print job is performed from a printable object, the print object does not know how many pages needed to print. It just keeps calling the Print method. As long as the print method returns a printable.page_exists value, the print job will stop generating a print page until the print method returns printable.no_such_page, the print job stops. Since the print job is calculated only after the print is completed, the page number on the dialog is not initialized [1,9999]. We can pass to the print object by building a java.awt.print.book object; you can also calculate the number of pages you need to print through the specified format and passed to the print object, which accurately knows how many pages are to print. 2.3.2 ServiceUI Print Dialog

Unlike Printable dialogs, the default behavior of the JDK1.4 provides the default behavior of the serviceUI's printer dialog that has been changed with the new API: By default, the dialog is not displayed. We must call the PrintDialog method using the ServiceUI class to create the print dialog as shown below.

3 Java print program design instance

3.1 Printing Text

3.1.1 Application Scene

Suppose we need to print a text editing domain (may have only a few lines, may also contain multiple pages), and print up to 54 per page, how to implement it?

3.1.2 Solution

Basic ideas are as follows: First we need to implement the Printable interface, then calculate how many pages in the format of up to 54 rows per page, and perform the corresponding print action when printing the button is clicked. The specific operation of printing text can be implemented via Graphics2D's DrawString method. 1. Implement Printable Interface / * Graphic Indicate Print Graphics Environment; PageFormat Indicates Print Page Format (the page size is set to measurement unit, 1 point is 1 talent 1/72, 1 inches of 25.4 mm. A4 paper is approximately 595 × 842 points); Page Indication page number * / public int print (Graphics G, Pageformat Pf, INT Page "throws printerexception {graphics2d g2 = (graphics2d) g; g2.setpaint (color.black); // Setting print color is black IF (Page> = PAGES) // When the print page number is larger than the total number of pages that need to be printed, the print job ends

Return Printable.no_such_page; g2.translate (pf.getimageable), pf.getimageable (); // Convert coordinate, determine print borders DrawCurrentPageText (G2, PF, PAGE); // Print current page text Return Printable.page_exists; / / Continue printing when there is a print page

} / * Print the specific text content of the specified page number * /

Private Void DrawCurrentPageText (Graphics2D G2, PageFormat Pf, INT Page) [Page]; // Get the contents of the current page to print text content / / Get the default font and the corresponding size

FontrenderContext CONTEXT = G2.GetFontrenderContext (); font f = area.getfont (); string drawtext; float ascent = 16; // Given the character dot array INT K, I = F.Getsize (), lines = 0; while (WHILE) S.Length ()> 0 && line <54) / / per page limited to within 54 lines

{K = s.indexof ('/ n'); // Get the position IF (k! = -1) // existing Enterprise

{Lines = 1; // Calculate the number of lines DrawText = s.Substring (0, k); // Get every line of text G2.DrawString (DrawText, 0, ascent); // Specific print every line of text, Shift

IF (s.Substring (k 1) .length ()> 0) {s = s.substring (k 1); // Intercepted text that has not yet printed

Ascent = i;}} else // does not exist

{Lines = 1; // Calculate the number of lines DrawText = S; // Get every line of text G2.DrawString (DrawText, 0, ascent); // Specific printing every line of text, while paper shift s = "" // Text has ended

}}} / * Press the print target text to the string array * /

Public string [] getdrawtext (string s) {string [] drawtext = new string [pages]; / / According to the number of pages

For (int i = 0; i

INT K, SUFFIX = 0, LINES = 0; while (s.Length ()> 0) {if (Lines <54) // Not enough

{K = s.indexof ('/ n'); if (k! = -1) // There is a return service

{LINES = 1; // Route number Add // calculate the specific text content of the page, store the array element to the corresponding subscript

DrawText [SUFFIX] = DrawText [SUFFIX] S.Substring (0, K 1); if (s.SUBSTRING (K 1) .length ()> 0) s = s.substring (k 1);} Else {lines = 1; // Route number is accumulated // Put the text content to the corresponding array element DrawText [SUFFIX] = DrawText [SUFFIX] S; S = "";}} Else // is full

{Lines = 0; // line count statistics clear suffix ; // array subtracted 1

}}}}} 2, the total number of pages that need to be printed public int getpagescount (string curStr) {int point = 0; int position, count = 0; string str = curStr; while (str.length ()> 0) // Text has not been calculated

{Position = str.indexof ('/ n'); // calculate the position of the return letter count = 1; // Statistics

IF (position! = -1) str = str.substring (position 1); // Intercepted text

Else Str = ""; // Text has been calculated

} If (count> 0) Page = count / 54 1; // Remove the total number of pages by 54 with 54 RETURN PAGE; // Return to the total number of pages to print

} 3.1, implement the print action button to listen by JDK1.4, and complete the specific print operation private void printTextAction () {PrintStr = area.getText (). Trim (); // Get the target text IF you need to print ( Printstr! = null &&printstr.length ()> 0) // When the print content is not empty

{Pages = getpageScount (PrintStr); // Get the number of printing Page PrinterJob MyPRTJOB = PrinterJob.getPrinterJob (); // Get the default print job PageFormat PageFormat = MyPRTJob.defaultPage (); // Get the default print page format

MyPRTJob.SetPrintable (this, PageFormat); // Setting the print job if (MyPRTJob.PrintDialog ()) // Displays the print dialog

{Try {myprtjob.print (); // Specific print operation per page} catch (printerexception pe) {pe.printStackTrace ();}}} else {// If the print content is empty, prompt user printing cancel

JOptionPane.showConfirmDialog (null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);}} 3.2, the new version offers API jdk1.4 to achieve print button action listener And complete the specific print operation private void printText2Action () {printflag = 0; // Print flag clear zero printstr = area.getText (). Trim (); // Get the target text IF you need to print (PrintStr! = Null && PrintStr.length ()> 0) // When the print content is not empty

{Pages = getpageScount (Printstr); // Get the number of print points / / Specify the printout format

DOCFLAVOR flavor = docflavor.service_formatted.printable; // Positioning the default print service

PrintService PrintService = PrintServiceLookup.lookupdefaultPrintService (); // Create a print job

DOCPRINTJOB JOB = PrintService.createPrintJob (); // Setting print properties

PrintRequestAttributeSet PRAS = new hashprintrequestattributeset (); DOCATTRIBUTESET DAS = new hashdocattributeset (); // Specify print content

DOC DOC = New SimpleDoc (this, flavor, das); // Do not display the print dialog, print jobs

Try {Job.Print (DOC, PRAS); / / Specific print operation per page

} Catch (printexception pe) {pe.printstacktrace ();}} else {// If the print content is empty, prompting the user print will cancel

JOPTIONPANE.SHOWCONFIRMDIALOG (NULL, "Sorry, Printer Job Is Empty, Print Cancelled!", "EMPTY", JOPANE.DEFAULT_OPTION, JOPANE.WARNING_MESSAGE);}}}}}}}}}}}}

3.2.1 Application Scene

Most commercial applications require print preview mechanisms that allow us to see the page on the screen, so you will wast paper because you don't like print results. Suppose we need to print preview before printing the text mentioned by the previous section. So how do you implement it? The interface implementation is shown below: (Next Preview Next page, Preview Preview Previous page, Close Close Preview)

3.2.2 Solution

Basic ideas: Although the Java2 platform prints API does not provide a standard print preview dialog, it is not complicated to design. Normally, the Print method plots the page environment into a printer graphics environment to implement print. In fact, the Print method does not really produce a print page, which just draws the content to the graphical environment. Therefore, we can ignore the screen graphics environment, through the appropriate scale, so that the entire print page is hosted in a screen rectangle to achieve accurate print preview. In the design implementation of the print preview, it is mainly necessary to solve two problems. First, how to draw the print content in a suitable scale to the screen; second, how to implement the front and reappere. Below I gave the specific implementation method of these two questions, please refer to the PrintPreviewDialog.java file in the attachment. / * Draw to the screen * /

public void paintComponent (Graphics g) {super.paintComponent (g); Graphics2D g2 = (Graphics2D) g; PageFormat pf = PrinterJob.getPrinterJob () defaultPage ();. // get page format double xoff; // page on the screen The horizontal offset of the initial position Double Yoff; // Vertical offset in the initial position of the page on the screen

Double scale; // Suitable on the screen for the proportion of the page Double PX = pf.getWidth (); // page width double py = pf.getHeight (); // page height

Double SX = getWidth () - 1; Double Sy = getHeight () - 1; if (PX / PY

YOFF = 0;} else {scale = SX / PX; // calculation ratio

XOFF = 0; YOFF = 0.5 * (Sy - scale * py); // Vertical offset

} G2.translate ((float) Xoff, (float) yoff; // conversion coordinate

g2.scale (Float) Scale (FLOAT); Rectangle2D Page = New Rectangle2D.double (0, 0, PX, PY); // Draw Page Rectangle G2.SetPaint (Color.White); // Settings page The background is white g2.fill (page); g2.setpaint (color.black); // Set page text is black

g2.draw (page); try {preview.print (G2, PF, CURRENTPAGE); / / Display the specified preview page

} Catch (printerexception pe) {g2.draw (new line2d.double); g2.draw (new line2d.double (0, px, 0, py));}} / * preview Specified page * /

Public void viewpage (int 4) {int newpage = currentpage pos; // Specify the page in the actual range

IF (0 <= newpage ") {currentpage = newpage; // Assign the specified page to the current page

Repaint ();}} This, only when the "Next" button is pressed, only need to call canvas.viewPage (1); when pressing the "Preview" button, you only need to call canvas.ViewPage (-1) to implement The front and rear pages of the preview.

3.3 Print Graphics

3.3.1 Application Scene

In practical applications, we also need to print graphics. For example, we sometimes need a full interface of a Java Applet or a application form and all components therebet all the components, how should it be implemented?

3.3.2 Solution

The basic ideas are as follows: All the Print and Printall methods are provided in the Java's Component class and its derived class. These two methods can be called directly to the components and graphics as long as they set the properties. / * Print the specified form and the components therebet * /

Private void printfraMection () {Toolkit Kit = Toolkit.getDefaultToolkit (); // Get Toolbox

Properties PROPS = New Properties (); Props.Put ("AWT.PRINT.PRINTER", "DURANGO"); // Setting print properties

Props.PUT ("AWT.PRINT.NUMCOPIES", "2"); if (kit! = null) {// Get print objects comes with the toolbox

PrintJob PrintJob = Kit.getPrintJob (this, "print frame", props); if (PrintJob! = Null) {graphics pg = printjob.getgraphics (); // Get the graphics environment of the print object

IF (pg! = null) {Try {this.printall (PG); // Print the form and all of its components} finally {pg.dispose (); // Logout graphics environment

} }Printjob.end (); // End print job

}}}

3.4 Print file

3.4.1 Application Scene

In many practical applications, we may need to print a file specified by the user. This file may be graphical files such as GIF, JPEG, etc. may also be text files, such as txt, java files, etc.; may also be complex PDF, DOC files, etc. So how should we achieve this for such print demand?

3.4.2 Solution

Basic Ideas: In JDK1.4, it is very troublesome and complicated to achieve such printing functions, even unimaginable. But fortunately, JDK1.4's print service API provides a set of classes and methods for printing file streams. With them, we can make it easy and easily to achieve a variety of different types of file printing. A universal processing method is given below. / * Print the specified file * /

Private void printfileAction () {// Constructs a file selector, default is the current directory

Jfilechooser filechooser = new jfilechooser (SystemProperties.user_dir); int 2 = filechooser.showopendialog (this); // Popup file selection dialog if (state == filechooser.Approve_option) // If the user selected files

{File file = filechooser.getSelectedFile (); // Get the selected file // Build print request property set

PrintRequestAttributeSet PRAS = new hashprintRequestattributeSet (); // Setting the print format, because the file type is not determined, here is autosense

Docflavor flavor = docflavor.input_stream.autosense; / / Find all available print services

PrintService PrintService [] = PrintServiceLookup.lookuppprintServices (Flavor, PRAS); // Location Default Print Service

PrintService DefaultService = PrintServiceLookup.lookupdefaultPrintService (); // Displays the print dialog

PrintService service = ServiceUI.printDialog (null, 200, 200, printService, defaultService, flavor, pras); if (service = null!) {Try {DocPrintJob job = service.createPrintJob (); // Create a print job FileInputStream fis = new FileInputStream (file); // Configure the file stream to be printed DOCATTRIBUTESET DAS = new hashdocattributeSet (); DOC DOC = New SimpleDoc (Fis, Flavor, DAS); // Establish print file format Job.Print (DOC, PRAS); / / Printing

} CatCH (Exception E) {E.PrintStackTrace ();}}}} In the above example, the type of file is not determined, the print format of the specified file is defined as Docflavor.input_Stream.autosense. In fact, if you have confirmed the format of the file before printing, if GIF, you should be defined as DOCFLAVOR.INPUT_STREAM.GIF; if it is PDF, it should be defined as docflavor.input_stream.pdf; as pure ASCII Files, you can define DOCFLAVOR.INPUT_STREAM.TEXT_HTML_US_ASCII. and many more. JAVAX.Print.docflavor of JDK1.4 provides an extremely rich file stream type, which you can make appropriate options depending on the specific application needs. The specific API reference documentation can be seen in this article 3.

4 Conclusion

The above is some of the experiences in the J2EE application development, summarizing some experiences with Java printing programming, hoping to give you some revelations and benefits. Although the print function is currently used in Java, it is still more trouble compared with Microsoft's MFC API. However, JDK1.4 is launched, and the printed print function before Java is an excellent complement. I believe that if you can understand the print program design examples described above and apply and expand, you should be able to solve the actual programming issues of currently most applications. With the further development and improvement of Java, it will better enrich its basic class libraries and print APIs. I believe that advanced printing functions to implement Java will also become more and more increasingly becoming a headache of our Java obsesses.

5 References "Java2 Core Technology Volume II: Advanced Characteristics" Machinery Press Java Print Service Reference Document: http://java.sun.com/j2se/1.4/docs/guide/jps/ JDK1.4 API Reference Document: Http://java.sun.com/j2se/1.4/docs/api/

转载请注明原文地址:https://www.9cbs.com/read-64834.html

New Post(0)