How to generate word document, excel document and PDF document by JSP

Time:2020-4-30

In this paper, JSP is used to generate word document, excel document and PDF document. To share with you for your reference, as follows:

In the Web OA system, the official document management seems to be indispensable. Sometimes it needs to query some data from the database and output it in a certain format, and display it in the form of word documents. Sometimes many word documents are saved in the BLOB field of a table in the database, and the server displays the picture files saved in the BLOB field to the user. Through the Internet search found that there are very few articles about this kind, now put them together for your reference.

1. Generate word documents directly on the client side

It is very simple to generate word documents on JSP pages. Just 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 setting, the content of the original page can be displayed in word.

If you need to download the word document, just add the following code on the JSP page:


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

Where filename in filename.doc is the file name of the word document to download, which can be customized from the line through <% = docname% >


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

This provides a prompt for the user to select.

Tips: if the programmer needs to follow the format he designed on word in advance when generating word documents, he can copy the word format and paste it into frontpage, then paste the HTML code into JSP page.

2 output the word entity in the database in the client

Only the word document entity in the BLOB field of Oracle output by client is discussed here. The class getBlobBean is called, which provides the blob function 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 {
//It is important to set the output content type. Otherwise, the client browser will not recognize the output content, resulting in a download dialog box.
 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(HttpServletRequest request, HttpServletResponse response){
try{
//This kind of function is to extract blob entity from Oracle cry
   getBlobBean getBlob=new getBlobBean();
   OutputStream sos = response.getOutputStream();
   getBlob.connFunction();
oracle.sql.BLOB blob=getBlob.getBlob("cehui");
//Output 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 EXCEL documents directly on the client side

<%@ page contentType="application/vnd.ms-excel; charset=gb2312" %>
<%
response.setHeader("Content-Disposition", "attachment;filename=20050304.xls");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
< title > generate < / Title >
</head>
<body>
Generate example excel. Use word layout, pour out HTML, copy the code to the web page, and then you can control the printing of this JSP page as you like. 
</body>
</html>

4. Generating PDF documents directly on the client side

Need to download jar package: the following code passed the test under JDK 1.4 rein2.16

IText package http://mesh.dl.sourceforge.net/sourceforge/itext/itext-1.3.5.jar
Font package http://itext.sourceforge.net/downloads/itextasian.jar

JSP is generated to client IE and opened directly

ie_PDF.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] ); } 
%> 

Build on the server side without downloading.

server_PDF.jsp:

<%@ page import ="com.lowagie.text.*,com.lowagie.text.pdf.*, java.io.*"%> 
<% 
String filename = "D://test//111111.pdf" ; 
Document document = new Document(PageSize.A4); 
ServletOutputStream out1 = response.getOutputStream(); 
try{ 
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename) ); 
document.open(); 
Document.add (new paragraph ("Hello World Chinese support"); 
document.close(); 
} 
catch(Exception e){} 
%>

Using iText to set the font of text is the most important problem for our Chinese programmers. Fortunately, there is a special package in iText for setting fonts in Asian countries. You can download this package from http://itext.sourceforge.net/downloads/itextasian.jar. Then 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 display of Chinese font is set in the above code. You can add Chinese to PDF as long as you use the following code

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

I hope this article is helpful for JSP programming.