一、开通阿里云OSS对象存储服务
对象存储 OSS_云存储服务_企业数据管理_存储-阿里云阿里云对象存储 OSS 是一款海量、安全、低成本、高可靠的云存储服务,提供 99.995 % 的服务可用性和多种存储类型,适用于数据湖存储,数据迁移,企业数据管理,数据处理等多种场景,可对接多种计算分析平台,直接进行数据处理与分析,打破数据孤岛,优化存储成本,提升业务价值。https://www.aliyun.com/product/oss?spm=5176.8465980.unusable.ddetail.7df51450v1aNb1
二、创建存储空间
1、创建Bucket
2、完成创建Bucket
三、申请AccessKey
四、代码实现
1、导入依赖
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>选择你的版本</version></dependency>
2、创建对应的工具类AliOssUtil类,此代码是固定代码,直接CV即可。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;@Data
@AllArgsConstructor
//固定代码,CV直接使用
public class AliOssUtil {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;/*** 文件上传** @param bytes :传入的文件要转为byte[]* @param objectName :表示在oss中存储的文件名字。* @return*/public String upload(byte[] bytes, String objectName) {// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 创建PutObject请求。ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}//文件访问路径规则 https://BucketName.Endpoint/ObjectNameStringBuilder stringBuilder = new StringBuilder("https://");stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);return stringBuilder.toString();}
}
3、配置阿里云OSS
aliyun.oss.bucketName = scl-oss-test
aliyun.oss.endpoint = oss-cn-beijing.aliyuncs.com
aliyun.oss.accessKeyId =
aliyun.oss.accessKeySecret =
4、配置相应model类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
public class AliOssProperties {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;}
5、将工具类配置到ioc容器中,便于后续的使用。
import com.fpl.model.AliOssProperties;
import com.fpl.utils.AliOssUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OssConfiguration {@Bean@ConditionalOnMissingBeanpublic AliOssUtil getAliOssUtil(AliOssProperties aliOssProperties) {
// log.info("创建OssUtil");AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());return aliOssUtil;}
}
五、结合上传pdf使用
上篇文章有介绍pdf使用。SpringBoot整合PDF动态填充数据并下载!!!-CSDN博客文章浏览阅读106次。TextPDF(现在也称为iText 7)是一款强大的Java库,专门用于创建、填充、阅读、操纵和维护PDF文档。:iTextPDF能够从零开始创建PDF文档,也可以读取已有的PDF文件并对其中的内容进行修改,如添加、删除或更新页面内容。:可以在PDF文档中插入文本、图片、图表等内容。:支持复杂表格的创建和填充,包括单元格合并、样式设定等。:支持创建和填充交互式PDF表单,包括文本字段、复选框、列表框等,并且可以对表单域进行读写操作。:提供对PDF文档进行数字签名的支持,确保文档的安全性和完整性。https://blog.csdn.net/qq_64847107/article/details/137959658?spm=1001.2014.3001.5502
1、将pdf模板上传到阿里云
2、修改上传pdf的代码实现将pdf上传到阿里云
其实就是修改了三句代码:
package com.by.controller;import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.by.util.AliOssUtil;
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.beans.factory.annotation.Autowired;
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.File;
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 {@Autowiredprivate AliOssUtil aliOssUtil;/*** 处理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", "350ml");// 填充数据并生成带数据的PDF字节流byte[] pdfBytes = getPdf(dataMap);//上传到ossaliOssUtil.upload(pdfBytes, downloadFileName);// 创建并返回包含填充后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 {//获取阿里云OSS上传的pdf模板String fileUrl = "https://scl-oss-test.oss-cn-beijing.aliyuncs.com/1.pdf";//将文件下载后保存在E盘,返回结果为下载文件大小long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("C:/Users/admin/Desktop"));// 获取PDF模板文件路径File sourcePdf = ResourceUtils.getFile("C:/Users/admin/Desktop/1.pdf");// 使用PDF阅读器加载模板文件PdfReader pdfReader = new PdfReader(new FileInputStream(sourcePdf));// 创建一个内存输出流用于存储填充好数据的PDF文件ByteArrayOutputStream outputStream = new ByteArrayOutputStream();// 创建PDF文档对象,连接读取器和输出流PdfDocument pdf = new PdfDocument(pdfReader, new PdfWriter(outputStream));// 设置默认页面大小为A4pdf.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();}
}