JSP generation of Word documents, EXCEL documents and PDF documents, excelpdf

Source: Internet
Author: User

JSP generation of Word documents, EXCEL documents and PDF documents, excelpdf

This document describes how to generate WORD Documents, EXCEL documents, and PDF documents in JSP. We will share this with you for your reference. The details are as follows:

In the web-OA system, document management seems indispensable. Sometimes some data needs to be queried from the database and output in a certain format and displayed as Word documents, sometimes Many Word documents are saved to the Blob field of a table in the database, and the server then presents the image file stored in the Blob field to the user. I found that there are very few such articles through searching on the Internet. I will sort them out for your reference.

1. Generate Word documents directly on the client

It is very easy to generate a Word document on the jsp page. You just need to change contentType = "text/html" to contentType = "application/msword; charset = gb2312". The Code is as follows:
Copy codeThe Code is as follows: <% @ page contentType = "application/msword; charset = gb2312" %>
Through settings, the content of the original page can be displayed in word.

To download a Word document, add the following code on the jsp page:

<%response.setHeader("Content-Disposition", "attachment;filename=filename.doc");%>

In filename.doc, filename is the name of the Word Document to be downloaded. It can be customized by <% = docName %> from the line, as shown below:

<%response.setHeader("Content-Disposition", "attachment;filename=<%=docName%>.doc");%>

In this way, a prompt is provided for the user to choose.

TIPS: If a programmer needs to follow the format designed on the word before generating a word document, he can copy the word format and paste it to the frontpage. Then, paste the html code to the jsp page.

2. output the word entity in the database on the client

Here we will only discuss how to output the Word document entity in the BLOB field of oracle by the client. The getBlobBean class is called, which provides the function of retrieving blob from oracle. The Code is as follows:

Package yourpackage; import javax. servlet. *; import javax. servlet. http. *; import java. io. *; import java. util. *; import oracle. SQL. *; import beans. yourbeanpackage. getBlobBean;/***** <p> Title: </p> * <p> Description: </p> * <p> Copyright: Copyright (c) 2004 </p> * <p> Company: </p> * @ author not attributable * @ version 1.0 */public class GetBlobServlet1 extends HttpServlet {// set the output content type, this setting is very important. Otherwise, the client browser cannot identify the output content, The download dialog box is displayed. Private static final String CONTENT_TYPE = "application/msword; charset = gb2312"; // Initialize global variables public void init () throws ServletException {} // Process the HTTP Get request public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType (CONTENT_TYPE); perform (request, response);} public void perform (HttpServl EtRequest request, HttpServletResponse response) {try {// This function is used to retrieve the blob entity getBlobBean getBlob = new getBlobBean () from oracle crying; OutputStream sos = response. getOutputStream (); getBlob. connFunction (); oracle. SQL. BLOB blob = getBlob. getBlob ("cehui"); // output the Word document if (blob! = Null) {InputStream pi = blob. getBinaryStream (); int blobsize = (int) blob. length (); byte [] blobbytes = new byte [blobsize]; int bytesRead = 0; while (bytesRead = pi. read (blobbytes ))! =-1) {sos. write (blobbytes, 0, bytesRead);} pi. close (); sos. flush (); sos. close ();} getBlob. dropConnFunction ();} catch (Exception e) {System. out. println (e. toString () ;}}// Clean up resources public void destroy (){}}

3. generate an EXCEL document directly on the client

<% @ Page contentType = "application/vnd. ms-excel; charset = gb2312 "%> <% response. setHeader ("Content-Disposition", "attachment?filename=20050304.xls"); %> 

4. Generate a PDF file directly on the client

Download the JAR package: the following code passes the test in JDK1.4 RESIN2.16

ITEXT pack http://mesh.dl.sourceforge.net/sourceforge/itext/itext-1.3.5.jar
Character bag http://itext.sourceforge.net/downloads/iTextAsian.jar

JSP is generated on the client IE side and opened directly

Ie_mirror.jsp:

<%@ page import="java.io.*,java.awt.Color,com.lowagie.text.*,com.lowagie.text.pdf.*"%> <% response.setContentType( "application/pdf" ); Document document = new Document(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PdfWriter writer=PdfWriter.getInstance( document, buffer ); document.open(); document.add(new Paragraph("Hello World")); document.close(); DataOutput output = new DataOutputStream( response.getOutputStream() ); byte[] bytes = buffer.toByteArray(); response.setContentLength(bytes.length); for( int i = 0; i < bytes.length; i++ ) { output.writeByte( bytes[i] ); } %> 

Generate a file on the server without downloading it.

Server_cmd.jsp:

<% @ Page import = "com. lowagie. text. *, com.lowagie.text=. *, java. io. * "%> <% String filename =" D: // test // 111111.20."; Document document = new Document (PageSize. a4); ServletOutputStream out1 = response. getOutputStream (); try {writable writer = writable writer. getInstance (document, new FileOutputStream (filename); document. open (); document. add (new Paragraph ("Hello World Chinese"); document. close () ;}catch (Exception e) {}%>

You can use iText to set the font of text, which is the most important question for Chinese programmers. 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);

The above Code sets the display of Chinese fonts. You only need to use the following code to include Chinese characters in the PDF.

String title = "I love coffee"; Paragraph t = new Paragraph (title, FontChinese); doc. add (t );

I hope this article will help you with JSP program design.

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.