The origin of the problem.
Not long ago, I did a small project to generate PDF reports through JSP, which was an eye-opener. Some of the company's information forms Html reports through the network. Although IE can directly print the content displayed in it, from the interface point of view, if the Html display results are directly printed out, it does not look very beautiful. If you convert it to a PDF file and then print it, the printing effect will be much better.
Introduction to iText
iText is an open source Java class library that can be used to easily generate PDF files. You can 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 completed, you will get a .jar package. Add this package to the JDK classpath to use it. If Chinese, Japanese, and Korean characters need to appear in the generated PDF file, you also need to download the iTextAsian.jar package by visiting http://itext.sourceforge.net/downloads/iTextAsian.jar .
Regarding the use of the iText class library, http://www.lowagie.com/iText/tutorial/index.html has a more detailed tutorial. This tutorial starts from the beginning and systematically introduces the methods and techniques of placing text, pictures, tables, etc. in PDF files. After reading this tutorial, you will be able to create some simple to complex PDF files. However, trying to solve all the difficulties encountered in the process of generating PDF files through tutorials is undoubtedly a luxury. Therefore, it is very important to read the iText API documentation. When readers download the class library, they can also download the documentation of the class library.
How to use iText to generate PDF reports 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. Readers only need to add the content they want to put in the PDF file between the two statements document.open(); and document.close();. This example only adds a line of text "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 example, The framework of the program is very clear and straightforward. However, specifying the location of text, pictures, and tables in PDF is a very troublesome task. Apart from the process of constantly modifying the position in the program, then running the program, generating the PDF file, and observing whether the position of the elements in the PDF is reasonable, there seems to be no other better method.
How to generate PDF reports through JSP
is not available in iText tutorials, and there is relatively little relevant information on the Internet. I once saw someone posting on CSDN asking for implementation details, and someone replied about the implementation principle: first generate a PDF file on the server, and then the user chooses to download or open it by clicking on the hyperlink pointing to the PDF file. This is an idea, or one of the ideas. This article realizes this idea and gives another idea and implements it in two ways.
1) Generate PDF files 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 obtained by each run should be unique and not duplicated. This program uses a random function to name the generated PDF files. The disadvantage of this program is that each time it is run, a PDF file will be generated on the server. If it is not deleted in time, the number will become larger and larger. This is obviously something the site maintainer does not want to see.
2) Transfer the PDF file to the client's cache in the form of a stream. The advantage of this is that it won't leave any "relics" on the server.
i) Generate directly through JSP page
<%@
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) Generated through 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 ();
}
ended up
using the second approach in my project. The source code of this article has been debugged on my tomcat4. Hope it can bring convenience to everyone.
Everyone is welcome to use it. If you need to reprint it, please indicate the source.