Easily print documents in Java

Source: Internet
Author: User
Tags processing text


A typical statement about implementing document printing in Java describes a complex process. It requires the determination of the font, parsing the text, and drawing the result into a Graphics object. This process seems quite difficult to execute, and it is inconsistent with the advanced programming method used for displaying document videos. If you want to spend a lot of effort to complete this process, you will not first think of programming in Java.

You do not want to complete the determination, parsing, and drawing process on your own. Instead, you want to simply send the document to an object that can handle everything for you to complete this task. This article will introduce such an object-DocumentRenderer, which uses a document as a parameter in the method and processes the specified task to print. For example, to use this class to display an HTML document requires two steps: Construct an instance of the javasentrenderer class and send the HTML document as a parameter to the print (HTMLDocument) method. The DocumentRenderer class is used to process the overhead required to print the document, including displaying a Print dialog box and formatting text. Download the source code for this class (DocumentRenderer. java ).

We designed this javasentrenderer class to take advantage of the advanced text performance that is already available in Java. Based on the principles of reusable and extensible classes, we use some existing objects (Java Swing Text Package uses it to format the Display Results) so that the printed results can be displayed on paper. The Design of javasentrenderer in this way enables us to create this class by writing nearly 200 lines of code less than the method discussed earlier.

In addition to the ability to write less code, the existing object in the implementation of javasentrenderer provides some additional functions to make this class more common. When we first designed this class, we just wanted to print out the HTML document. Adding some features to print other types of documents is a later idea. When we find that we can print a Rich Text Format document by adding about six lines of additional code to the code for the HTML printing class, we will add this function later in this project.

Show document
DocumentRenderer can be used to print several types of documents contained in JEditorPane. We tested this printer class using three types of documents (which can be identified by JEditorPane by default): HTMLDocuments, PlainDocuments, and Rich Text Format documents. This class should be able to print out other types of documents contained in JEditorPane with only a few minor changes.

The DocumentRenderer class separates the print form of a document from its video display. This allows you to format the text of specific printed results without affecting the screen display. DocumentRenderer uses the actual size of all printed pages to display text and calculate the line break ). This class allows scaling when the document width is insufficient to display on the print page ).

DocumentRenderer is quite intelligent. Page breaks do not divide a single statement into two pages. It will not be split into two halves. It will not display the upper half of a sentence at the end of the page while the lower half of the sentence will be displayed at the top of the next page. This class can process a large number of fonts, colors, and small icons. The column text (columnar text) is displayed. For the text features that each JEditorPane can display, usually entrenderer can present this performance on paper.

You only need to use two lines of code to combine javasentrenderer into your program. Create an instance of this class with a constructor without parameters, and then call an appropriate printing method to handle other things. For example, the following code prints this htmlDocument, which is a valid instance of the HTMLDocument class: DocumentRenderer extends entrenderer = new
DocumentRenderer ();
DocumentRenderer. print (htmlDocument );

It displays a Print dialog box that allows you to select a printer, print quantity, and cancel printing.

PlainDocuments uses the print (PlainDocument) method to print data in the same way as HTMLDocuments. Since Rich Text Format documents cannot be directly accessed in Java, you must send this type of documents to javasentrenderer (by encapsulating it into a JEditorPane), just like this: javasentrenderer. print (jeditorPane );

Here, jeditorPane is a valid example of JEditorPane, which contains a Rich Text Format document.

To make it easier for you, you can call the DocumentRenderer pageDialog method to display a Print dialog box so that you can adjust the page size, page edge settings, and paper orientation ). DocumentRenderer also provides a way for developers to choose whether to scale proportionally for documents that cannot be fully displayed within the print width. We think that zooming is usually a good choice, because it can prevent text from being separated at the correct page edge, but it seems suitable for users to choose. This setScaleWidthToFit (boolean) method provides the option of proportional scaling. You must be sure to call the scaling and pageDialog methods before calling the print method.

Learn more about DocumentRenderer
DocumentRenderer is used to display a Print dialog box and start Printing by using a standardized tool available in the Java Swing Printing API. Because you do not need to fully understand this API when using this DocumentRenderer class, and this API has been described in many places (see resources), we will not introduce it here. The source code for the DocumentRenderer class also contains the complete document of the print logic.

