<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.2.4</version>
</dependency>
嵌入视频为mp4
public static void extractEmbeddedVideos(String pdfPath) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdfPath));
int videoCount = 0;
// 遍历PDF中的每一页
for (int pageNum = 1; pageNum <= pdfDoc.getNumberOfPages(); pageNum++) {
PdfPage page = pdfDoc.getPage(pageNum);
PdfArray annotations = page.getPdfObject().getAsArray(PdfName.Annots);
for (int i = 0; i < annotations.size(); i++) {
PdfDictionary annotDict = annotations.getAsDictionary(i);
PdfAnnotation annot = PdfAnnotation.makeAnnotation(annotDict);
if (PdfName.RichMedia.equals(annot.getSubtype())) {
videoCount++;
PdfDictionary richMediaContent = annotDict.getAsDictionary(new PdfName("RichMediaContent"));
if (richMediaContent != null) {
PdfDictionary assets = richMediaContent.getAsDictionary(new PdfName("Assets"));
if (assets != null) {
PdfArray names = assets.getAsArray(PdfName.Names);
for (int j = 0; j < names.size(); j += 2) {
PdfDictionary fileDict = names.getAsDictionary(j+1);
String name = "F:\\" + fileDict.getAsString(PdfName.UF);
if (name.endsWith(".mp4")) {
PdfDictionary efDict = fileDict.getAsDictionary(PdfName.EF);
if (efDict != null) {
byte[] videoData = efDict.getAsStream(PdfName.F).getBytes(); // 读取字节流
FileUtil.writeBytes(videoData,name);
videoCount++;
}
}
}
}
}
}
}
}
pdfDoc.close();
if (videoCount == 0) {
System.out.println("未找到嵌入的视频文件。");
}
}