Java printing program design full Raiders

xiaoxiao2021-03-06  41

Preface often requires printing function in our actual work. 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. Print 1 in Java 1, Java's printing API Java printing API is mainly present in the 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, how to implement printing to create 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; in JDK1.4, you can pass Javax.print.printSerivCelookup to find a print service object. 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, and now you can also pass Java.Awt .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. 3, the printer dialog 3.1 Printable Print dialog begins to display a print dialog by printerJob.PrintDialog prior to print jobs. 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. 3.2 ServiceUi's print dialog box is different from the Printable dialog box that the default behavior of the serviceUI's printer dialog box has been changed with the new API: The dialog box is not displayed by default. We must call the PrintDialog method using the ServiceUI class to create the print dialog as shown below. Java Printing Program Design Example 1 ? 1.2 Solution The basic idea is 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 specified printing graphics environment; PageFormat specifies the printing page format (the page size is set to a unit of 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); / / Set the print color to black if (Page> = PAGES) // When the print page number is larger than the total number of pages you need to print, the print job ends RETURN Printable.no_such_page; g2.translate (pf.getimageablex (), PF.GetImageAbley ); // conversion coordinate, determine print borders DrawCurrentPageText (G2, PF, PAGE); // Print the current page text Return Printable.page_exists; // Continue print job} / * Print the specified page number text * / private void drawCurrentPageText (Graphics2D g2, PageFormat pf, int page) {String s = getDrawText (printStr) [page]; // Get the text to be printed in this page // get the default font size and the appropriate FontRenderContext context = g2.GetFontrenderContext (); font f = area.getfont (); string drawtext; float ascent = 16; // given characters Data INT K, i = F.Getsize (), lines = 0; while (s. Length ()> 0 && lines <54) // Limited each page {k = s.indexof ('/ n'); // Get the position IF of each Enterprise (k! = -1) // There is a return letter {lines = 1; // calculate the number of lines DrawText = s.Substring (0, k); // Get every line of text G2.DrawString (DrawText, 0, ascent); // Specific print One line of text, simultaneous paper displacement IF (s.substring (k 1) .length ()> 0) {s = s.substring (k 1); // Intercepted text 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}}} / * Target text Press page to store the string array * / public string [] getdrawtext (string s) {string [] drawtext = new string [pages]; // According to the number of pages, INT I = 0; i 0) {IF (Lines <54) // Not a page {K = s.indexof ('/ n'); if (k! =

-1) // There is a return letter {lines = 1; // Route number is accumulated // calculates the specific text content of the page, stores the array element of 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 / / Put the text content to the corresponding array element DrawText [Suffix] = DrawText [SUFFIX] S; S = "";}} else // is full of pages {lines = 0; // Row count statistics clear suffix ; // A number of standards 1}} Return DrawText;} 2) Calculate the total number of pages that need to be printed Public INT getpageScount (String Curstr) {INT Page = 0; int position, count = 0; string str = curstr; while Str.Length ()> 0) // Text has not been calculated {position = str.indexof ('/ n'); // calculate the location of the return letter count = 1; // Statistics number IF (position! = -1) Str = str.substring (position 1); // Intercepting uncounted text Else Str = ""; // Text has been calculated} if (count> 0) Page = count / 54 1; // Taking the total number of points with a total of 54 Return Page; // Returns the total number of pages to be printed} 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 total number of pages printed PrinterJob myPrtJob = PrinterJob.getPrinterJob (); // get the default print job PageFormat pageFormat = myPrtJob.defaultPage (); // get the default print page format myPrtJob.setPrintable ( this, PageFormat; // Set the print job IF (MyPRTJob.PrintDialog ()) // Displays the print dialog {try {myprtjob.print (); // Perform specific print operation of each page} Catch (Printerexception PE) { PE.PrintStackTrace ();}}} Else {// If the print content is empty, prompt user printing will cancel JOPTIONPANE.SHOWCONFIRMDIALOG (Null, "Sorry, Printer Job Is Empty, Print Cancelle!", "EMPTY", JOPANE. Default_Option, JOPANE.WARNING_MESSAGE

Private void printText2Action () {printflag = 0; // Print flag clear zero printstr = area.getText (). Trim (); // Get target text IF you need to print (PrintStr! = null &&printstr.length ()> 0 ) // When the print content is not empty {pages = getpagescount (PrintStr); // Get the printout number // Specify the printout format DOCFLAVOR FLAVOR = DOCFLAVOR.Service_Formatted.printable; // Position the default print service printservice = PrintServiceLookup.lookupDefaultPrintService (); // create a print job DocPrintJob job = printService.createPrintJob (); // set the print properties PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet (); DocAttributeSet das = new HashDocAttributeSet (); // specify the print content Doc doc = new SimpleDoc (this, flavor, das); // Does not display the print dialog, directly print job try {job.print (DOC, PRAS); // Take specific print operation of each 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 Cancelle!", "EMPTY", JOPTYPANE.DEFAULT_OPTION, JOPTIONPANE.WARNING_MESSAGE);}} Print Preview 1, application scenario

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)

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 to the screen in a suitable scale;

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 the content to be printed to the screen * / public void PaintComponent (Graphics G) {Super.PaintComponent (G); graphics2d g2 = (graphics2d) g; pageformat pf = printerJob.getPrinterJob (). Defaultpage (); / / Get the page format Double Xoff; / / // The horizontal shift of the page initial position on the screen is offset; // Vertical offset on the page initial position Double Scale; // Suitable for the page on the screen Double PX = PF .GETWIDTH (); // page width double py = pf.getHeight (); // page height double sx = getWidth () - 1; double syl, = getHeight () - 1; if (PX / PY

Print graphics 1, application scenario

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?

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 component thereof * / private void printframeAction () {Toolkit Kit = Toolkit.getDefaultToolkit (); // Get Toolbox Properties Props = New Properties (); Props.Put ("awt.print .printer "," durango "); // Sets the print properties PrOPS.PUT (" AWT.PRINT.NUMCOPIES "," 2 "); if (kit! = null) {// Get the print object with the toolbox comes with PrintJob PrintJob = Kit.GetPrintJob (this, "Print Frame", Props); if (PrintJob! = null) {graphics pg = printJob.getgraphics (); // Get the graphical environment IF (PG! = null) {TRY {This.printall (PG); // Print the form and all its components} finally {pg.dispose (); // Logout graphic environment}} printJob.end (); // End print job}}} print file

1, application scenario

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?

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 a specified file * / private void printFileAction () {// a file selector configured, the current default directory JFileChooser fileChooser = new JFileChooser (SystemProperties.USER_DIR); int state = fileChooser.showOpenDialog (this); // pop File Selection dialog box if (state == filechooser.Approve_option) // If the user selects the file {file file = filechooser.getSelectedFile (); // Get selected file // Build print request attribute set PrintRibuteSet PRAS = new hashprintRequestattributeSet ( ); // Setting the print format, because the file type is not determined, here select Autosense Doclavor flavor = docflavor.input_stream.autosense; / / Find all available print services PrintService printservice [] = printservice = printservices (flavicelookup.lookupprintServices (flavic, PRAS); // positioning the default print service PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService (); // display the Print dialog box 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 DOCATRIBUTESET DAS = new hashdocattributeSet (); DOC DOC = New SimpleDoc (Fis, Flavor, DAS); // Establish print file format Job.Print (DOC, PRAS); // Print of file} catches (Exception E) {E.PrintStackTrace ();}}}} on top In the example, the type of file has not been determined, so 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.

Conclude

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

New Post(0)