Using Itext to generate PDF reports in JSP _jsp programming

Source: Internet
Author: User
Tags getmessage

The origin of the problem

Not long ago done a JSP to generate a PDF report of the small project, it is an open vision. Some of the enterprise information through the network to form an HTML report, although IE can directly print the contents of the display, but from the interface, if the direct HTML display results printed out, it is not very beautiful. If you turn 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. You download the latest version of the class library by visiting http://sourceforge.net/project/showfiles.php?group_id=15255&release_id=167948, After the download is complete, you will get a. jar package, which can be used by adding this package to the JDK classpath. If you need to see Chinese, Japanese, and Korean characters in the generated PDF file, you also need to download the Itextasian.jar package by accessing Http://itext.sourceforge.net/downloads/iTextAsian.jar.

Http://www.lowagie.com/iText/tutorial/index.html has a more detailed tutorial on the use of the IText class library. This tutorial begins with a more systematic introduction to the methods and techniques of putting text, pictures, forms, and so on in a PDF file. After reading this tutorial, you can basically do some simple to complex PDF files. However, trying to solve all the difficulties in the process of generating PDF files through tutorials is an extravagant hope. Therefore, it is important to read the Itext API documentation. While downloading the class library, the reader can also download the document for the class library.

How to use Itext to generate PDF reports in Java programs

The following is one of the simplest examples of the above tutorial, which depicts the general procedural framework for generating PDF files through Itext. Readers only need to add the content they want to put in the PDF file in the middle of Document.open () and Document.close () two statements. This example only adds the word "Hello World" to the PDF file.


Document document = new document ();

Try

{

Pdfwriter.getinstance (document, New FileOutputStream ("Chap0101.pdf"));

Document.open ();

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

}

catch (Documentexception de)

{

System.err.println (De.getmessage ());

}

catch (IOException IoE)

{

System.err.println (Ioe.getmessage ());

}

Document.close ();

As can be seen from the above examples, the framework of the procedure is very clear. However, it is very troublesome to specify the position of text, drawing, and table in the PDF. There seems to be no better way to do this than to constantly modify the location in the program, then run the program, generate a PDF file, and see if the elements are reasonable in the PDF.

How to generate a PDF report from a JSP

This part is not in the Itext tutorial, the relevant information on the Internet is also relatively few. I have seen on the csdn of people asking for implementation details, someone back to the implementation of the principle: first on the server to generate a PDF file, and then the user clicks to the PDF file to select a hyperlink to download or open. It's a thought, or one of the ideas. This paper realizes this idea, and gives another idea and realizes it through two ways.

1 The PDF file is generated directly on the server.

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

<%

String filename = "PDF" + (new Random ()). Nextint () + ". 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"));

Document.close ();

}

catch (Exception e) {}%>

The above program generates a static PDF file on the server. Obviously, the name of the PDF file to run each time should be unique and not heavy. This program uses random functions to name the generated PDF file. The disadvantage of this procedure is that each run will produce a PDF file on the server, if not deleted in time, the number will become larger and bigger, this is obviously the site defenders do not want to see.

2 Transfer the PDF file to the client's cache via streaming form. The advantage of this is that there will be no "relics" left on the server.

i) directly through the JSP page generation

<%@

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]);

}

%>

II Generation via Servlet

Import java.io.*;

Import javax.servlet.*;

Import javax.servlet.http.*;

Import com.lowagie.text.*;

Import com.lowagie.text.pdf.*;

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

{

PDFWriter writer = pdfwriter.getinstance (document, BA);

Document.open ();

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

}

catch (Documentexception 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. This article's source code in my tomcat4 above all is debugging passes. Hope can bring convenience to everyone.

Welcome to use, if you need to reprint, 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.