1 31 package org.pdfbox.examples.pdmodel; 32 33 import java.io.ByteArrayInputStream ; 34 import java.io.IOException ; 35 import java.util.GregorianCalendar ; 36 import java.util.HashMap ; 37 import java.util.Map ; 38 39 import org.pdfbox.exceptions.COSVisitorException; 40 41 import org.pdfbox.pdmodel.PDDocument; 42 import org.pdfbox.pdmodel.PDDocumentNameDictionary; 43 import org.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode; 44 import org.pdfbox.pdmodel.PDPage; 45 46 import org.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification; 47 import org.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile; 48 import org.pdfbox.pdmodel.edit.PDPageContentStream; 49 50 import org.pdfbox.pdmodel.font.PDFont; 51 import org.pdfbox.pdmodel.font.PDType1Font; 52 53 54 60 public class EmbeddedFiles 61 { 62 65 public EmbeddedFiles() 66 { 67 super(); 68 } 69 70 78 public void doIt( String file) throws IOException , COSVisitorException 79 { 80 PDDocument doc = null; 82 try 83 { 84 doc = new PDDocument(); 85 86 PDPage page = new PDPage(); 87 doc.addPage( page ); 88 PDFont font = PDType1Font.HELVETICA_BOLD; 89 90 PDPageContentStream contentStream = new PDPageContentStream(doc, page); 91 contentStream.beginText(); 92 contentStream.setFont( font, 12 ); 93 contentStream.moveTextPositionByAmount( 100, 700 ); 94 contentStream.drawString( "Go to Document->File Attachments to View Embedded Files" ); 95 contentStream.endText(); 96 contentStream.close(); 97 98 PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode(); 100 101 102 PDComplexFileSpecification fs = new PDComplexFileSpecification(); 104 fs.setFile( "Test.txt" ); 105 byte[] data = "This is the contents of the embedded file".getBytes(); 107 ByteArrayInputStream fakeFile = 108 new ByteArrayInputStream ( data ); 109 PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile ); 110 ef.setSubtype( "test/plain" ); 112 ef.setSize( data.length ); 113 ef.setCreationDate( new GregorianCalendar () ); 114 fs.setEmbeddedFile( ef ); 115 116 Map efMap = new HashMap (); 118 efMap.put( "My first attachment", fs ); 119 efTree.setNames( efMap ); 120 PDDocumentNameDictionary names = new PDDocumentNameDictionary( doc.getDocumentCatalog() ); 121 names.setEmbeddedFiles( efTree ); 122 doc.getDocumentCatalog().setNames( names ); 123 124 125 doc.save( file ); 126 } 127 finally 128 { 129 if( doc != null ) 130 { 131 doc.close(); 132 } 133 } 134 } 135 136 143 public static void main(String [] args) 144 { 145 EmbeddedFiles app = new EmbeddedFiles(); 146 try 147 { 148 if( args.length != 1 ) 149 { 150 app.usage(); 151 } 152 else 153 { 154 app.doIt( args[0] ); 155 } 156 } 157 catch (Exception e) 158 { 159 e.printStackTrace(); 160 } 161 } 162 163 166 private void usage() 167 { 168 System.err.println( "usage: " + this.getClass().getName() + " <output-file>" ); 169 } 170 } | Popular Tags |