记录一次java导出PDF的经验
每次下载导出都要到处搜索,把自己的经验记录下来以便以后使用。
主要思想就是将查询到的数据放入一个Map中调用generateTempPDF方法按照项目中存储的模板生成一个临时目录下的pdf,然后调用controller里面的导出逻辑将临时目录下的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>
1.首先要使用adobe Acrobat pro DC准备表单将参数都填入,例如:
临时目录及模板放入项目的resources下即可:
2.Controller层
@GetMapping(“/exportPersonalPdf”)
public void exportPersonalPdf(HttpServletRequest request, HttpServletResponse response, String testSn) {
BufferedInputStream bis = null;
OutputStream os = null;
String outPath = null;
try {
long userId = getUser();
// 这个地方将数据返回一个导出的pdf临时存储的绝对路径即可
String tempPath = pdfSerrvice.generatePersonalPdf(userId, testSn);
if (tempPath != null) {
// 获取项目根目录
outPath = FileUtil.getFileAbsPath(tempPath);
String fileName = “pdf文件名称.pdf”;
InputStream path = new FileInputStream(outPath);
// 判断浏览器类型
String agent = (String) request.getHeader(“USER-AGENT”);
if (agent != null && agent.indexOf(“Firefox”) != -1) {
// UTF-8编码,防止输出文件名乱码
fileName = new String(fileName.getBytes(“UTF-8”), “iso-8859-1”);
} else {
fileName = URLEncoder.encode(fileName, “UTF-8”);
}
response.reset();
response.setCharacterEncoding(“utf-8”);
response.setContentType(“application/pdf”);
response.setHeader(“Content-Disposition”, “attachment; filename=” + fileName);
bis = new BufferedInputStream(path);
byte[] b = new byte[bis.available() + 1000];
int i = 0;
// 直接下载导出
os = response.getOutputStream();
while ((i = bis.read(b)) != -1) {
os.write(b, 0, i);
}
os.flush();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 下载成功将临时目录下的文件清理
FileUtil.deleteLocationFile(outPath);
}
}
3.业务层
/**
* 生成pdf存放到临时文件夹下
*
* @param dataMap 外部输入的数据
* @param templatePath 模板路径
* @param tempPath 临时文件路径
* @throws IOException 异常
* @return 返回的是生成的pdf临时路径,用完之后需要清理
*/
public static String generateTempPDF(Map<String, Object> dataMap,
String templatePath, String tempPath) throws IOException {
PdfReader reader = null;
PdfStamper ps = null;
OutputStream fos = null;
ByteArrayOutputStream bos = null;
String outPath = null;
try {
// 模板绝对路径 “files/pdf模板.pdf”
String fileName = FileUtil.getFileAbsPath(templatePath);
reader = new PdfReader(fileName);
bos = new ByteArrayOutputStream();
ps = new PdfStamper(reader, bos);
// 使用中文字体
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
fontList.add(bf);
AcroFields fields = ps.getAcroFields();
fields.setSubstitutionFonts(fontList);
fillData(fields, dataMap);//渲染
// 必须要调用这个,否则文档不会生成的
ps.setFormFlattening(true);
if (ps != null) {
ps.close();
}
outPath = FileUtil.getFileAbsPath(tempPath);
// 生成pdf路径存放的路径 "temp/temp" + TimeUtil.formatDate(new Date()) + ".pdf"
File file = new File(outPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(outPath);
fos.write(bos.toByteArray());
} catch (Exception exception) {
log.error("generateTempPDF exception.", exception);
} finally {
if (fos != null) {
fos.flush();
fos.close();
}
if (bos != null) {
bos.close();
}
if (reader != null) {
reader.close();
}
}
return outPath;
}
/**
* 填充模板中的数据
*/
private static void fillData(AcroFields fields, Map<String, Object> data) {
try {
for (String key : fields.getFields().keySet()) {
Object value = data.get(key);
if (value == null) {
continue;
}
fields.setField(key, value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
4.业务中使用的几个方法
import com.google.common.io.BaseEncoding;
import com.sun.jna.Platform;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Base64.Decoder;
/**
* 获取文件绝对路径
*
* @param filePath filePath
* @return String
*/
public static String getFileAbsPath(String filePath) {
String path = null;
if (Platform.isWindows()) {
// 在win64系统的固定位置
path = (GeneratePdf.class.getResource(“/”).getPath() + filePath).substring(1).replaceAll(“/”, “\\”);
} else if (Platform.isLinux()) {
// 在linux64系统的固定位置
path = "/usr/" + filePath;
}
System.out.println(path);
return path;
}
/**
* 将日期date 转换成字符串
*
* @param date date
* @return String
* @throws ParseException
*/
public static String formatDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy_MM_dd_HH_mm_ss”);
String str = simpleDateFormat.format(date);
return str;
}