Itext使用 Java导出PDF

7 篇文章 0 订阅
3 篇文章 0 订阅

需求:需要将多张二维码输出到pdf中,供前端下载,并在每个二维码下面添加名称信息

itext:
可以帮助我们根据生成pdf文件
maven坐标

 <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
  </dependency>

操作流程:

controller 获取请求和响应对象
@RequestMapping(value = "/exportPdf")
	public void excelPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
		towerSiteService.exportPdf(request, response);
	}
service 对数据进行处理返回到前台

用到的对象
Document pdf文档对象
Rectangle 文档对象的格式
PdfPTable pdf表格对象
BaseFont 设置字体
Image 读取图片
PdfPCell 单元格
Paragraph 段落 可添加到单元格

public void exportPdf(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/pdf");
		// 设置文件名称
		response.setHeader("Content-Disposition", "attachment;filename=站址二维码.pdf");
		String hql = "from TowerSite g ";
		// 获取数据
		List<Data> list = 数据库.查询方法();
		// 设置纸张规格
		Document doc = new Document();
		Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
		doc.setPageSize(pageSize);
		try {
			PdfWriter.getInstance(doc, response.getOutputStream());
			doc.open();
			// 新建pdf表格
			PdfPTable table = new PdfPTable(4);
			for (Data data : list) {
				// 添加中文字体
				BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				// 设置字体
				Font font = new Font(bfChinese, 12, Font.NORMAL);
				Image image = Image.getInstance("图片地址");
				// 新建单元格
				PdfPCell cell = new PdfPCell();
				// 添加图片
				cell.addElement(image);
				// 设置站址编码
				cell.addElement(new Paragraph("测试标题1:" + data.getTitle(), font));
				// 设置站址名称
				cell.addElement(new Paragraph("测试标题2:" + data.getTitle(), font));
				table.addCell(cell);
			}
           //添加空格 撑开表格
			table.addCell("");
			table.completeRow();
			doc.add(table);
			doc.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

具体流程:
创建文档对象 -----设置文档格式------创建表格对象—设置字体----获取图片----循环数据----创建单元格—向单元格添加图片–添加其他内容----将表格对象添加到文档对象–关闭文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值