java pdf 表单填充 linux下获取文件路径 linux下获取Resources下文件路径

  1. 对象转map
		Map<String, String> map = JSON.parseObject(JSONUtil.toJsonStr(platform), new TypeReference<Map<String, String>>() {
		});
  1. 生成pdf
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			log.info("电签流程生成pdf成功");
			byteArrayOutputStream = PdfUtils.genPdf(map);
		}catch (Exception e) {
			log.error("电签流程生成pdf失败 {}", e.getMessage());
			throw new BusinessException(EnumBizCode.ERROR_CODE_FAILED_CREATE_PDF);
		}
  1. 工具类
package com.bison.teamwork.util;

import com.bison.common.constant.BusinessException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.*;
import java.util.Map;

/**
 * Description: PdfUtils <br>
 * 依赖的包:itextpdf    itext-asian
 * commons-io,commons-codec
 */
@Slf4j
public class PdfUtils {

	public static ByteArrayOutputStream genPdf(Map map) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = inputStreamToFile();
		return fillParam(map, byteArrayOutputStream.toByteArray());
	}

	/**
	 * Description: 使用map中的参数填充pdf,map中的key和pdf表单中的field对应 <br>
	 */
	public static ByteArrayOutputStream fillParam(Map<String, String> fieldValueMap, byte[] file) {
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			PdfReader reader = null;
			PdfStamper stamper = null;
			BaseFont base = null;
			try {
				reader = new PdfReader(file);
				stamper = new PdfStamper(reader, byteArrayOutputStream);
				stamper.setFormFlattening(true);
				base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				AcroFields acroFields = stamper.getAcroFields();
				for (String key : acroFields.getFields().keySet()) {
					acroFields.setFieldProperty(key, "textfont", base, null);
					acroFields.setFieldProperty(key, "textsize", new Float(12), null);
				}
				if (fieldValueMap != null) {
					for (String fieldName : fieldValueMap.keySet()) {
						acroFields.setField(fieldName, fieldValueMap.get(fieldName));
					}
				}
			} catch (Exception e) {
				throw new BusinessException(e.getMessage());
			} finally {
				if (stamper != null) {
					try {
						stamper.close();
					} catch (Exception e) {
						throw new BusinessException(e.getMessage());
					}
				}
				if (reader != null) {
					reader.close();
				}
			}
		} catch (Exception e) {
			log.error("填充参数异常");
			throw new BusinessException(e.getMessage());
		} finally {
			IOUtils.closeQuietly(byteArrayOutputStream);
		}
		return byteArrayOutputStream;
	}
	
	/***
	 * linux下获取文件方式
	 * @param  
	 * @return {@link File}
	 * @date 2022/10/26 
	**/
	
	public static File inputStreamToFile(){
		try {
			//读取文件
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			org.springframework.core.io.Resource[] resources = resolver.getResources("verify" + File.separator + "verify.pdf");
			org.springframework.core.io.Resource resource = resources[0];
			InputStream ins = resource.getInputStream();

                        // 此处会一直用缓存 静态文件比较好
			File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "verify.pdf");
			if (file.exists()) {
				return file;
			}
			OutputStream os = new FileOutputStream(file);

			int bytesRead;
			int len = 8192;
			byte[] buffer = new byte[len];
			while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
			return file;
		} catch (IOException e) {
			log.error("获取文件异常");
			throw new BusinessException(e.getMessage());
		}
	}

	/***
	 * linux下获取文件方式
	 * @param
	 * @return {@link ByteArrayOutputStream}
	 * @date 2022/10/26
	 **/

	public static ByteArrayOutputStream inputStreamToFile() {
		InputStream ins = null;
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			//读取文件
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			org.springframework.core.io.Resource[] resources = resolver.getResources("verify" + File.separator + "verify.pdf");
			org.springframework.core.io.Resource resource = resources[0];
			ins = resource.getInputStream();

			byteArrayOutputStream = new ByteArrayOutputStream();
			int bytesRead;
			int len = 8192;
			byte[] buffer = new byte[len];
			while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
				byteArrayOutputStream.write(buffer, 0, bytesRead);
			}
			return byteArrayOutputStream;
		} catch (IOException e) {
			log.error("获取文件异常");
			throw new BusinessException(e.getMessage());
		} finally {
			IoUtil.close(ins);
			IoUtil.close(byteArrayOutputStream);
		}
	}

}

  1. 引入的包
        <!-- pdf文件依赖包 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- pdf字体依赖包 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.11</version>
        </dependency>

posted on   何苦->  阅读(311)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示