- package com.app.util;
-
- import com.itextpdf.text.Rectangle;
- import com.itextpdf.text.pdf.*;
-
- import javax.imageio.ImageIO;
- import java.awt.image.BufferedImage;
- import java.io.*;
- import java.util.Base64;
- import java.util.HashMap;
- import java.util.Map;
-
- public class TestPdf {
-
- public static void main(String[] args) throws Exception {
- testPdf();
-
- }
-
- static void testPdf() throws Exception {
- // 模板文件路径
- String inputFileName = "D:\\pdfWork\\1.pdf";
- // 生成的文件路径
- String outputFileName = "D:\\pdfWork\\2.pdf";
- OutputStream os = null;
- PdfStamper ps = null;
- PdfReader reader = null;
- PdfStamper stamper = null;
- try {
- os = new FileOutputStream(new File(outputFileName));
- // 2 读入pdf表单
- reader = new PdfReader(inputFileName);
- // 3 根据表单生成一个新的Pdf
- ps = new PdfStamper(reader, os);
-
- String password = "123456";
- //pdf权限,值为"PdfWriter.ALLOW_PRINTING"
- int permission = 0;
- ps.setEncryption(password.getBytes(),
- password.getBytes(),PdfWriter.ALLOW_SCREENREADERS, false);
-
- // 4 获取pdf表单
- AcroFields form = ps.getAcroFields();
- // 5给表单添加中文字体
- // BaseFont bf = BaseFont.createFont("Font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
- // form.addSubstitutionFont(bf);
- // 6查询数据================================================
- Map<String, Object> data = new HashMap<String, Object>();
- data.put("AName", "张三");
- data.put("BName", "李四");
- data.put("ACode", "Z3");
- data.put("BCode", "L4");
- data.put("Sign_Date", "2023-9-9");
-
- //图片地址
- String imageUrl = "D:\\pdfWork\\1.png";
- String imgBase64 = convertImageToBase64Str(imageUrl);
- //String img2Base64 = convertImageToBase64Str(imgUrl);
- Map<String, String> templateImageMap = new HashMap<>();
- data.put("AImg", imgBase64);
- data.put("BImg", imgBase64);
-
- ps.setFormFlattening(true);
-
- 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();
- }
- }
- }
-
- /**
- * 图片转Base64字符串
- * @param imageFileName
- * @return
- */
- public static String convertImageToBase64Str(String imageFileName) {
- ByteArrayOutputStream baos = null;
- try {
- //获取图片类型
- String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
- //构建文件
- File imageFile = new File(imageFileName);
- //通过ImageIO把文件读取成BufferedImage对象
- BufferedImage bufferedImage = ImageIO.read(imageFile);
- //构建字节数组输出流
- baos = new ByteArrayOutputStream();
- //写入流
- ImageIO.write(bufferedImage, suffix, baos);
- //通过字节数组流获取字节数组
- byte[] bytes = baos.toByteArray();
- //获取JDK8里的编码器Base64.Encoder转为base64字符
- return Base64.getEncoder().encodeToString(bytes);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (baos != null) {
- baos.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- }
复制代码
|