Add PDF Attachments PDFBox

Today we will learn how to Add PDF Attachments PDFBox.
Assuming that you have a path where the resource to be added as an attachment to the PDF, simply we need to create a temporary file, where we transfer the bytes of resource to be include in our PDF.
Infact we extract InputStream from these resources and using the OutputStream we create a temp file which will later become one PDEmbeddedFile with a specific file name.

In my example I start from a Map of attachments and for each InputStream I build a PDEmbeddedFile is in turn added to a PDComplexFileSpecification map.
At the end of Map iteration we suppose to have more files, will be added to the PDF file tree (object called PDEmbeddedFilesNameTreeNode ) which is added to the PDF dictionary, easy true 🙂

public class PDFAttachments {
 
	protected final static Log logger = LogFactory.getLog(PDFAttachments.class);
 
	public static void attachments(PDDocument document, Map<String, InputStream> resourcesToAdd){
 
		final Map<String, PDComplexFileSpecification> attachmentsFileMap = new HashMap<String, PDComplexFileSpecification>();
 
		for (Map.Entry<String, InputStream> entry : resourcesToAdd.entrySet()){
 
			String filename = entry.getKey();
			File file = null;
			OutputStream outputStream = null;
			InputStream inputStream = null;
 
			try {
				inputStream = entry.getValue();
				int lastIndexOf = filename.lastIndexOf(".");
				if(lastIndexOf>-1){
					String extension = filename.substring(lastIndexOf + 1, filename.length());
					if(extension.length()>0){
 
					        file = File.createTempFile(filename, extension);
						outputStream = new FileOutputStream(file);
						byte[] buffer = new byte[8 * 1024];
					        int bytesRead;
					        while ((bytesRead = inputStream.read(buffer)) != -1) {
					    	   outputStream.write(buffer, 0, bytesRead);
					        }
 
						PDComplexFileSpecification fs = new PDComplexFileSpecification();
						FileInputStream fins1 = new FileInputStream(file);
						PDEmbeddedFile ef = new PDEmbeddedFile(document, fins1);
						fs.setEmbeddedFile(ef);
						fs.setFile(filename);
						attachmentsFileMap.put(filename, fs);
					}
				}
 
			} catch (IOException e) {
				logger.error("Error during add attachment to PDF");
			}finally{
				if(outputStream!=null){
					try {
						outputStream.close();
					} catch (IOException e) {
						logger.error("Error during close OutputStream");
					}
				}
				if(entry.getValue()!=null){
					try {
						entry.getValue().close();
					} catch (IOException e) {
						logger.error("Error during close Inputstream");
					}
				}
				if(file!=null){
					file.delete();
				}
			}
		}
 
		final PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
		efTree.setNames(attachmentsFileMap);
 
		final PDDocumentNameDictionary names = new PDDocumentNameDictionary(document.getDocumentCatalog());
		names.setEmbeddedFiles(efTree);
 
		document.getDocumentCatalog().setNames(names);
 
	}
 
}

I also quote you for even more particulars of PDFBOX that you can be added to the PDF dictionary trees of JavaScript files (PDJavascriptNameTreeNode) or name dictionary (PDDestinationNameTreeNode).

I conclude by saying that this method of add PDF attachments PDFBox covers any extension of the files to be added as an attachment without worrying about managing the extensions as we take advantage of the intermediate step provided by the temporary Java files, which I recommend removing for take up space unnecessarily on your workspaces 🙂

Add PDF Attachments PDFBox ultima modidfica: 2018-01-28T18:18:57+01:00 da Gianluca Di Vincenzo