package com.kingdee.eas.custom.ssPDF.utils; import com.itextpdf.text.pdf.*; import com.kingdee.bos.BOSException; //import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.ZipParameters; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class PDFFillInformationUtil { /** * 给pdf填充数据 * @param file 原始文件 * @param field map key 为字段名,value 为填充值 * @return 填充后的文件 文件类型为byte[] */ public File fillInformation(byte[] file, Map field,String tempFilePath,String fileName) throws IOException { try { System.setProperty("javax.xml.parsers.DocumentBuilderFactory","com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); // 读取PDF模板 PdfReader pdfReader = new PdfReader(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 创建需就改PDF文件 PdfStamper pdfStamper = new PdfStamper(pdfReader, baos); AcroFields form = pdfStamper.getAcroFields(); BaseFont bf = BaseFont.createFont("c:/windows/fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 设置字段数据 ArrayList fontList = new ArrayList(); fontList.add(bf); form.setSubstitutionFonts(fontList); Iterator> iterator = field.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); String key = entry.getKey(); String value = entry.getValue(); //给字段添加值 form.setField(key, value); //form.setFieldProperty(key, "setflags", PdfFormField.MARKUP_HIGHLIGHT, null); } //生成后的pdf 可以在编辑 pdfStamper.setFormFlattening(false); // 关闭修改器,并释放资源 pdfStamper.close(); pdfReader.close(); File outFile = new File(tempFilePath+"/"+fileName); // if (!outFile.createNewFile()) { // throw new RuntimeException("pdf 填充数据失败!!"); // } if (!(outFile.exists())) { outFile.createNewFile(); } else { outFile.delete(); outFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(outFile); baos.writeTo(fos); fos.close(); // 关闭流释放资源 return outFile; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("pdf 填充数据失败!!"); } } /** * 创建压缩包 * * @param destFileName * @param files * @return */ // public static String compress(String destFileName, List files) throws BOSException { // ZipParameters parameters = new ZipParameters(); // //parameters.setCompressionMethod(8); // //parameters.setCompressionLevel(5); // try { // ZipFile zipFile = new ZipFile(destFileName); // for (int i = 0; i < files.size(); ++i) { // File file = files.get(i); // zipFile.addFile(file, parameters); // } // return destFileName; // } catch (ZipException var9) { // var9.printStackTrace(); // throw new BOSException(var9.getMessage()); // } // } }