Java 使用itext生成pdf以及下载

使用方法:

1.需要两个jar包:

iText-5.0.6.jar    //必须使用该版本,否则缺少相关的方法

TextAsian.jar

//是为了文档中正常显示中文所必须引用的包

TextAsian.jar使用时并不是单纯的引入就可以了,还需要进一步处理该jar包,否则无法显示

(无奈当时没有保存那个解决方法的链接,所以以后要用正确的包的话,就去毕设项目下找该包)

2以下是一个完整的例子。

一、要生成pdf的jsp页面

<%@ page language="java" import="java.util.*,utils.*,entity.*,dao.*" pageEncoding="utf-8"%>
<%@ include file="top.jsp" %>
<% /*------------------------------操作记录-----------------------------------*/
    DoOperation dp=new DoOperation();
    Operation op=new Operation();
    User user=(User) session.getAttribute("UserBean");
    String IP=(String) session.getAttribute("IP");
    op=dp.getOperation(IP, user.getId()+"", "舆情报告", "成功");
    OperationCl oc=new OperationCl();
    oc.addOperation(op);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta charset="gbk">
<title>舆情报告</title>
<meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="author" content="puyuetian qq632827168">
<meta name="renderer" content="webkit">
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="stylesheet" href="./css/invatation/upload.css" />
<link rel="stylesheet" href="./css/invatation/default.css" />
<script charset="utf-8" src="./js/invatation/kindeditor-min.js"></script>
<script charset="utf-8" src="./js/invatation/zh_CN.js"></script>
<script charset="utf-8" src="./js/invatation/puyuetian.js"></script>
<script language="javascript" type="text/javascript"
    src="./js/My97DatePicker/WdatePicker.js"></script>
<link rel="stylesheet" href="./css/invatation/amazeui.min.css">
<link rel="stylesheet" href="./css/invatation/app.css">
<!--[if (gte IE 9)|!(IE)]><!-->
<script src="./js/invatation/jquery.min.js"></script>
<!--<![endif]-->

<script src="./js/invatation/amazeui.min.js"></script>
</head>
<body>
    <style>
.hook-mail-forgotpassword-a {
    font-size: 12px;
    display: block;
    text-align: right;
}
</style>
<br>

    <div class="am-container">
        <div class="am-container">
            <div style="background-color: white;padding: 1.6rem;">

                <style>
