用java实现PDF的下载

1.下载PDF模版

2.导入依赖

  <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.2.5</version>
            <type>pom</type>
        </dependency>

3.完整代码

package com.by.controller;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 控制器类,用于处理PDF模板填充及下载请求
 */
@RestController
public class PdfController {

    /**
     * 处理GET请求以下载填充了数据的PDF文件
     *
     * @param response HttpServletResponse对象,用于设置响应头和发送下载文件
     * @return 响应实体,包含填充好数据的PDF字节流
     * @throws IOException 如果读取或写入PDF文件时发生异常
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> test(HttpServletResponse response) throws IOException {
        // 设置响应头,指示浏览器以附件形式下载文件,并设置文件名
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String downloadFileName = System.currentTimeMillis() + ".pdf";
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);

        // 准备需要填充到PDF模板中的数据
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("name", "张三");
        dataMap.put("code", "123456");

        // 填充数据并生成带数据的PDF字节流
        byte[] pdfBytes = getPdf(dataMap);

        // 创建并返回包含填充后PDF字节流的响应实体
        return new ResponseEntity<>(pdfBytes, headers, HttpStatus.CREATED);
    }

    /**
     * 根据提供的数据填充PDF模板并返回填充后的PDF字节流
     *
     * @param dataMap 需要填充到PDF模板中的键值对数据
     * @return 填充好数据的PDF文件字节数组
     * @throws IOException 如果读取或写入PDF文件时发生异常
     */
    private byte[] getPdf(Map<String, String> dataMap) throws IOException {
        // 获取PDF模板文件路径
        String sourcePdf = ResourceUtils.getURL("classpath:").getPath() + "/templates/1.pdf";

        // 使用PDF阅读器加载模板文件
        PdfReader pdfReader = new PdfReader(new FileInputStream(sourcePdf));

        // 创建一个内存输出流用于存储填充好数据的PDF文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 创建PDF文档对象,连接读取器和输出流
        PdfDocument pdf = new PdfDocument(pdfReader, new PdfWriter(outputStream));

        // 设置默认页面大小为A4
        pdf.setDefaultPageSize(PageSize.A4);

        // 获取PDF表单域对象
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
        Map<String, PdfFormField> fields = form.getFormFields();

        // 设置字体,这里使用的是"STSong-Light"字体
        PdfFont currentFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED);

        // 遍历待填充的数据,并将其填入对应的表单域
        dataMap.forEach((key, value) -> {
            Optional<PdfFormField> formFieldOptional = Optional.ofNullable(fields.get(key));
            formFieldOptional.ifPresent(formField -> {
                // 设置字体并替换表单域的值
                formField.setFont(currentFont).setValue(value);
            });
        });

        // 锁定并合并所有表单域,使其无法再编辑
        form.flattenFields();

        // 关闭PDF文档,释放资源
        pdf.close();

        // 将填充好的PDF文件转换为字节数组并返回
        return outputStream.toByteArray();
    }
}


4.模版位置

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用com.lowagie.text.pdf插件编写的PDF报表工具类,支持动态报表创建,使用简单,附件中包含了测试类和生成的报表文件。附件中的代码需要修改相关的保存路径后可以直接使用。创建一张报表例子: private JsFileExportResult createRowReport() { String condition = "开始时间:2018-02-02 14:00:30 结束时间:2018-02-06 16:00:30"; PDFGridReport pdfReport = new PDFGridReport("报表创建测试", GridReportTestModel.getModels()); pdfReport.addCondition(condition); pdfReport.header("字段名称1", "item1", 0, 0).width(160); pdfReport.header("字段名称3", "item3", 0, 2).getCell().backgroundColor(Color.ORANGE); pdfReport.header("字段名称4", "item4", 0, 3); pdfReport.header("字段名称5", "item5", 0, 4); pdfReport.header("字段名称2", "item2", 0, 1); pdfReport.header("值", "value", 0, 5).alignH(HAlign.ALIGN_CENTER).getCell().alignH(HAlign.ALIGN_RIGHT); pdfReport.header("时间", "time", 0, 6); pdfReport.header("图片", "image", 0, 7).width(60).alignH(HAlign.ALIGN_CENTER).getCell() .alignH(HAlign.ALIGN_CENTER).alignV(VAlign.ALIGN_MIDDLE); // 横向打印 pdfReport.getPageSetting().setPrintHorizontal(); pdfReport.group("item1").childGroup("item2"); pdfReport.setCellFormat(new PDFCellValueFormat() { @Override public String format(String fieldName, String oriValue) { if ("value".equals(fieldName)) { return String.format("%.2f", Double.parseDouble(oriValue)).toString(); } else { return oriValue; } } }); JsFileExportResult fileResult = pdfReport.createReport(); return fileResult; }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值