创建PDF模板,java添加内容、导出下载PDF
2024-10-09 07:38:58
本文主要内容是:用java在pdf模板中加入数据,图片。
废话不多说,举个非常简单的例子:
首先创建word文档,导出PDF。
用 软件adobe acrobat打开,操作步骤如图:
在指定位置添加文本域, 保存退出。pdf模板创建完成,我们保存到 E:盘,起名叫 练习。
接下来是java内容。
在pom.xml文件加入,
<!-- itext 图片转pdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.</version>
</dependency>
在Controller层创建,节约时间直接附上代码
package com.boot.controller; import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper; @RestController
public class PdfController { /**
* 导出pdf
* @author Changhai
* @param response
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value={"/exportpdf"})
public String exportPdf(HttpServletResponse response) throws UnsupportedEncodingException {
// 指定解析器
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
//String path = request.getSession().getServletContext().getRealPath("/upload/");
String filename="练习.pdf";
String path="e:/";
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;fileName="
+ URLEncoder.encode(filename, "UTF-8"));
OutputStream os = null;
PdfStamper ps = null;
PdfReader reader = null;
try {
os = response.getOutputStream();
// 2 读入pdf表单
reader = new PdfReader(path+ "/"+filename);
// 3 根据表单生成一个新的pdf
ps = new PdfStamper(reader, os);
// 4 获取pdf表单
AcroFields form = ps.getAcroFields();
// 5给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示
BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
form.addSubstitutionFont(bf);
// 6查询数据================================================
Map<String, Object> data = new HashMap<String, Object>();
data.put("name", "小帅哥");
data.put("like", "大美女");
// 7遍历data 给pdf表单表格赋值
for (String key : data.keySet()) {
form.setField(key,data.get(key).toString());
}
ps.setFormFlattening(true);
//-----------------------------pdf 添加图片----------------------------------
// 通过域名获取所在页和坐标,左下角为起点
System.out.println("pdf 添加图片");
String imgpath="e:/美女.png";
int pageNo = form.getFieldPositions("img").get().page;
Rectangle signRect = form.getFieldPositions("img").get().position;
float x = signRect.getLeft();
float y = signRect.getBottom();
// 读图片
Image image = Image.getInstance(imgpath);
// 获取操作的页面
PdfContentByte under = ps.getOverContent(pageNo);
// 根据域的大小缩放图片
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
//-------------------------------------------------------------
System.out.println("===============PDF导出成功=============");
} catch (Exception e) {
System.out.println("===============PDF导出失败=============");
e.printStackTrace();
} finally {
try {
ps.close();
reader.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
在浏览器上访问
www.localhost:8080/exportpdf
好了 pdf下载成功
效果图:
感谢您的阅读
最新文章
- Xamarin.Android之ActionBar与菜单
- RPM包的制作
- Linux环境下解压超过4GB的zip文件
- The Python Tutorial
- MVC过滤器使用案例:统一处理异常顺道精简代码
- php四种基础算法:冒泡,选择,插入和快速排序法
- [SQL]select scope_identity()传回插入相同范围之识别资料行中的最后一个识别值
- date类型时间比较大小
- sql 调用函数的方法
- pgsql获取表相关数据
- ajax提交的javascript代码
- shopex-百度爬虫抓取过于频繁导致php-cgi占用CPU过高的解决办法
- H5左侧滑删除简单实现
- 如何往linux上面上传东西
- 解决jpgraph在php7.0版本下时,无法显示例子图表的问题
- solusvm安装过程
- django之前-----web应用与框架
- 吴裕雄 oracle PL/SQL编程
- 24.Mysql高级安装和升级
- splay专题复习——bzoj 3224 &; 1862 &; 1503 题解