Java导出根据模板PDF(Springboot+Adobe Acrobat)

1、使用Adobe Acrobat创建PDF模板(设置文本域),文本域命名对应Java实体类
在这里插入图片描述
在这里插入图片描述

2、引入依赖

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

3、编写实现类和控制类

@Service
@Slf4j
public class PdfServiceImpl implements PdfService {
    @Override
    public void generator(Invoice invoice, HttpServletResponse response) throws UnsupportedEncodingException, FileNotFoundException {
        // 模板名称
        String templateName = "Invoice_elle_April2022模板.pdf";
        String path = "";
        // 获取操作系统名称,根据系统名称确定模板存放的路径
        String systemName = System.getProperty("os.name");
        if (systemName.toUpperCase().startsWith("WIN")) {
            path = "C:/Users/Administrator/Desktop/";
        }
        // 生成导出PDF的文件名称
        String fileName = "Invoice.pdf";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        // 设置响应头
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        OutputStream out = null;
        PdfReader reader = null;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            // 保存到本地
            // out = new FileOutputStream(fileName);
            // 输出到浏览器端
            out = response.getOutputStream();
            // 读取PDF模板表单
            reader = new PdfReader(path + templateName);
            // 字节数组流,用来缓存文件流
            bos = new ByteArrayOutputStream();
            // 根据模板表单生成一个新的PDF
            stamper = new PdfStamper(reader, bos);
            // 获取新生成的PDF表单
            AcroFields form = stamper.getAcroFields();
            // 给表单生成中文字体,这里采用系统字体,不设置的话,中文显示会有问题
            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(font);
            // 装配数据
            Map<String, Object> data = new HashMap<>(15);
            data.put("billedTo", invoice.getBilledTo());
            data.put("dateOfIssue", invoice.getDateOfIssue());
            data.put("invoiceNumber", invoice.getInvoiceNumber());
            data.put("amountDue", invoice.getAmountDue());
            data.put("description", invoice.getDescription());
            data.put("rate", invoice.getRate());
            data.put("qty", invoice.getQty());
            data.put("lineTotal", invoice.getLineTotal());
            data.put("total", invoice.getTotal());
            // 遍历data,给pdf表单赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            // 表明该PDF不可修改
            stamper.setFormFlattening(true);
            // 关闭资源
            stamper.close();
            // 将ByteArray字节数组中的流输出到out中(即输出到浏览器)
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            log.info("*****************************PDF导出成功*********************************");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
public interface PdfService {
    void generator(Invoice invoice, HttpServletResponse response) throws UnsupportedEncodingException, FileNotFoundException;
}
@RestController
@RequestMapping("/pdf")
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @PostMapping("/export")
    public void generatorAdmissionCard(@RequestBody Invoice invoice, HttpServletResponse response) {
        try {
            pdfService.generator(invoice, response);
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

4、导出效果(字体和换行可在Adobe Acrobat中设置)
在这里插入图片描述

参考文章:
Java如何实现Pdf的导出?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java根据PDF模板生成PDF的过程可以通过使用JavaPDF库来实现。有一些流行的Java PDF库,如iText和Apache PDFBox,可以提供生成PDF的功能。这些库允许你使用Java代码来创建和编辑PDF文档,并且可以根据给定的PDF模板生成新的PDF文件。 下面是一个使用iText库来根据PDF模板生成PDF的简单示例代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; public class PdfGenerator { public static void main(String[] args) { try { // 读取PDF模板文件 PdfReader reader = new PdfReader("template.pdf"); // 创建新的PDF文件 Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream("output.pdf")); document.open(); // 替换模板中的内容 PdfStamper stamper = new PdfStamper(reader, copy); AcroFields form = stamper.getAcroFields(); form.setField("field1", "value1"); form.setField("field2", "value2"); stamper.close(); document.close(); System.out.println("PDF生成成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 这段代码首先使用PdfReader读取PDF模板文件,然后创建一个新的PDF文件。接着使用PdfStamper替换模板中的内容,其中`form.setField("field1", "value1")`语句用于替换PDF中的字段内容。最后,通过关闭stamper和document来保存和关闭新生成PDF文件。 请注意,以上示例仅供参考,并且需要根据你的具体需求进行修改和适配。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值