.am-breadcrumb li {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 360px;
}
</style>

                <link rel="stylesheet" href="./css/invatation/edit.css">

                <script>
                    var editor;
                    KindEditor.ready(function(K) {
                        editor = K.create(‘textarea[name=content]‘, {
                            width : ‘100%‘,
                            height : ‘360px‘,
                            resizeType : 1,
                            allowPreviewEmoticons : false,
                            allowImageUpload : false,
                            items : [ ‘source‘, ‘|‘, ‘fontname‘, ‘fontsize‘,
                                    ‘|‘, ‘forecolor‘, ‘hilitecolor‘, ‘bold‘,
                                    ‘italic‘, ‘underline‘, ‘removeformat‘, ‘|‘,
                                    ‘justifyleft‘, ‘justifycenter‘,
                                    ‘justifyright‘, ‘insertorderedlist‘,
                                    ‘insertunorderedlist‘, ‘|‘, ‘emoticons‘,
                                    ‘table‘, ‘code‘, ‘image‘, ‘link‘,
                                    ‘quickformat‘ ]
                        });
                    });
                </script>
                <a name="post"></a>
                <div class="am-container" style="background:white">
                    <form name="form_post" class="am-form am-form-horizontal"
                         method="post" action="reportServlet">
                        <div class="text"  style=" text-align:center;font-size:26px;">舆情报告</div>
                        <br>
                        <div class="am-form-group ">
                            <input type="text" style="width:560px;" name="title"
                                placeholder="舆情事件" value="" onfocus="readsortdiv(‘visible‘)"
                                autocomplete="off">
                            <div id="readsortdiv" class="readsortdiv"></div>
                        </div>

                        <div class="am-form-group ">
                            <input name="time" class="Wdate" type="text" placeholder="发生时间"
                                onClick="WdatePicker()" style="width:220px;">
                        </div>

                        <div class="am-form-group">
                            <select name="area" style="margin: 10px 0px;width:360px;">
                                <option value="0">发生地区</option>
                                <option value=‘和平区‘>和平区</option>
                                <option value=‘南开区‘>南开区</option>
                                <option value=‘河东区‘>河东区</option>
                                <option value=‘河西区‘>河西区</option>
                                <option value=‘河北区‘>河北区</option>
                                <option value=‘红桥区‘>红桥区</option>
                                <option value=‘西青区‘>西青区</option>
                                <option value=‘塘沽区‘>塘沽区</option>
                                <option value=‘汉沽区‘>汉沽区</option>
                                <option value=‘东丽区‘>东丽区</option>
                                <option value=‘大港区‘>大港区</option>
                                <option value=‘津南区‘>津南区</option>
                                <option value=‘北辰区‘>北辰区</option>
                                <option value=‘武清区‘>武清区</option>
                                <option value=‘宝坻区‘>宝坻区</option>
                                <option value=‘宁河县‘>宁河县</option>
                                <option value=‘静海县‘>静海县</option>
                                <option value=‘蓟县‘>蓟县</option>
                            </select>
                        </div>

                        <div class="am-form-group">
                            <textarea name="summary" placeholder="舆情概述"></textarea>
                        </div>
                        <div class="am-form-group">
                            <textarea name="data" placeholder="相关数据"></textarea>
                        </div>
                        <div class="am-form-group">
                            <textarea name="result" placeholder="结论"></textarea>
                        </div>
                        <div class="am-form-group">
                            <textarea name="advise" placeholder="部门意见"></textarea>
                        </div>
                        <div class="am-form-group">
                            <input type="submit" class="am-btn am-btn-primary" value="生成PDF" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <link rel="stylesheet" href="./css/invatation/hdrive.css">
        <script defer="defer">
            var $USER = Array();
            $USER[‘ID‘] = "2";
            $USER[‘USERNAME‘] = "游客";
            $USER[‘NICKNAME‘] = "匿名游客";
            $USER[‘QUANXIAN‘] = "bbcode,download,lookread,lookuser,reply,search";
            $USER[‘TIANDOU‘] = "0";
            $USER[‘JIFEN‘] = "0";
            $USER[‘QIANDAODAYS‘] = "79";
            $USER[‘QIANDAOTIME‘] = "1452392237";
            $USER[‘SEX‘] = "机器人";
            $USER[‘BIRTHDAY‘] = "0";
            $USER[‘MAIL‘] = "[email protected]";
            $USER[‘QQ‘] = "632827168";
            $USER[‘PHONE‘] = "保密";
            $USER[‘SIGN‘] = "系统用户组 - 游客";
            $USER[‘FRIENDS‘] = "_1_";
            $USER[‘READLEVEL‘] = "0";
            var $GET = Array();
            $GET[‘C‘] = "edit";
            $GET[‘TYPE‘] = "read";
            $GET[‘SORTID‘] = "0";
            var $SET = Array();
            $SET[‘QIANDAOJIFEN‘] = "10";
            $SET[‘QIANDAOTIANDOU‘] = "10";
            var $QIANDAOED = ‘FALSE‘;

            function windowonscroll() { //页面滚动事件
                //navmove();
            }

            function loadinghere() { //页面加载至此事件
                $newmessagenum = ‘492‘;
                if ($newmessagenum != ‘‘) {
                    $newmessagenum = parseInt($newmessagenum);
                    $title = "您有新条新消息。";
                    document.getElementById("mf_m_new").style.visibility = ‘visible‘;
                    document.getElementById("mf_m").title = $title;
                }
                if ($USER[‘ID‘] != 2) {
                    showxunzhang();
                    showuserlevelprogressbar();
                }
                qiandao(0);
            }

            function loadcomplete() {
                //页面加载完成事件,异步数据驱动
                var s = document.createElement(‘script‘);
                s.src = ‘http:\/\/tongji.hadsky.com\/tongji.php?domain=‘
                        + document.domain + ‘&allurl=‘
                        + encodeURIComponent(document.location);
                //alert(encodeURI(document.location));
                document.getElementsByTagName(‘head‘)[0].appendChild(s);
            }
            try {
                loadinghere();
            } catch (e) {
                //TODO handle the exception
            }
            window.onscroll = windowonscroll;
            //创建全局驱动框架
            var cifrm = document.createElement(‘iframe‘);
            cifrm.name = ‘ifrm‘;
            cifrm.id = ‘ifrm‘;
            cifrm.style.display = ‘none‘;
            document.getElementsByTagName(‘body‘)[0].appendChild(cifrm);
            window.onload = loadcomplete;
        </script>

        <script src="./js/invatation/upload.js"></script>
        <link rel="stylesheet" href="./css/invatation/footer.css" />
        <div class="am-container">
            <div style="background-color: white;padding: 1.6rem;">
                <p class="am-text-center am-article-meta"
                    style="padding-top:4.8rem;padding-bottom:1.6rem;">
                    梦虽然遥不可及,但并不是不可能实现;只要坚持,就会离梦越来越近!</p>
            </div>
        </div>
