Saturday, June 29, 2013

Add, Delete & Get Attachment Of a PDF


This Java code shows Addition, Deletion & Saving Attachment in a PDF Document using Aspose.Pdf for Java. In order to add attachment in a PDF document, you need to create a FileSpecification object with the file, which needs to be added, and the file description.

Attachment Addition in PDF 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 attachments from a PDF

com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf");
pdfDocument.getEmbeddedFiles().delete();
pdfDocument.save("output.pdf");

Get an individual attachment from the PD

com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf");
com.aspose.pdf.FileSpecification fileSpecification = pdfDocument.getEmbeddedFiles().get_Item(1);
System.out.printf("Name: - " + fileSpecification.getName());
System.out.printf("\nDescription: - " + fileSpecification.getDescription());
System.out.printf("\nMime Type: - " + fileSpecification.getMIMEType());
try {
    InputStream input = fileSpecification.getContents();
    File file = new File(fileSpecification.getName());
    file.getParentFile().mkdirs();
    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);
    input.close();
    output.close();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.dispose();

Overview: Aspose.Pdf for Java
Aspose.Pdf is a Java PDF component to create PDF documents without using Adobe Acrobat. It supports Floating box, PDF form field, PDF attachments, security, Foot note & end note, Multiple columns document, Table of Contents, List of Tables, Nested tables, Rich text format, images, hyperlinks, JavaScript, annotation, bookmarks, headers, footers and many more. Now you can create PDF by API, XML and XSL-FO files. It also enables you to converting HTML, XSL-FO and Excel files into PDF.