java实现pdf预览和下载

1、引入依赖

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

        <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.19</version>
        </dependency>

2、代码:

		PdfReader reader = null;
		ByteArrayOutputStream bos = null;
		PdfStamper stamper = null;
		try {
			Resource resource = resourceLoader.getResource("classpath:盖章证明模板.pdf");
			reader = new PdfReader(resource.getInputStream());
			bos = new ByteArrayOutputStream();
			stamper = new PdfStamper(reader, bos);
			//这个form就是pdf里面的表单key就是pdf的键 value 就是往里面要放的值
			BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			AcroFields form = stamper.getAcroFields();
			Set<Map.Entry<String, String>> entries = map.entrySet();
			for (Map.Entry<String, String> entry : entries) {
				form.setFieldProperty(entry.getKey(), "textfont", bf, null);
				form.setField(entry.getKey(), entry.getValue());
			}
			//true代表生成的PDF文件不可编辑
			stamper.setFormFlattening(true);
			stamper.close();
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
			String timeString = formatter.format(LocalDateTime.now());
			String fileName = "涉敏载体集中销毁证明" + timeString +".pdf";
			response.reset();
			response.setContentType("application/pdf;charset=UTF-8");
			response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			OutputStream out = response.getOutputStream();

			//加载pdf
			PDDocument document = PDDocument.load(bos.toByteArray());
			//获得文档属性对象
			PDDocumentInformation info = document.getDocumentInformation();
			//修改标题属性  这个标题会被展示
			info.setTitle(fileName);
			document.setDocumentInformation(info);
			//修改完直接输出到响应体中
			document.save(out);
			document.close();
			out.close();
		} catch (Exception e) {
			log.error("pdf预览发生错误:{}", e.getMessage());
		}
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值