</body>
</html>

二、处理请求的servlet

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.OperationCl;
import dao.ReportCl;
import entity.Operation;
import entity.Report;
import entity.User;
import utils.DoOperation;
import utils.DoPDF;

import java.text.SimpleDateFormat;
import java.util.Date;
public class reportServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("utf-8");
        /*------------------操作记录-------------------*/
        DoOperation dp=new DoOperation();
        Operation op=new Operation();
        HttpSession session = request.getSession();
        User user=(User) session.getAttribute("UserBean");
        String IP=(String) session.getAttribute("IP");
        op=dp.getOperation(IP, user.getId()+"", "舆情报告", "成功");
        OperationCl oc=new OperationCl();
        oc.addOperation(op);
        //前台接收数据
        String title=request.getParameter("title");
        String time=request.getParameter("time");
        String area=request.getParameter("area");
        String summary=request.getParameter("summary");
        String data=request.getParameter("data");
        String result=request.getParameter("result");
        String advise=request.getParameter("advise");
        //得到用户id
        int userID=user.getId();
        //文档路径和命名
        SimpleDateFormat df = new  SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String str=df.format(new Date());// new Date()为获取当前系统时间
        String filePath="F://MyEclipseWorkspace2014//MyData//WebRoot//WEB-INF//report//"+str+"report.pdf";
        String fileName=str+"report.pdf";//在文件名前加上时间,文件名不再重复
        //生成pdf文档
        DoPDF doPdf=new DoPDF();//生成pdf的类
        doPdf.getPDF(filePath, title, time, area, summary, data, result, advise);

    }

}

三、真正生成pdf文档的类DoPDF

package utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class DoPDF {
public void getPDF(String filePath,String title,String time,String area,
        String summary,String data,String result,String advise) throws IOException{
    Document document = new Document(PageSize.A4);
    try {
        try {

            PdfWriter.getInstance(document,
                    new FileOutputStream(filePath));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        document.open();
        BaseFont bfCN;
        Font fontCN ;

            bfCN = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", false);
            fontCN = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK);

        PdfPTable table = new PdfPTable(4);
        table.setTotalWidth(new float[]{66,84,66,84});

        // 设置字体大小
        PdfPCell cell = new PdfPCell(new Phrase("舆情报告",fontCN));
        cell.setColspan(4);
        cell.setBorderWidth(0);//设置表格的边框宽度为0
        cell.setMinimumHeight(30);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        PdfPCell cell1 = new PdfPCell(new Phrase("舆情事件",fontCN));
        cell1.setColspan(1);
        cell1.setBorderWidth(1);//设置表格的边框宽度为0
        cell1.setMinimumHeight(30);
        table.addCell(cell1);
        PdfPCell cell2 = new PdfPCell(new Phrase(title,fontCN));
        cell2.setColspan(3);
        cell2.setBorderWidth(1);//设置表格的边框宽度为0
        cell2.setMinimumHeight(30);
        table.addCell(cell2);

        PdfPCell cell3 = new PdfPCell(new Phrase("发生时间",fontCN));
        cell3.setColspan(1);
        cell3.setBorderWidth(1);//设置表格的边框宽度为0
        cell3.setMinimumHeight(30);
        table.addCell(cell3);
        PdfPCell cell4 = new PdfPCell(new Phrase(time,fontCN));
        cell4.setColspan(1);
        cell4.setBorderWidth(1);//设置表格的边框宽度为0
        cell4.setMinimumHeight(30);
        table.addCell(cell4);
        PdfPCell cell5 = new PdfPCell(new Phrase("发生地区",fontCN));
        cell5.setColspan(1);
        cell5.setBorderWidth(1);//设置表格的边框宽度为0
        cell5.setMinimumHeight(30);
        table.addCell(cell5);
        PdfPCell cell6 = new PdfPCell(new Phrase(area,fontCN));
        cell6.setColspan(1);
        cell6.setBorderWidth(1);//设置表格的边框宽度为0
        cell6.setMinimumHeight(30);
        table.addCell(cell6);

        PdfPCell cell7 = new PdfPCell(new Phrase("舆情概述",fontCN));
        cell7.setColspan(4);
        cell7.setBorderWidth(1);//设置表格的边框宽度为0
        cell7.setMinimumHeight(30);
        table.addCell(cell7);

        PdfPCell cell8 = new PdfPCell(new Phrase(summary,fontCN));
        cell8.setColspan(4);
        cell8.setBorderWidth(1);//设置表格的边框宽度为0
        cell8.setMinimumHeight(90);
        table.addCell(cell8);

        PdfPCell cell9 = new PdfPCell(new Phrase("相关数据",fontCN));
        cell9.setColspan(4);
        cell9.setBorderWidth(1);//设置表格的边框宽度为0
        cell9.setMinimumHeight(30);
        table.addCell(cell9);

        PdfPCell cell10 = new PdfPCell(new Phrase(data,fontCN));
        cell10.setColspan(4);
        cell10.setBorderWidth(1);//设置表格的边框宽度为0
        cell10.setMinimumHeight(90);
        table.addCell(cell10);

        PdfPCell cellA = new PdfPCell(new Phrase("结论",fontCN));
        cellA.setColspan(4);
        cellA.setBorderWidth(1);//设置表格的边框宽度为0
        cellA.setMinimumHeight(30);
        table.addCell(cellA);

        PdfPCell cellB = new PdfPCell(new Phrase("cell B",fontCN));
        cellB.setColspan(4);
        cellB.setBorderWidth(1);//设置表格的边框宽度为0
        cellB.setMinimumHeight(90);
        table.addCell(cellB);

        PdfPCell cellC = new PdfPCell(new Phrase(advise,fontCN));
        cellC.setColspan(4);
        cellC.setBorderWidth(1);//设置表格的边框宽度为0
        cellC.setMinimumHeight(30);
        table.addCell(cellC);

        PdfPCell cellD = new PdfPCell(new Phrase("cell D",fontCN));
        cellD.setColspan(4);
        cellD.setBorderWidth(1);//设置表格的边框宽度为0
        cellD.setMinimumHeight(90);
        table.addCell(cellD);

        PdfPCell cellE = new PdfPCell(new Phrase("领导意见",fontCN));
        cellE.setColspan(2);
        cellE.setBorderWidth(1);//设置表格的边框宽度为0
        cellE.setMinimumHeight(30);
        table.addCell(cellE);

        PdfPCell cellF = new PdfPCell(new Phrase("审批意见",fontCN));
        cellF.setColspan(2);
        cellF.setBorderWidth(1);//设置表格的边框宽度为0
        cellF.setMinimumHeight(30);
        table.addCell(cellF);

        PdfPCell cellM = new PdfPCell(new Phrase("",fontCN));
        cellM.setColspan(2);
        cellM.setBorderWidth(1);//设置表格的边框宽度为0
        cellM.setMinimumHeight(70);
        table.addCell(cellM);

        PdfPCell cellN = new PdfPCell(new Phrase("",fontCN));
        cellN.setColspan(2);
        cellN.setBorderWidth(1);//设置表格的边框宽度为0
        cellN.setMinimumHeight(70);
        table.addCell(cellN);
        document.add(table);
    }catch (DocumentException  e) {
        e.printStackTrace();
    } finally {
        document.close();
    }
}
}

四、文档下载的servlet

package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        /*-----------------接收文件名和文件路径-----------------------------------*/
        String filename = request.getParameter("filename");
        String path = request.getParameter("filepath");
        //System.out.println(filename);
        response.setContentType(getServletContext().getMimeType(filename));
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        //String fullFileName=getServletContext().getRealPath("/download/"+filename);
        InputStream in=new FileInputStream(path);
        OutputStream out = response.getOutputStream();
        //创建缓冲区
        byte buffer[] = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while((len=in.read(buffer))>0){
            //输出缓冲区的内容到浏览器,实现文件下载
            out.write(buffer, 0, len);
        }
        //关闭文件输入流
        in.close();
        //关闭输出流
        out.close(); } 

}
时间: 2024-11-06 03:56:32

