在很多专业或学术场景中,PDF 文档常常需要附带额外的文件,例如 Excel 表格、PPT 演示或者参考资料。能够在 PDF 中管理附件,有助于文档的组织、共享,也方便接收者快速访问相关内容。
本文将介绍 四种在 Java 中添加和删除 PDF 附件的方法,包括直接附件和注释附件两种类型:
这些示例使用 Spire.PDF for Java,它提供了加载 PDF、添加附件、管理注释以及保存修改等功能。你可以下载 JAR 包并引入项目,也可以通过 Maven 添加依赖:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>12.4.4</version>
</dependency>
</dependencies>添加到项目后,就可以在 Java 中对 PDF 附件进行操作。
最简单的方式是将文件直接作为 普通附件 附加到 PDF 中,这种附件会显示在 PDF 的附件面板中。例如,将 Excel 文件添加到报告中:
import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachment;
public class AttachFilesToPdf {
public static void main(String[] args) {
// 创建 PDF 文档对象
PdfDocument doc = new PdfDocument();
// 加载已有 PDF 文件
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");
// 创建附件对象
PdfAttachment attachment = new PdfAttachment("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
// 添加附件到 PDF
doc.getAttachments().add(attachment);
// 保存更新后的 PDF
doc.saveToFile("Attachment.pdf");
// 关闭文档
doc.close();
}
}说明:普通附件会在附件面板中显示,可直接打开,适用于附加数据文件或参考资料。
对于需要提示用户的场景,可以通过 注释附件 添加文件,这样可以在页面上显示提示文字,引导用户点击打开附件。例如,在 PDF 中显示 “Here is the report:” 并附加 PPT 文件:
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.PdfDocument;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.EnumSet;
public class AnnotationAttachment {
public static void main(String[] args) throws IOException {
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");
// 获取第一页
PdfPageBase page = doc.getPages().get(0);
// 绘制提示文字
String label = "请查看附件报告:";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("微软雅黑", Font.PLAIN, 13));
double x = 35;
double y = page.getActualSize().getHeight() - 220;
page.getCanvas().drawString(label, font, PdfBrushes.getRed(), x, y);
// 将外部文件转换为字节数组
String filePath = "C:\\Users\\Administrator\\Desktop\\Report.pptx";
byte[] data = toByteArray(filePath);
// 根据文字长度计算注释位置
Dimension2D size = font.measureString(label);
Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 5), (float) y, 10, 15);
// 创建附件注释
PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
annotation.setFlags(EnumSet.of(PdfAnnotationFlags.Default));
annotation.setIcon(PdfAttachmentIcon.Graph);
annotation.setText("点击此处打开附件");
// 添加注释到页面
page.getAnnotationsWidget().add(annotation);
// 保存文档
doc.saveToFile("Attachments.pdf");
doc.close();
}
// 将文件转换为字节数组
public static byte[] toByteArray(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("文件过大...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
if (offset != buffer.length) {
throw new IOException("无法完整读取文件 " + file.getName());
}
fi.close();
return buffer;
}
}说明:注释附件可以在页面上提供可点击提示,更适合需要交互提示的文档,例如报告或展示材料。
如果 PDF 中的附件已经不再需要,可以通过附件集合删除:
import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;
public class RemoveAttachments {
public static void main(String[] args) {
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
// 获取普通附件集合(不包含注释附件)
PdfAttachmentCollection attachments = doc.getAttachments();
// 删除所有附件
attachments.clear();
// 或者删除指定附件
// attachments.removeAt(0);
// 保存更新后的 PDF
doc.saveToFile("output/DeleteAttachments.pdf");
doc.close();
}
}说明:只会删除普通附件,不影响注释附件。
如果 PDF 中的附件是通过 注释方式添加 的,需要遍历页面注释并删除:
import com.spire.pdf.PdfDocument;
import com.spire.pdf.annotations.PdfAnnotation;
import com.spire.pdf.annotations.PdfAnnotationCollection;
import com.spire.pdf.annotations.PdfAttachmentAnnotationWidget;
public class RemoveAnnotationAttachments {
public static void main(String[] args) {
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
// 遍历每一页
for (int i = 0; i < doc.getPages().getCount(); i++) {
PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget();
// 遍历注释并删除附件注释
for (Object annotation : annotationCollection) {
if (annotation instanceof PdfAttachmentAnnotationWidget) {
annotationCollection.remove((PdfAnnotation) annotation);
}
}
}
// 保存文档
doc.saveToFile("output/DeleteAnnotationAttachments.pdf");
doc.close();
}
}说明:该方法只会删除注释附件,普通附件不会受到影响。
通过这四种方法,我们可以灵活地在 PDF 中管理附件:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。