Attach Files to PDF Documents
- 2 minutes to read
The PDF Document API enables you to embed external files inside a PDF document. Each attachment is stored as an Attachment object that defines file metadata and binary content.
Use the PdfDocument.getAttachments() method to access the collection of attachments in a document. The method returns an IAttachmentCollection object that manages Attachment instances.
IAttachmentCollection attachments = pdfDocument.getAttachments();
Add a File Attachment
Create an Attachment object and add it to the document’s attachment collection.
The following code snippet attaches a text file to a PDF document:
import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.DXPaperKind;
import java.nio.channels.*;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
try (PdfDocument pdfDocument = new PdfDocument()) {
// Add an A4-size page to the document.
pdfDocument.getPages().add(DXPaperKind.A4);
// Create an attachment.
Attachment attachment = new Attachment();
attachment.setFileName("sample.txt");
attachment.setData(Files.readAllBytes(Path.of("sample.txt")));
attachment.setMimeType("text/plain");
attachment.setDescription("Sample text file");
attachment.setRelationship(AssociatedFileRelationship.SOURCE);
// Add attachment to the document.
pdfDocument.getAttachments().add(attachment);
// Save the document.
try (WritableByteChannel channel =
FileChannel.open(Path.of("result.pdf"),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING)) {
pdfDocument.save(channel);
}
}
}
}
Attachment Settings
| Setting | Description | API |
|---|---|---|
FileName |
The name of the attached file. | getFileName(), setFileName() |
Data |
The binary content of the file. | getData(), setData() |
MimeType |
MIME type of the file (for example, text/plain, application/pdf). |
getMimeType(), setMimeType() |
Description |
The attachment description. | getDescription(), setDescription() |
CreationDate |
The date when the attachment was created. | getCreationDate(), setCreationDate() |
ModificationDate |
The date when the attachment was last modified. | getModificationDate(), setModificationDate() |
Relationship |
Specifies the role of the file in the document (for example, SOURCE). |
getRelationship(), setRelationship() |
Iterate Through Attachments
The following code snippet accesses and processes all attachments in a document:
for (Attachment attachment : pdfDocument.getAttachments()) {
System.out.println(attachment.getFileName());
System.out.println(attachment.getMimeType());
}
Remove an Attachment
The following code snippet removes an attachment from a PDF document by index or by reference:
// Remove the attached file by index.
pdfDocument.getAttachments().remove(0);
// Remove the attached file by reference.
pdfDocument.getAttachments().remove(attachment);
See Also