依据原来的的pdf,我今天又用以前的SpringMVC重新写了一份。
学习就是要活学活用,请不要死板!!!
原文:https://blog.csdn.net/weixin_40989555/article/details/80742607
必要的maven依赖
<!-- pdf打印 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
页面部分
<%--==========查询的from表单:===========--%>
<div class="input-group" style="margin-left:50px;">
<form id="searchForm" name="searchForm" action="${pageContext.request.contextPath}/notice/searchNotice" method="post">
<span style="height: 35px;font-size: 18px">消息内容:</span><input id="searchContent" name="content" type="text" class="input_area" value="${content}">
<span style="height: 35px;font-size: 18px">起始日期:</span><input id="startDate" name="startDate" style="width:200px" type="text" class="input_area" value="${startDate}">
<span style="height: 35px;font-size: 18px">结束日期:</span><input id="endDate" name="endDate" style="width:200px" type="text" class="input_area" value="${endDate}">
<button class="btn btn-info btn-sm" type="submit"><i class="glyphicon glyphicon-search"></i>搜索</button>
<button class="btn btn-danger btn-sm" onclick="jsClearForm(document.forms[0]);" type="button"><i class="glyphicon glyphicon-refresh"></i>重置</button>
</form>
<a onclick="downloadPdf()" target="_self" class="btn btn-info btn-sm" data-toggle="modal" >导出pdf</a>
</div>
<%--==========公用模态框============--%>
<div class="modal fade" id="commonModal" role="dialog" aria-hidden="true" aria-labelledby="myModalLabel">
<div class="modal-dialog ">
<div class="modal-content ">
<div class="modal-header">
<button class="close" aria-hidden="true" type="button" data-dismiss="modal">
×关闭
</button>
<h4 class="modal-title" id="com_title">
</h4>
</div>
<div class="modal-body" >
<h3 class="modal-title" id="com_msg" style="text-align:center"><%--提示信息--%>
</h3>
<form method="POST" enctype="multipart/form-data" id="com_form" action="">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn_modal" id="com_btn">确定</button>
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
</div>
</div>
</div>
</div>
JS
//生产pdf
var p_count = 0;
function downloadPdf(){
$('#com_form').empty();//删除被选元素的子元素
if(p_count == 0){
var html = "";
html += '<input id="p_content" name="p_content" type="hidden" class="input_area" value=""> ';
html += '<input id="p_st" name="p_st" type="hidden" class="input_area" value=""> ';
html += '<input id="p_et" name="p_et" type="hidden" class="input_area" value=""> ';
$('#com_form').append(html);
p_count ++;
}
$('#p_content').val($('#searchContent').val());
$('#p_st').val($('#startDate').val());
$('#p_et').val($('#endDate').val());
$('#com_title').text('确定?');
$('#com_msg').text('是否打印当前数据?');
$('#com_btn').on('click', function (){//绑定按钮点击事件
$('#com_form').attr('action', '${pageContext.request.contextPath}/notice/downloadPdf.do');//声明访问路径,form表单提交
$('#com_form').submit();
$("#commonModal").modal('hide');
});
$("#commonModal").modal('show');//显示模态框
}
后台:
import java.io.*;
//生成pdf引用
import com.itextpdf.text.Element;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
@Controller
@RequestMapping("notice")
public class NoticeController {
@Autowired
private NoticeService noticeService;
/**
* 生成pdf
*/
@RequestMapping(value = "/downloadPdf.do")
public String downloadPdf(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String content = req.getParameter("p_content").trim();
String startDate = req.getParameter("p_st");
String endDate = req.getParameter("p_et");
Map<String, String> map = new HashMap<String, String>();
String searchContent = "%" + content + "%";
if(searchContent.length() > 0){
map.put("searchContent", searchContent);
}
if(startDate.trim().length() > 0){
map.put("startDate", startDate.trim());
}
if(endDate.trim().length() > 0){
map.put("endDate", endDate.trim());
}
List<Notice> list = noticeService.searchNotice(map);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
/*******pdf文件内容生成开始*********/
Document document = new Document(PageSize.A4, 25, 25, 25, 25);
//创建文件夹
String filePar = null;
filePar = "D:/systemTest/"+new Date().getTime();// 文件夹路径
File myPath = new File( filePar );
file = new File(filePar+"/消息列表"+ new Date().getTime()+".pdf");
if (!myPath.exists()){
myPath.mkdir();
}
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
//设置中文字体
BaseFont bfChinese = null;// FontFactory.getFont(FontFactory.COURIER,
// 14, Font.BOLD, new CMYKColor(0, 255, 0, 0);//大小,粗细,颜色
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
} catch (IOException e) {
e.printStackTrace();
}
Font f10 = new Font(bfChinese, 10, Font.NORMAL);
Font f12 = new Font(bfChinese, 12, Font.NORMAL);
Font f26 = new Font(bfChinese, 26, Font.NORMAL);//一号字体
//创建标题
Paragraph title1 = new Paragraph("反馈消息", f26);
title1.setAlignment(Element.ALIGN_CENTER);
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);
Section section1 = chapter1;
/*Paragraph title2 = new Paragraph("老板,请问有没有哇哈哈~~矿泉水。", f12);
title2.setLeading(22f);//-行间距
section1.add(title2);*/
// 创建4列的表格
int colNumber = 3;
PdfPTable t = new PdfPTable(colNumber);
//设置段落上下空白
t.setSpacingBefore(25);
t.setSpacingAfter(25);
t.setHorizontalAlignment(Element.ALIGN_CENTER);// 居左
float[] cellsWidth = { 0.2f, 0.55f, 0.25f }; // 定义表格的宽度
t.setWidths(cellsWidth);// 单元格宽度
t.setTotalWidth(500f);//表格的总宽度
t.setWidthPercentage(100);// 表格的宽度百分比
//设置表头
PdfPCell c1 = new PdfPCell(new Paragraph("ID",f12));
t.addCell(c1);
PdfPCell c2 = new PdfPCell(new Paragraph("消息内容",f12));
t.addCell(c2);
PdfPCell c3 = new PdfPCell(new Paragraph("创建时间",f12));
t.addCell(c3);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
for (Notice notice : list) {
t.addCell(new Paragraph(String.valueOf(notice.getId()),f10));
t.addCell(new Paragraph(notice.getContent(),f10));
t.addCell(new Paragraph(sdf.format(notice.getCreate_time()),f10));
}
section1.add(t);
document.add(chapter1);
document.close();
/*******pdf文件生成结束*********/
try {
fin = new FileInputStream(file);
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/pdf");
String filename = "消息列表";
// 设置浏览器以下载的方式处理该文件
if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
filename = URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}
resp.setHeader("Content-Disposition", "attachment;filename=" + filename + ".pdf");//下载使用
out = resp.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null)
fin.close();
if (out != null)
out.close();
if (file != null)
file.delete(); // 删除临时文件
if (myPath != null)// 删除临时文件夹
myPath.delete();
}
return null;
}
}
import java.util.List;
import java.util.Map;
import org.education.web.entity.Notice;
/**
*
* @author 作者 E-mail:云端的辣椒
* @date 创建时间:2017年11月19日 下午13:25:13
* @version 1.0
*
*/
public interface NoticeService {
//记录数
public int getNoticeCount();
//获取消息列表
public List<Notice> getNoticeList();
//增加
public boolean addNotice(Notice notice);
//逻辑删除
public boolean deleteById(int id);
//查询信息
public List<Notice> searchNotice(Map<String, String> map);
//批量删除
public boolean batchDeletes(List<String> delList);
//通过id查询信息
public Notice selectByPrimaryKey(Integer id);
//通过id修改
public void updateNoticeById(Notice notice);
}
import java.util.List;
import java.util.Map;
import org.education.web.dao.NoticeMapper;
import org.education.web.entity.Notice;
import org.education.web.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author 作者 E-mail:云端的辣椒
* @date 创建时间:2017年11月19日 下午13:26:20
* @version 1.0
*
*/
@Service
public class NoticeServiceImpl implements NoticeService {
@Autowired
private NoticeMapper noticeMapper;
@Override
public int getNoticeCount() {
return noticeMapper.getNoticeCount();
}
@Override
public List<Notice> getNoticeList() {
return noticeMapper.getNoticeList();
}
@Override
public boolean addNotice(Notice notice) {
return noticeMapper.addNotice(notice);
}
// 通过条件 查询分页对象
@Override
public List<Notice> searchNotice(Map<String, String> map) {
return noticeMapper.searchNotice(map);
}
@Override
public boolean deleteById(int id) {
return noticeMapper.deleteById(id);
}
@Override
public boolean batchDeletes(List<String> delList) {
return noticeMapper.batchDeletes(delList);
}
@Override
public Notice selectByPrimaryKey(Integer id) {
return noticeMapper.selectByPrimaryKey(id);
}
@Override
public void updateNoticeById(Notice notice) {
noticeMapper.updateNoticeById(notice);
}
}
import java.util.List;
import java.util.Map;
import org.education.web.entity.Notice;
/**
*
* @author 作者 E-mail:云端的辣椒
* @date 创建时间:2017年11月19日 下午13:22:52
* @version 1.0
*
*/
public interface NoticeMapper {
int getNoticeCount();
//获取消息列表
public List<Notice> getNoticeList();
//增加
public boolean addNotice(Notice notice);
//逻辑删除
public boolean deleteById(Integer id);
//批量删除
public boolean batchDeletes(List<String> delList);
//搜寻信息
public List<Notice> searchNotice(Map<String, String> map);
//通过id查询信息
public Notice selectByPrimaryKey(Integer id);
//通过id修改
public void updateNoticeById(Notice notice);
}
Mybatis
<select id="searchNotice" parameterType="java.util.Map" resultMap="NoticeResultMap">
select id,content,create_time from notice
<where>
status=0
<if test="searchContent !='' and searchContent != null">
and content like #{searchContent}
</if>
<if test="endDate !='' and endDate != null">
and create_time between #{startDate} and #{endDate}
</if>
<if test="startDate !='' and startDate != null">
and create_time > #{startDate}
</if>
</where>
order by create_time desc
</select>
到这里也差不多了,来看下效果吧。