springboot实现将pdf文件转成不可复制的pdf文件,并将新生成的路径返回给前端
时间: 2025-06-29 15:02:01 浏览: 13
### 实现 Spring Boot 将 PDF 文件转换为文本不可复制的 PDF 并返回新文件路径
为了实现这一功能,在 Spring Boot 中可以采用以下方案:
#### 依赖引入
首先,需要在 `pom.xml` 文件中加入必要的依赖来处理 PDF 文档。iText 是一个常用的 Java 库用于创建和操作 PDF 文件。
```xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.15</version>
</dependency>
```
#### 创建控制器和服务层逻辑
定义 RESTful API 接口接收上传的原始 PDF 文件,并调用服务层完成转换工作。
```java
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@Autowired
private IPdfService pdfService;
@PostMapping("/convert")
public ResponseEntity<String> convertPdf(@RequestParam("file") MultipartFile file) throws IOException {
String filePath = pdfService.convertToNonCopyable(file);
return ResponseEntity.ok(filePath);
}
}
```
接着编写具体的服务实现类来进行 PDF 处理。
```java
@Service
public class PdfServiceImpl implements IPdfService {
@Override
public String convertToNonCopyable(MultipartFile inputFile) throws IOException {
try (InputStream inputStream = inputFile.getInputStream()) {
// 设置输出目录
File tempDir = Files.createTempDirectory("non_copy_pdf").toFile();
Path outputPath = Paths.get(tempDir.getAbsolutePath(), UUID.randomUUID().toString() + ".pdf");
// 使用 iText 修改权限设置
PdfReader reader = new PdfReader(inputStream);
PdfWriter writer = new PdfWriter(outputPath.toString());
PdfDocument document = new PdfDocument(reader, writer);
// 关闭文本提取权限
StampingProperties stampingProps = new StampingProperties();
PdfEncryptionPermissions permissions = new PdfEncryptionPermissions()
.setModifyContents(false)
.setExtractContent(false);
SecureRandom random = new SecureRandom();
byte[] userPassword = new byte[32];
byte[] ownerPassword = new byte[32];
random.nextBytes(userPassword);
random.nextBytes(ownerPassword);
document.setEncryption(
userPassword,
ownerPassword,
permissions,
EncryptionConstants.ENCRYPTION_AES_256
);
document.close();
return outputPath.toAbsolutePath().toString();
} catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
}
```
上述代码片段展示了如何利用 iText 来读取输入流中的 PDF 文件,关闭其文本拷贝选项并将加密后的结果保存到临时位置[^1]。
最后一步是在前端接收到服务器响应后展示下载链接或直接触发浏览器自动下载行为。
```javascript
fetch('/api/pdf/convert', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(path => {
const aTag = document.createElement('a');
aTag.href = path;
aTag.download = '';
document.body.appendChild(aTag);
aTag.click();
});
```
此 JavaScript 片段说明了当客户端成功获取新的 PDF 文件路径之后怎样动态构建 `<a>` 标签并模拟点击事件以促使用户下载文件。
阅读全文
相关推荐


