Java 使用itext生成pdf以及下载的相关文章

java使用iText生成pdf表格

转载地址:http://www.open-open.com/code/view/1424011530749 首先需要你自己下载itext相关的jar包并添加引用,或者在maven中添加如下引用配置: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <dependency>     <groupId>com.lowagie</groupId>     <artifactId>iText</artifactId>  

Java Itext 生成PDF文件

利用Java Itext生成PDF文件并导出,实现效果如下: PDFUtil.java package com.jeeplus.modules.order.util; import java.io.OutputStream; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Arr

itext生成PDF文件报错“Font &#39;STSong-Light&#39; with &#39;UniGB-UCS2-H&#39; is not recognized.”

最近需要写一个抽取表结构的工具,类似于powerdesigner中的表图,其中有一步用到了itext这个第三方jar包来生成pdf文件,碰到了一个问题,记录于此. 问题描述: 工程使用maven构建,pom.xml中对于jar包的定义如下: <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</vers

java调用wkhtmltopdf生成pdf文件,美观,省事

最近项目需要导出企业风险报告,文件格式为pdf,于是搜了一大批文章都是什么Jasper Report,iText ,flying sauser ,都尝试了一遍,感觉不是我想要的效果, 需要自己调整好多东西,样式,字体等等,好麻烦,毕竟博主这么懒的人,哈哈.-------jstarseven 言归正传: java生成pdf文件,方式很多,以上提到的哪几种方式具体可以参考这篇文章<讲解很详细>:http://blog.csdn.net/ouyhong123/article/details/2640

利用itext生成pdf的简单例子

一.itext简介 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转化为PDF文件. iText的安装非常方便,在http://www.lowagie.com/iText/download.html网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了 二 .生成简单的pdf文件 1

itext 生成pdf文件添加页眉页脚

原文来自:https://www.cnblogs.com/joann/p/5511905.html 我只是记录所有jar版本,由于版本冲突及不兼容很让人头疼的,一共需要5个jar, 其中itextpdf是itext的升级版本,并且itextpdf-5.5.jar以上版本算总页数不需要-1,之前版本必须-1: jfinal.jar只能用2.0版本,用3.0的会报版本过高:希望能帮到有需要的人 itextpdf-5.5.13.jar 下载地址:http://central.maven.org/mav

新知识:Java 利用itext填写pdf模板并导出(昨天奋战到深夜四点,知道今天两点终于弄懂)

废话少说,不懂itext干啥用的直接去百度吧. ***************制作模板******************* 1.先用word做出界面 2.再转换成pdf格式 3.用Adobe Acrobat 打开你刚刚用word转换成的pdf 会出现如下界面 下一步 点击浏览,选择刚才你转换好的pdf 下一步 4.打开后它会自动侦测并命名表单域,右键表单域,点击属性,出现文本域属性对话框,有的人说要改成中文字体,可是我没有改一样成功啦 5.一般情况下不需要修改什么东西,至少我没有修改哦 6.直

Freemarker+IText生成pdf文件

最近项目中遇到要用html生成pdf文件的需求,一开始研究了下前端插件jspdf,使用h5 canvas绘图生成图片,再把图片生成pdf文件,遇到了各种各样的问题,生成的pdf文件达到20多M,height超过5000浏览器就崩溃,有兴趣的童鞋可以尝试一下,该方案LZ最终放弃了. 接着开始尝试服务端生成,使用freemaker模板生成静态html文件,通过iext生成pdf,网上很多关于renderer.setDocument(dom,null)的用法,LZ尝试后发现效率奇低,最后放弃了,直接使

iText生成PDF的关键源码分析

对于iText的学习,基本上都是来源于官网上的例子.这和我学习easyUI.jQuery的途径都是一致的. 这也再次证明了,想用好一个软件,官方提供的例子和文档都是最佳的学习资料. 因为对方是最了解这款软件的人,设计出来的demo当然是最有应用价值的~ 这里吐槽一下,iText的demo真难找,官网上反反复复找了好多次才找到,不知道大家是否和我一样,在这里给大家一个捷径. 下面就拿官网的例子来讲一讲,首先如何生成PDF? /** * 这也就是所有demo中最核心的代码 * Creates a P