Servlet output PDF document Method

Source: Internet
Author: User

Java Servlet programming can easily send HTML files to the client's Web browser. However, many sites also allow access to documents in non-HTML format, including Adobe PDF, Microsoft Word, and micorsoft excel. In fact, as long as these non-HTML formats can be expressed as MIME types, servlet can be used for sending. This document uses PDF as an example to describe how to use servlet to transfer a non-HTML file and how the file is generated on the server using Java.

You only need to write the file to the servlet output stream, you can use the servlet to open a file in the browser. First, start from obtaining the servlet output stream:

Servletoutputstream out = res. getoutputstream ();

Mime (multipurpos Internet Mail Extension multi-destination Internet Mail Extension Protocol) is used on the Internet to transmit mixed formats, multimedia and binary data files. To open a document in the servlet response object, you must set the MIME type of the document.

Send PDF documents to the Web Client
(1) MIME type
The Web browser uses the MIME type to identify non-HTML documents and determines how to display the data in the documents. When the plug-in (plug-in) is used in combination with the MIME type, the corresponding plug-in can be started to process the document when the web browser downloads the MIME type indication document. Some MIME types can also be used together with external programs. After a file is downloaded by a browser, the corresponding external program is started.

MIME type is very useful. They allow Web browsers to process documents in different formats, but do not need to embed relevant knowledge in advance. Java Servlets can use the MIME type to send non-HTML files to a browser, such as Adobe PDF and micorsoft word. The correct MIME type ensures that these non-HTML files are displayed by the correct plug-in or external programs.

The MIME type of a PDF file is "application/pdf ". To open a PDF document using Servlet, you need to set the content type of the header in the response object to "application/pdf ":

// MIME type of the PDF file
Res. setcontenttype ("application/pdf ");
// You can also set it in the following way:

Response. setheader ("Content-Type", "application/pdf ");
(2) Content Disposition
Content-disposition in the HTTP Response Header allows the servlet to specify the information represented in the document. With this header, you can specify the document to be opened separately (instead of in the browser) and display it according to user operations. If you want to save a document, you can also recommend a file name for this document. The recommended name will appear in the "file name" column of the Save As dialog box. If not specified, the servlet name will appear in the dialog box. In servlet, you need to set the header as follows:

Res. setheader ("content-disposition ",
"Attachment; filename =" +
"Example.pdf ");
// Attachment-because you do not want to open it directly in the browser, instead, Use Adobe Acrobat.
// You can set the default file name to determine the suggested name for saving the text.
// Response. setheader ("content-disposition", "inline; filename=report ");
(3) encapsulate non-HTML documents
After completing the above work, the rest is very simple. You need to create a java.net. url object based on the name of the file to be transferred. The string sent to the URL constructor must be a valid URL address pointing to the file. Here, I want to open the local PDF file:

String fileurl = "http: // localhost/aboutadobe/careeropp/pdfs/tables.pdf;

The URL string can also be similar to a http://www.gr.com/pub/somefile.doc or http://www.gr.com/pub/somefile.xls. However, make sure that the type of the file to be transferred is consistent with the MIME type set in the HTTP Response object.

(4) Others
Before reading the transmitted documents, you must first obtain the input stream inputstream from the URL object and encapsulate inputstream with bufferedinputstream.

Bufferedinputstreambis = newbufferedinputstream (URL. openstream ());

Once you complete the preceding operations, you just need to write the bytes in inputstream to the servlet output stream outputstream:

Bufferedoutputstreambos = new bufferedoutputstream (out );

Byte [] buff = new byte [2048];
Intbytesread;

// A simple read/write Loop
While (-1! = (Bytesread = bis. Read (buff, 0, Buff. Length ))){
Bos. Write (buff, 0, bytesread );
}


In the final code block, close these streams, such as Bos. Close ();

PDF file generation on the server
Using the itext040 toolkit, you can easily output a very beautiful PDF file.

1. Create document
Document document = new document (P0, P1, P2, P3, P4)

Where P0 is the page size, such as pagesize. A4; P1? P4 respectively describes the left and right sides of the page.

2. Constructor
Using writer. getinstance (document, new fileoutputstream ("tables.pdf "))

After the program is executed, a file named tables.pdf will be generated under the current directory.

Then open document: Document. open ()

3. Define a table as needed
// A table with ten columns
Table datatable = new table (10 );
// Defines the distance between cells to zero
Datatable. setcellpadding (0 );
// Define the cell Interval
Datatable. setcellspacing (3 );
// Make the table have no border
Datatable. setborder (rectangle. no_border );
// Define the width of each column
Intheaderwidths [] = {10, 30, 15, 15, 5, 5, 5, 5 };
Datatable. setwidths (headerwidths );
Datatable. setwidth (100 );

4. Font definition:
Basefont BF = basefont. createfont (string name, string encoding, Boolean embedded)

"Name" is the font name and "encoding" is the encoding name.

5. Cell Definition
Cell cell = new cell (new phrase ("string", f ));

String is the content to be displayed in cell. There are also many methods to control the cell. The following are commonly used methods:

Cell. setborder (INT value)

Based on experience, the border shape corresponding to the value can be found in:

Legend value integer
Rectangle. align_bottom 6
Rectangle. align_baseline 7
Rectangle. align_center 1
Rectangle. align_justified 3
Rectangle. align_middle 5
Rectangle. align_right 2
Rectangle. align_top 4

Cell. setcolspan (INT value) and cell. setrowspan (INT value) define the columns and rows occupied by cells.

It is worth noting that the total number of cells in a row must strictly match the number of columns defined during table construction.

Cell. sethorizontalalignment (INT value) and cell. setverticalalignment (INT value) determine the position of the cell in the horizontal and vertical directions respectively.

Finally, add the cell to the table: Table. addcell (cell)

6. Add Table to document and close document:

Document. Add (table );
Document. Close ();

Summary
As you have read, you can use itext040 to compile a JavaBean that can output PDF documents. Then, output it to the client through sevlet, which is quite simple. You can set the correct MIME type as long as you use the appropriate method.

Servlet output PDF document Method

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.