Add, Delete & Get Attachment from a PDF Document in Java Applications
Join the DZone community and get the full member experience.
Join For Free//Add attachment in a PDF document.
//open document
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf");
//setup new file to be added as attachment
com.aspose.pdf.FileSpecification fileSpecification = new com.aspose.pdf.FileSpecification("sample.txt", "Sample text file");
//add attachment to document's attachment collection
pdfDocument.getEmbeddedFiles().add(fileSpecification);
// Save updated document containing table object
pdfDocument.save("output.pdf");
//Delete all the attachments from the PDF document.
//open document
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf");
//delete all attachments
pdfDocument.getEmbeddedFiles().delete();
//save updated file
pdfDocument.save("output.pdf");
//Get an individual attachment from the PDF document.
//open document
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf");
//get particular embedded file
com.aspose.pdf.FileSpecification fileSpecification = pdfDocument.getEmbeddedFiles().get_Item(1);
//get the file properties
System.out.printf("Name: - " + fileSpecification.getName());
System.out.printf("\nDescription: - " + fileSpecification.getDescription());
System.out.printf("\nMime Type: - " + fileSpecification.getMIMEType());
// get attachment form PDF file
try {
InputStream input = fileSpecification.getContents();
File file = new File(fileSpecification.getName());
// create path for file from pdf
file.getParentFile().mkdirs();
// create and extract file from pdf
java.io.FileOutputStream output = new java.io.FileOutputStream(fileSpecification.getName(), true);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer)))
output.write(buffer, 0, n);
// close InputStream object
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
// close Document object
pdfDocument.dispose();
Opinions expressed by DZone contributors are their own.
Comments