Java printing program design

xiaoxiao2021-03-06  42

1 Foreword In our practical work, you often need to implement print function. 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 Printing in Java 2.1 Java Print APIJAVA'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 printing To generate 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. 2.3 Printer Dialog 2.3.1 Printable Print dialog Before you print, 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's print dialog box is different from the Printable dialog box that the default behavior of the serviceUI's printer dialog in JDK1.4 has 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 Printing Program Design Example 3.1 Printing Text 3.1.1 Application Scene Couw We need to print a form of a form (possibly only a few lines, may also contain multiple pages), and print up to 54 per page, How to achieve? 3.1.2 Solution The 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, when printing the button is clicked, perform the corresponding print action. The specific operation of printing text can be implemented via Graphics2D's DrawString method. 1. Implement Printable interface / * graphic specify the printing graphics environment; PageFormat Indicates the print 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, while paper transfer 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}}} / * 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 Initialization array for (int i = 0; i 0) {IF (Lines <

54) / / Not enough to {k = s.indexof ('/ n'); if (k! = -1) // Presented Enterprise {LINES = 1; // Route number is added // calculate 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; // Row number is accumulated // Put the text content to the corresponding array element DrawText [SUFFIX] = DrawText [SUFFIX] S; s = "";}} Else // is full of pages {lines = 0; // line count statistics clear suffix ; // array subtitle 1}} Return DrawText;} 2, the total number of pages that need to be printed PUBLIC INT getpageScount (string curStr) {int point, 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 number IF (position! = -1) str = str.substring (position 1); // Intercepting Nothing Capital 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 print the total number of pages} 3.1 Using JDK1.4 Previous Release Implementation Print Action Buttons to listen, and complete the specific print operation Private Void PrintTextac Tion () {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 jobs 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 }} 3.2, the API provided in JDK1.4, the Print Action button is listened, and the specific print operation private void printText2Action () {printflag = 0; // Print flag clever 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 print page // specify the number of printed output format DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; // locate the default print service PrintService printService = PrintServiceLookup.lookupDefaultPrintService (); // create a print job DocPrintJob job = printService.createPrintJob (); // set Print properties PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet (); DocAttributeSet das = new HashDocAttributeSet (); // specified print contents Doc doc = new SimpleDoc (this, flavor, das); // Print dialog box is not displayed, direct printing job try {job .print (DOC, PRAS); // Perform specific print operation of each page} CA TCH (PrintExtStackTrace ();}} else {// If the print content is empty, prompting user printing will cancel JOPTIONPANE.SHOWCONFIRMDIAROG (NULL, "Sorry, Printer Job Is Empty, Print Cancelle!", " Empty ", JOPANE.DEFAULT_OPTION, JOTIONPANE.WARNING_MESSAGE);}}}}}}}}}}}}}}} 3.2 Print preview 3.2.1 How many commercial applications in application scenario need to provide print preview mechanism, which allows us to see the page on the screen, so it will not be Waste Paper. 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 Thoughts: Although the Java2 Platform's printing API does not provide standard print preview dialog, but yourself It is not complicated to perform 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 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 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 of its components} finally {pg.dispose (); // logout graphic environment}} printjob.end (); // End print job}}} Print Files 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 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 DOCATTRIBUTESET DAS = new hashdocattributeSet (); DOC DOC = New SimpleDoc (FIS, FLAVOR, DAS); // Establish print file format Job.Print (DOC, PRAS); // Printing of file} Catch (Exception E) {E. PRINTSTACKTRACE ();}}}} In the above example, the type of file is not determined because 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.

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

New Post(0)