你可以用 「PDAnnotationFileAttachment」 嘗試。它會提供一個註釋。通過點擊註釋,您可以打開附件。
示例代碼:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.apache.pdfbox.pdmodel.graphics.color.PDGamma;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationFileAttachment;
public class FileAttach {
public static void main(String arg[]) throws IOException, COSVisitorException
{
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
// Adding attachment
String caption = "DEMO.mp4";
// PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
// final Map<String, PDComplexFileSpecification> embeddedFileMap = new HashMap<String, PDComplexFileSpecification>();
PDComplexFileSpecification fs = new PDComplexFileSpecification();
File f1 = new File("C:\\PDF\\DEMO.mp4");
FileInputStream fins1 = new FileInputStream(f1);
PDEmbeddedFile ef = new PDEmbeddedFile(doc, fins1);
ef.setSubtype("application/octet-stream");
fs.setEmbeddedFile(ef);
fs.setFile(caption);
// embeddedFileMap.put(caption, fs);
// efTree.setNames(embeddedFileMap);
// PDDocumentNameDictionary nameDir = new PDDocumentNameDictionary(doc.getDocumentCatalog());
// nameDir.setEmbeddedFiles(efTree);
// doc.getDocumentCatalog().setNames(nameDir);
int offsetX = 20;
int offsetY = 600;
//PDAnnotationLink txtLink = new PDAnnotationLink();
PDAnnotationFileAttachment txtLink = new PDAnnotationFileAttachment();
txtLink.setFile(fs);
PDGamma blueColor = new PDGamma();
blueColor.setB(1);
txtLink.setColour(blueColor);
txtLink.setAnnotationFlags(PDAnnotationFileAttachment.FLAG_LOCKED);
// Set the rectangle containing the link
PDRectangle position = new PDRectangle();
position.setLowerLeftX(offsetX);
position.setLowerLeftY(offsetY);
position.setUpperRightX(offsetX + 20);
position.setUpperRightY(offsetY + 20);
txtLink.setRectangle(position);
page.getAnnotations().add(txtLink);
doc.save("C:\\PDF\\Vishal\\aa.pdf");
doc.close();
}
}