How to generate pdf and excel in java

Source: Internet
Author: User
Tags image png processing text

During this time, I took over a project and generated pdf and word in java. I found some good information on the Internet and put it here for learning. I. Preface in enterprise information systems, report processing has always played an important role. This article will introduce iText, a Java component for generating PDF reports. By using Jsp or JavaBean on the server side to generate a PDF report, the client displays or downloads the generated report through a super connection, which effectively solves the Report Processing Problem of the B/S system. II. Introduction to iText is a well-known open source site sourceforge project. It is a java class library used to generate PDF documents. Using iText, you can not only generate PDF or rtf documents, but also convert XML and Html files into PDF files. The installation of iText is very convenient, download iText on the http://www.lowagie.com/iText/download.html-download website. after the jar file, you only need to add iText. jar path, you can use the iText class library in the program. 3. Five steps are required to create the first PDF Document to generate a PDF Document using iText: ① create an instance of the com. lowagie. text. Document Object. Document document = new Document (); ② establish a Writer to associate with the document object. The Writer can write the Document to the disk. Using writer. getInstance (document, new FileOutputStream ("Helloworld. PDF"); ③ open the document. Document. open (); ④ add content to the document. Document. add (new Paragraph ("Hello World"); ⑤ close the document. Document. close (); the preceding five steps generate a Helloworld. PDF file with the content "Hello World ". Create com. lowagie. text. the instance com. lowagie. text. there are three Document Object Construction functions: public Document (); public Document (Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom); The pageSize parameter of the build function is the size of the Document page. For the first build function, the page size is A4, the same as Document (PageSize. a4). For the third build function, the parameters marginLeft, marginRight, marginTop, and marginBottom are left, right, top, and bottom margins respectively. The pageSize parameter allows you to set attributes such as page size, surface background color, and page horizontal/vertical. IText defines paper types such as A0-A10, AL, LETTER, HALFLETTER, _ 11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA and FLSE, you can also use Rectangle pageSize = new Rectangle (144,720); to customize the paper. You can use the Rectangle method rotate () to set the page to horizontal. Once a Writer object is created for a document object, one or more Writer objects need to be associated. Html. HtmlWriter can save a document as an html file. Before opening a document, you can set the document title, topic, author, keyword, binding method, creator, producer, and creation date. The called methods are as follows: public boolean addTitle (String title) public boolean addSubject (String subject) public boolean addKeywords (String keywords) public boolean addAuthor (String author) public boolean addCreator (String creator) public boolean addProducer () public boolean addCreationDate () public boolean addHeader (String name, String content) where the addHeader method is The file is invalid. addHeader is only valid for html documents and is used to add document header information. Before a new page is generated, you can set the page size, bookmarks, HeaderFooter, and other information. The call method is public boolean setPageSize (Rectangle pageSize) public boolean add (Watermark watermark) public void removeWatermark () public void setHeader (HeaderFooter header) public void resetHeader () public void setFooter (HeaderFooter footer) public void resetFooter () public void resetPageCount () public void setPageCount (int pageN) If you want to set page properties on the first page, these methods must be called before the document opens. For PDF documents, iText also provides the document display attributes. You can call the setViewerPreferences method of the writer to control the display attributes of Acrobat Reader when the document is opened, such as whether to display a single page, whether to display a full screen, and whether to hide status entries. In addition, iText provides security protection for PDF files. Using the setEncryption method of Writer, you can set the user password, read-only, printable, and other attributes of a document. Add document content all content added to the document is in the unit of objects, such as Phrase, Paragraph, Table, and Graphic objects. Commonly used is a Paragraph (Paragraph) object, used to add a Paragraph of text to the document. 4. Text Processing in iText, text is processed using text blocks (Chunk), phrases (Phrase), and paragraphs (paragraph. A Chunk is the smallest unit for processing text. It consists of a string with a format (including font, color, and size. The following code generates a character string with a font of HELVETICA, a size of 10, and an underscore: Chunk chunk1 = new Chunk ("This text is underlined", FontFactory. getFont (FontFactory. HELVETICA, 12, Font. UNDERLINE); a Phrase (Phrase) consists of one or more chunks, and a Phrase (Phrase) can also be set to a font, however, the Chunk is invalid. You can use the Phrase (Phrase) member function add to add a text block (Chunk) to the Phrase (Phrase), for example, phrase6.add (chunk); paragraph (paragraph) it is composed of one or more chunks or phrases (Phrase). It is equivalent to the Section concept in a Word document and can also set the font size, color, and other attributes of a paragraph. You can also set the indent and alignment of the first line of a paragraph (left-aligned, right-aligned, and center-aligned ). You can use the setAlignment function to set the paragraph alignment. The setAlignment parameter 1 is centered, 2 is right, and 3 is left alignment. The default value is left alignment. 5. Table processing in iText: com. lowagie. text. table and com. lowagie. text. PDF. PDFPTable. For simple table processing, you can use com. lowagie. text. table, but if you want to process complex tables, this requires com. lowagie. text. PDF. PDFPTable. Com. lowagie. text. Table is described here. Class com. lowagie. text. there are three Table constructors: ① Table (int columns) ② Table (int columns, int rows) ③ Table (Properties attributes) the columns, rows, and attributes parameters are the number of columns, number of rows, and table attributes of the table. When creating a table, you must specify the number of columns in the table. You do not need to specify the number of rows. After creating a table, you can set attributes of the table, such as the Border width, border color, and padding (padding space. The following code uses a simple example to describe how to use a Table: 1: table Table = new table (3); 2: Table. setBorderWidth (1); 3: table. setBorderColor (new Color (0, 0,255); 4: table. setPadding (5); 5: table. setSpacing (5); 6: Cell cell = new Cell ("header"); 7: cell. setHeader (true); 8: cell. setColspan (3); 9: table. addCell (cell); 10: table. endHeaders (); 11: cell = new Cell ("example cell with colspan 1 and rowspan 2"); 12: cell. setRowspan (2); 13: cell. setBorderColor (n Ew Color (255, 0, 0); 14: table. addCell (cell); 15: table. addCell ("1.1"); 16: table. addCell ("2.1"); 17: table. addCell ("1.2"); 18: table. addcells ("2.2"); 19: table. addCell ("cell test1"); 20: cell = new Cell ("big cell"); 21: cell. setRowspan (2); 22: cell. setColspan (2); 23: table. addCell (cell); 24: table. addCell ("cell test2"); the running result is as follows: Line 1-5 of header cell test2 code is used to create a new table. As shown in the code, a table with 3 columns is created, set the Border width to 1, the color to blue, and the padding to 5. Line 6-10 of the Code is used to set the table header and Line 4 of cell. setHeader (true); displays the cell as the header information; 8th rows of cells. setColspan (3); specify that the cell occupies three columns. When adding table header information, note that once the table header information is added, you must call the endHeaders () method, for example, Row 3. Otherwise, the header information is not displayed after the table is displayed across pages. Line 11-14 of the Code adds a cell with a column width and a row length to the table. When a cell is added to a table, it is added from left to right and from top to bottom. For example, after executing 11 lines of code, there is a blank space in two rows and two columns in the lower right corner of the table. When adding cells to the table, fill in the blank space first, and then start another row, lines 15-24 indicate the order of adding. 6. The class for processing tables in image processing iText is com. lowagie. text. currently, iText supports GIF, Jpeg, PNG, and wmf formats. For different Image formats, iText uses the same constructor to automatically recognize the Image format. The following code obtains examples of gif, jpg, and png images. Image gif = Image. getInstance ("vonnegut.gif"); Image jpeg = Image. getInstance ("myKids.jpg"); Image png = Image. getInstance ("hitchcock.png"); position of the image the position of the image mainly refers to the alignment of the image in the document, and the positional relationship between the image and the text. In IText, the public void setAlignment (int alignment) function is used for processing. The alignment parameter is Image. RIGHT, Image. MIDDLE, Image. LEFT indicates the right alignment, center, and LEFT alignment. TEXTWRAP, Image. UNDERLYING indicates that the text is displayed in a circular image and the image is displayed as the background of the text. These two parameters can be combined to achieve the expected effect. For example, the effect displayed by setAlignment (Image. RIGHT | Image. TEXTWRAP) is the RIGHT alignment of the Image, and the text is displayed around the Image. Image Size and rotation if the image is not displayed in the document according to the original size, you can use the following function to set: public void scaleAbsolute (int newWidth, int newHeight) public void scalePercent (int percent) public void scalePercent (int percentX, int percentY) function public void scaleAbsolute (int newWidth, int newHeight) directly sets the display size; function public void scalePercent (int percent) sets the display proportion, for example, scalePercent (50) indicates that the display size is 50% of the original size, while scalePercent (int percentX, int percentY) indicates the display ratio of the image height and width. If the image needs to be rotated after a certain angle, you can use the public void setRotation (double r) function to set the parameter r to radian. If the rotation angle is 30 degrees, then the parameter r = Math. PI/6. 7. The default iText font setting for Chinese processing does not support Chinese fonts. You need to download the Far East font package iTextAsian. jar. Otherwise, you cannot output Chinese fonts to the PDF file. The following code can be used in Chinese: BaseFont bfChinese = BaseFont. createFont ("STSong-Light", "UniGB-UCS2-H", BaseFont. NOT_EMBEDDED); com. lowagie. text. font FontChinese = new com. lowagie. text. font (bfChinese, 12, com. lowagie. text. font. NORMAL); Paragraph pragraph = new Paragraph ("hello", FontChinese); 8. There are many advanced functions in post-computation iText, which will not be described here, for more information, see the published document. In general, iText is a set of good PDF components in the java environment. Because iText supports jsp/javabean development, the report problem in B/S applications can be well solved. Because iText is not designed specifically for report production, all the content and formats in the report must be implemented by writing code. Compared with professional report software that supports visual design, the programming workload increases to a certain extent. Java pdf Program Generation example: as a program developer, HelloWorld is no stranger to the HelloWorld program. Almost every language or application will always give you a HelloWorld example. When introducing iText, we may also start to run the above Code from HelloWorld (remember to put itext. jar in your ClassPath). If everything is normal, you will see a file named helloworkflow in "c:/examples. Open this file. What do you see? Yes. The document contains a line of characters "HelloWorld", for example. How is it easy? Of course, in actual application, it is impossible to simply output a string and complete the process. We also need to do a lot of work to output more complex PDF files, next let's begin to learn more about other iText functions. For more complex settings, we can analyze the Document construction method. In addition to the non-parameter construction in the previous example, there are two other:/** Created on 2004-1-3, create the first Hello World Program */package test1; import java. io. fileNotFoundException; import java. io. fileOutputStream; import com. lowagie. text. *; import com.lowagie.text=. *; public class HelloWorld {public static void main (String [] args) {// create a Document Object Document doc = new Document (); try {// define the output location and load the document object into the output object using writer. getInstance (Doc, new FileOutputStream ("c:/helloworkflow"); // open the doc object. open (); // Add the text "Hello World" doc. add (new Paragraph ("HelloWorld"); // close the Document Object and release the resource doc. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (incluentexception e) {e. printStackTrace () ;}} public Document (); public Document (Rectangle pageSize, int marginLeft, int marginRight, int ma RginTop, int marginBottom); the first is to set the page size of the document, and the second is to set the page size of the document and the page margin. The following are examples. Rectangle pSize = new Rectangle (144,90); // The document background color pSize. setBackgroundColor (Color. blue); // create a Document Object and set its initialization size. Document doc = new Document (pSize); Rectangle pSize = new Rectangle (144,90 ); // document background color pSize. setBackgroundColor (Color. blue); // create a Document Object and set the initialization size and margin Document doc = new Document (pSize, 5, 5, 5 ); modify the code in the first example and run it. You can see that the output PDF document looks like this. The document becomes very small and the background is blue: in the above example, we set the document size through Rectangle. In fact, iText has already defined many common Pages, such as: A0-A10, LEGAL, LETTER and so on, these are put in the com. lowagie. text. PageSize class, you can directly reference the page information by calling the static method in PageSize. For example: PageSize. A4; you can use iText to set the font of text, which is the most important question for Chinese programmers in China. Fortunately, there is a specialized package in iText to set the fonts for Asian countries. You can download this package from http://itext.sourceforge.net/downloads/itextasian.jar. Then you can put it directly in your ClassPath. How to set the font? BaseFont bfChinese = BaseFont. createFont ("STSong-Light", "UniGB-UCS2-H", BaseFont. NOT_EMBEDDED); Font FontChinese = new Font (bfChinese, 12, Font. NORMAL); in the above Code, set the display of the Chinese font. You only need to use the following code to include Chinese characters into the PDF String title = "I love coffee "; paragraph t = new Paragraph (title, FontChinese); doc. add (t); if you think this setting is very troublesome, You have to expand its source code by yourself, and set all the fonts in the BaseFont. Editing a Table in iText is similar to using a Table in HTML, but it has a cell representing a grid. Basically, the Table here is consistent with the Table object in Swing, for example, in the above Code, set the Table: // define a table Table table = new Table (2); // set the table border Table. setBorderWidth (1); Cell cell Cell = new cell ("Matrix III"); Cell. setHeader (true); // sorts cells. setColspan (2); cell. setBackgroundColor (Color. blue); table. addCell (cell); now you must know how to add an Image to the document. Yes, you only need to declare an Image object, here the Image and the Image in AWT are used in the same way. // Define an Image jpeg = Image. getInstance ("C:/matrix.jpg"); // center jpeg image. setAlignment (Image. ALIGN_CENTER); I will give a general introduction to the use of iText. For more information, see the source code. 2. generate excel in java: A simple applet. Find an old project to study it. Public class CreateSimpleExcelToDisk {/*** @ Author: heasen * @ Date: 2010-3-24 * @ function: create a simple format Excel */private static List <Student> getStudent () throws Exception {List list = new ArrayList (); SimpleDateFormat df = new SimpleDateFormat ("yyyy-mm-dd"); Student user1 = new Student (1, "James", 16, df. parse ("1997-03-12"); Student user2 = new Student (2, "Li Si", 17, df. parse ("1996-08-12"); Student user3 = new Student (3, "Wang Wu", 26, df. parse ("1985-11-12"); list. add (user1); list. add (user2); list. add (user3); return list;} public static void main (String [] args) throws Exception {// step 1, create a webbook, corresponding to an Excel file HSSFWorkbook wb = new HSSFWorkbook (); // Step 2: Add a sheet to the webbook, corresponding to the sheet HSSFSheet sheet = wb in the Excel file. createSheet ("Student table 1"); // Step 3: Add row 0th in the table header. Note that the earlier version of poi has a limit on the number of rows in the Excel worksheet. createRow (int) 0); // Step 4: Create a cell and set the value header to center the header with HSSFCellStyle = wb. createCellStyle (); style. setAlignment (HSSFCellStyle. ALIGN_CENTER); // create a center format HSSFCell cell = row. createCell (short) 0); cell. setCellValue ("student ID"); cell. setCellStyle (style); cell = row. createCell (short) 1); cell. setCellValue ("name"); cell. setCellStyle (style); cell = row. createCell (short) 2); cell. setCellValue ("Age"); cell. setCellStyle (style); cell = row. createCell (short) 3); cell. setCellValue ("Birthday"); cell. setCellStyle (style); // Step 5: Write the data into the object data. In the actual application, the data is obtained from the database. List list = CreateSimpleExcelToDisk. getStudent (); for (int I = 0; I <list. size (); I ++) {row = sheet. createRow (int) I + 1); Student stu = (Student) list. get (I); // Step 4: Create a cell and set the row value. createCell (short) 0 ). setCellValue (double) stu. getId (); row. createCell (short) 1 ). setCellValue (stu. getName (); row. createCell (short) 2 ). setCellValue (double) stu. getAge (); cell = row. createCell (short) 3); cell. setCellValue (new SimpleDateFormat ("yyyy-mm-dd "). format (stu. getBirth ();} // Step 6: Save the file to the specified location. try {FileOutputStream fout = new FileOutputStream ("E:/students.xls"); wb. write (fout); fout. close ();} catch (Exception e) {e. printStackTrace ();}}}

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.