使用Servlet将数据写入PDF

本文将演示如何使用Servlet技术将数据写入PDF。我们使用的PDF导出技术是iText,首先我们要下载iText的包导入项目,才能编写Java代码把数据写入到PDF。

1 下载iText包

iText是一种生成PDF报表的Java组件。通过在服务器端使用Jsp或JavaBean生成PDF报表,先下载iText包并导入项目:

下载iText相关包

2 编写index.jsp

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>一点教程网-使用Servlet将数据写入PDF</title>
</head>
<body>
<h1>使用Servlet将数据写入PDF</h1>
<a href="ExportToPdf">导出PDF</a>
</body>
</html>

3 编写PdfServlet

PdfServlet将使用iText技术写出数据到PDF,并下载到本地:

import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Iterator;
import java.util.List;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class PdfServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //设置响应类
            response.setContentType("application/pdf");
            //设置响应头,用于浏览器弹出下载提示框
            response.setHeader("Content-disposition", "attachment;filename=yiidian.pdf");

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

            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            //设置中文字体,解决中文无法显示的问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            Font titleFont = new Font(bfChinese, 10, Font.NORMAL, Color.RED);

            document.add(new Paragraph("欢迎访问一点教程网学习IT教程", titleFont));
            document.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

4 配置web.xml

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>PdfServlet</servlet-name>
        <servlet-class>PdfServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PdfServlet</servlet-name>
        <url-pattern>/ExportToPdf</url-pattern>
    </servlet-mapping>

</web-app>

5 运行测试

打开PDF文档,内容如下:

热门文章

优秀文章