使用方法:

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'] = "632827168@qq.com";
$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(); } }

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

  1. java使用iText生成pdf表格

    转载地址:http://www.open-open.com/code/view/1424011530749 首先需要你自己下载itext相关的jar包并添加引用,或者在maven中添加如下引用配置: ...

  2. 【PDF】java使用Itext生成pdf文档--详解

    [API接口]  一.Itext简介 API地址:javadoc/index.html:如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/ ...

  3. 关于java poi itext生成pdf文件的例子以及方法

    最近正在做导出pdf文件的功能,所以查了了一些相关资料,发现不是很完善,这里做一些小小的感想,欢迎各位“猿”童鞋批评指正. poi+itext,所需要的jar包有itext-2.1.7.jar,poi ...

  4. Java Itext 生成PDF文件

    利用Java Itext生成PDF文件并导出,实现效果如下: PDFUtil.java package com.jeeplus.modules.order.util; import java.io.O ...

  5. Java使用iText7生成PDF

    前言 我们之前使用js库html2canvas + jspdf实现html转PDF.图片,并下载(详情请戳:html页面转PDF.图片操作记录),大致原理是将页面塞到画布里,以图片的方式放到PDF中, ...

  6. java利用iTextWorker生成pdf

    使用itext生成pdf,在linux环境下,中文全部失踪,因为itext要在linux下支持中文字体需要引入itext-asian, 并添加一个字体类. public static class Pd ...

  7. 在linux环境下使用itext生成pdf

    转载请注明出处 https://www.cnblogs.com/majianming/p/9537173.html 项目中需要对订单生成pdf文件,在不断的尝试之后,终于生成了比较满意的pdf文档. ...

  8. 用itext生成PDF报错:Font 'STSong-Light1' with 'UniGB-UCS2-H' is not recognized.

    用itext生成PDF报错,加上try catch捕获到异常是 BaseFont bFont = BaseFont.createFont("STSong-Light1", &quo ...

  9. 【Java】使用iText生成PDF文件

    iText介绍 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转 ...

随机推荐

  1. FreeSWITCH 基础

    [1]FreeSWITCH 是什么? FreeSWITCH是一个开源的电话交换平台. 世界上第一个跨平台的.伸缩性极好的.免费的.多协议的电话软交换平台. 从技术上讲,FreeSWITCH是一个B2B ...

  2. sublime中如何安装vue.js插件,并使代码高亮显示

    前提概要: sublime的下载地址:http://www.sublimetext.com/ notepad++下载地址:https://notepad-plus-plus.org/ .vue的文件在 ...

  3. html 自动跳转,meat(http-equiv)标签详解

    http-equiv顾名思义,相当于http的文件头作用,它可以向浏览器传回一些有用的信息,以帮助正确和精确地显示网页内容,与之对应的属性值为content,content中的内容其实就是各个参数的变 ...

  4. 配置过滤器filter对跨站脚本攻击XSS实现拦截

    1.web.xml中配置filter [html] view plain copy   <filter> <filter-name></filter-name> & ...

  5. DNN优势

  6. Orthogonal Least Squares Learning Algorithm for Radial Basis Function Networks

    Orthogonal Least Squares Learning Algorithm for Radial Basis Function Networks S. Chen, C. F. N. Cow ...

  7. phpstorm+xdebug, 实现断点调试: xdebug如何配置

    [XDebug] xdebug.profiler_output_dir="D:\phpStudy\tmp\xdebug" xdebug.trace_output_dir=" ...

  8. 蓝屏代码stop:0X000000EA(0X85E286B8,0X8635F210,0XF7A53CBC,0X00000001)

    你这是显卡驱动问题,我把蓝屏代码都给你,以后在出现蓝屏自己看看行了. 1.0x0000000A:IRQL_NOT_LESS_OR_EQUAL ◆错误分析:主要是由问题的驱动程序.有缺陷或不兼容的硬件与 ...

  9. 关于scrollLeft的获取在不同浏览器或相同浏览器的不同版本下的获取

    chrome61向w3c规则靠拢,document.body.scrollLeft获取的值一直为0,需要使用document.documentElement.scrollLeft(或document. ...

  10. PAT 天梯赛 L3-013. 非常弹的球 【物理】

    题目链接 https://www.patest.cn/contests/gplt/L3-013 思路 将速度 分解成 竖直方程 和 垂直方向 当 角度为 45° 时 射出的时候 水平方向 最远 所以 ...