前言:本章节采用的文件服务器是七牛云的,不同的文件服务器可以根据实际api不同作出相应的操作
好了废话不多说,开始撸代码

First:导入pom依赖

<!-- 操作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>
        <!-- 操作七牛云-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>[7.2.0, 7.2.99]</version>
        </dependency>

导入好了pom依赖后记得更新maven 工程哦

Second:制作好一个上传七牛云的工具类

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import lombok.extern.java.Log;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@Log
public class QiniuUtil {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static final String ACCESS_KEY = "****";
    private static final String SECRET_KEY = "****";
    //要上传的空间 bucket name
    private static final String BUCKET_NAME = "****";

    /**
     * 简单上传
     * @param localFilePath
     * @param fileName
     * @return
     * @throws QiniuException
     */
    public static String easyUpLoad(File localFilePath, String fileName) throws QiniuException {
        return intoResult(null,localFilePath,null, fileName,null);
    }

    /**
     * 字节数组上传
     * @param uploadBytes
     * @param fileName
     * @return
     * @throws QiniuException
     */
    public static String byteUpLoad(byte[] uploadBytes, String fileName) throws QiniuException {
        return intoResult(uploadBytes,null,null, fileName,null);
    }


    /**
     * 数据流上传
     * @param byteInputStream
     * @param fileName
     * @return
     * @throws QiniuException
     */
    public static String byteArrayInputStreamUpLoad(ByteArrayInputStream byteInputStream, String fileName) throws QiniuException {
        return intoResult(null,null,byteInputStream, fileName,null);
    }

    /**
     * 断点续上传
     * @param localFilePath
     * @param fileName
     * @return
     */
    public static String recorderUpLoad(File localFilePath, String fileName) {
        String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), BUCKET_NAME).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            return intoResult(null,localFilePath,null,fileName,fileRecorder);
        } catch (IOException ex) {
            ex.printStackTrace();
            return ex.getMessage();
        }
    }

    private static String intoResult(byte[] uploadBytes, File localFilePath, ByteArrayInputStream byteInputStream, String fileName, FileRecorder fileRecorder) throws QiniuException {
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
//        String substring = fileName.substring(fileName.lastIndexOf("."));
        String key = "hlm/images/"+fileName;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        Response response = null;
        try {
            if(uploadBytes != null && localFilePath == null && byteInputStream == null){
                response = uploadManager.put(uploadBytes, key, upToken);
            }
            if(localFilePath != null && uploadBytes == null && byteInputStream == null){
                response = uploadManager.put(localFilePath, key, upToken);
            }
            if(byteInputStream != null  && uploadBytes == null && localFilePath == null){
                response = uploadManager.put(byteInputStream,key,upToken,null, null);
            }
            if(response == null){
                return "参数错误";
            }
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            throw new QiniuException(r);
        }
    }
}

Third:制作生成pdf的方法

直接通过固定模板生成

@RequestMapping(value = "/pdf",method = RequestMethod.GET)
    public String exportPdf(HttpServletResponse response) throws UnsupportedEncodingException {
        // 指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        String filename="XXXXX.pdf";
        String path="C:\\XXX\\XXXX\\Desktop";
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + URLEncoder.encode(filename, "UTF-8"));

        ByteArrayOutputStream byteArrayOutputStream = null;
        PdfStamper ps = null;
        String s = null;
        PdfReader reader = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            // 2 读入pdf表单
            reader = new PdfReader(path+ "/"+filename);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, byteArrayOutputStream);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体
            BaseFont bf = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", false);
            form.addSubstitutionFont(bf);
            // 6查询数据
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("username", "康怀安");
            data.put("idcard", "360302188888888888");
            data.put("mobile", "15888888888");
            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key,data.get(key).toString());
            }
            // 如果为false那么生成的PDF文件还能编辑,一定要设为true
            ps.setFormFlattening(true);
            ps.close();
            reader.close();
            s = QiniuUtil.byteUpLoad(byteArrayOutputStream.toByteArray(), filename);
            System.out.println(s);
            //-----------------------------pdf 添加图片----------------------------------
            // 通过域名获取所在页和坐标,左下角为起点
//            System.out.println("pdf 添加图片");
//            String imgpath="C:\\Users\\Dell\\Desktop\\小图标\\qr\\92021339.jpg";
//            int pageNo = form.getFieldPositions("icon").get(0).page;
//            Rectangle signRect = form.getFieldPositions("icon").get(0).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 {
                if(ps != null){
                    ps.close();
                }
                if(reader != null){
                    reader.close();
                }
                byteArrayOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return s;
    }

读取七牛模板生成pdf(编写一个下载的工具)

private static InputStream download(String url) {
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if (resp.isSuccessful()) {
                ResponseBody body = resp.body();
                return body.byteStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
        return null;
    }
PdfReader reader = new PdfReader(download);

根据一个固定的模板生成pdf,如果你需要下载生成好的模板,可以将byteArrayOutputStream 流改为response.getOutptStream
注意:
PdfStamper 生成的文件要在close之后才会写入传进去的流里面,所有当你不是预留给浏览器下载的时候,记得close再来操作你存储流的对象

你的pdf制作需要使用Adobe Acrobat 9 Pro软件制作

制作方法

java pdf里导入附件 java上传pdf文件_java pdf里导入附件

java pdf里导入附件 java上传pdf文件_上传_02


制作的话还是很简单啦~~~~~~~~~~

这个时候,你是不是需要这个软件啦~~~~~~~~~~~~

下载的也很多资源的,我还没有上传百度云,所有不能给出下载连接了,但是直接搜这个Adobe Acrobat 9 Pro软件的话网络上也是有很多资源的