However, we may want to explain the process in which DocumentRenderer locates text on a separately printed page so that you can understand the improved functions provided by this class, this will help you review the logic of the display document that this Java printing process typically follows.

Documents are usually printed in a simple way. First, the document will be placed in JEditorPane. You can imagine the printing process as placing a rectangle on the JEditorPane (the size of the rectangle is equal to the size of the page printing area) and printing the content without caring about the outside part.

The top of the rectangle is flat with the top of the JEditorPane, and the area inside the rectangle is painted ). If the bottom of the rectangle passes through the text, you do not need to ignore it; the characters are separated at the bottom of the print page. When the second page is printed, the top of the rectangle is moved down to the row occupied by the front and bottom. This process is repeated. Because the second page starts at the end of the first page, the separated characters at the bottom of the first page will appear at the top of the second page. The same applies to the following pages.
To avoid disconnection from the line, DocumentRenderer checks the side document carefully to determine whether a separate text fits completely with the page. This is better than simply placing a rectangle in JEditorPane and printing the content.

View)
If you think of JEditorPane as a method that contains only one document, you cannot determine the position or size of all texts. A document is too large for this task. The document may fit into a single page, maybe not. To make the document fully fit with the printed paper, you must divide it into small parts to detect the position of each part.

Fortunately, the Java Swing Text Package provides a View class that allows you to divide a document into a single, well-drawn part. You can think of JEditorPane as composed of several view parts. Now you can print documents completely based on the size and position of these small parts.

The Child class of the View class is used to process the tasks of displaying and printing text in the visual component. However, what many programmers who process printed text do not realize is that views can provide these same functions when displayed on paper. Although a detailed discussion of the view is not a topic in this article, it is necessary to have a general understanding of the view during the document printing.

In Swing, a view is used as a container for processing text display. A root view in a tree directory can have multiple view branches. The leaf view that represents the real text is displayed at the end of these branches ).

Consider the tree structure of this view as a single, large view containing the entire text. This document view is divided into several paragraph views, which are divided into several separate rows in sequence. Although the view situation in real work is much more complex than this simple description, the example shows how to use a view to divide a document into smaller parts that fit the print paper. By checking each row, you can determine whether it fits exactly with the print paper without being separated at the bottom. If the number of rows matches, print the statement. If the number of rows does not match, record the statement to print the Statement on the next page.

The view contained in JEditorPane adopts an operation similar to the component behavior in JPanel. The main difference is that the view does not require layout managers for location processing. They will participate in the layout themselves. In this way, the view in JEditorPane operates like a real component and layout manager. The view knows how to view, how to draw itself, and where to display its subdocuments.

A view is not directly created. More specifically, they are generated by the factory of the ViewFactory subclass. A ViewFactory generates a document and divides it into the Root View and the required branch view and leaf view. The factory will handle these tedious parsing documents and computing la s in this way.

You rarely deal with these factories directly. For many parts, they are automatically called. Set the document in JEditorPane and call the JEditorPane. validate () method to send the document to the appropriate factory. The factory will return the required view. These views are then used in the layout of components.

Print View
The DocumentRenderer class can put the document to be printed into jeditorPane, which is an instance of JEditorPane. The width of jeditorPane determines the size of the printed page and it calls a verification method to execute the layout. DocumentRenderer does not display this JEditorPane, so the screen display does not take effect. The Root View to be printed is obtained through a complicated jeditorPane User Interface call: View rootView =
JeditorPane. getUI (). getRootView (jeditorPane );

This rootView and its subviews may query the required information to layout the printed document. These views provide coordinates and sizes in the drawing environment (graphical context) of each part of the text. With this information, you can determine whether the text matches the printed page. If the delimiter matches, the DocumentRenderer prints the content. If the delimiter does not match, this class will determine the paging character used to print this part of the text without separating it.

Because the view knows how to draw it by yourself, you do not need to set the font or color yourself. DocumentRenderer uses multiple fonts and colors to process styled text by calling the painting method of a simple view ).

However, the tree structure of this view is also stored.

Related Article

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.