Use iText to generate a PDF report in JSP

Source: Internet
Author: User

Origin

Not long ago, I made a small project to generate PDF reports through JSP, opening my eyes. Some enterprise information forms Html reports through the network. Although IE can directly print the content displayed in the reports, from the perspective of the interface, if the Html display result is printed directly, not very nice. If you convert it into a PDF file and then print it, the printing effect will be much better.

IText Introduction

IText is an open-source Java class library that can be used to easily generate PDF files. By accessing http://sourceforge.net/project/showfiles.php? Group_id = 15255 & release_id = 167948 download the latest version of the class library. After the download is complete, you will get a. jar package. Add this package to the JDK classpath for use. If the generated PDF file contains Chinese, Japanese, and Korean characters, access http://itext.sourceforge.net/downloads/itextasian.jarto download the itextasian.jarpackage.

For more information about the use of the iText class library, visit http://www.lowagie.com/itext/tutorial/index.html. This tutorial describes how to add text, images, and tables to a PDF file. After reading this tutorial, you can make some PDF files from simple to complex. However, it is a luxury to try to solve all the difficulties encountered in the process of generating PDF files through the tutorial. Therefore, it is very important to read the api documentation of iText. When downloading the class library, you can also download the documentation of the class library.

How to Use iText to generate a PDF report in a java program

The following is the simplest example in the above tutorial. This example depicts the general program framework for generating PDF files through iText. You only need to add the content you want to put in the PDF file between document. open (); and document. close. In this example, only a line of "Hello World" is added to the PDF file.


Document document = new Document ();

Try

{

Using writer. getInstance (document, new FileOutputStream ("Chap0101.pdf "));

Document. open ();

Document. add (new Paragraph ("Hello World "));

}

Catch (incluentexception de)

{

System. err. println (de. getMessage ());

}

Catch (IOException ioe)

{

System. err. println (ioe. getMessage ());

}

Document. close ();

The above example shows that the program framework is very clear. However, it is very troublesome to specify the positions of text, pictures, and tables in PDF. In addition to constantly changing the position in the program, then running the program, generating a PDF file, and observing whether the position of the element in the PDF is reasonable, there seems to be no better way.

How to generate a PDF report using JSP

This part is not found in the iText tutorial, and there is little relevant information on the Internet. I once saw someone posting on CSDN asking for implementation details, and someone replied to the implementation principle: first generate a PDF file on the server, and then the user chooses to download or open it by clicking the hyperlink pointing to the PDF file. This is an idea, or an idea. This article implements this idea and provides another idea and implements it in two ways.

1) generate a PDF file directly on the server.

<% @ Page import = "com. lowagie. text. *, com.lowagie.text=. *, java. io. *" %>

<%

String filename = "PDF" + (new Random (). nextInt () + ". pdf ";

Document document = new Document (PageSize. A4 );

ServletOutputStream out1 = response. getOutputStream ();

Try

{

Using writer = Using writer. getInstance (document, new FileOutputStream (filename ));

Document. open ();

Document. add (new Paragraph ("Hello World "));

Document. close ();

}

Catch (Exception e) {}%>

 

The above program generates a static PDF file on the server. Obviously, the names of the PDF files obtained from each operation should be unique and cannot be duplicated. This program uses a random function to name the generated PDF file. The disadvantage of this program is that every operation will generate a PDF file on the server. If it is not deleted in time, the number will increase, which is obviously not desired by the site maintainer.

 

2) Transfer the PDF file to the client cache in the form of a stream. The advantage of doing so is that it will not leave any "relics" on the server ".

 

(I) generate the file directly through the JSP page.

 

 

<% @

Page import = "java. io. *, java. awt. Color, com. lowagie. text. *, com.lowagie.text}. *" %>

<%

Response. setContentType ("application/pdf ");

Document document = new Document ();

ByteArrayOutputStream buffer = new ByteArrayOutputStream ();

Response writer = Response writer. 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]);

}

%>

 

Ii) generate through Servlet

 

 

Import java. io .*;

Import javax. servlet .*;

Import javax. servlet. http .*;

Import com. lowagie. text .*;

Import com.lowagie.text= .*;

Public void doGet (HttpServletRequest request, HttpServletResponse response)

Throws IOException, ServletException

{

Document document = new Document (PageSize. A4, 36,36, 36,36 );

ByteArrayOutputStream ba = new ByteArrayOutputStream ();

Try

{

Author writer = author writer. getInstance (document, ba );

Document. open ();

Document. add (new Paragraph ("Hello World "));

}

Catch (incluentexception de)

{

De. printStackTrace ();

System. err. println ("A Document error:" + de. getMessage ());

}

Document. close ();

Response. setContentType ("application/pdf ");

Response. setContentLength (ba. size ());

ServletOutputStream out = response. getOutputStream ();

Ba. writeTo (out );

Out. flush ();

}


End

I used the second method in the project. The source code of this article is successfully debugged on Tomcat 4. I hope this will bring convenience to you.

You are welcome to use it. If you need to reprint it, please indicate the source.

 

 

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.