| 1 22 package gnu.jpdf; 23 24 import java.io.*; 25 import java.util.*; 26 27 37 public class PDFOutput 38 { 39 42 protected OutputStream os; 43 44 51 protected ByteArrayOutputStream baos; 52 53 56 protected int offset; 57 58 61 protected Vector offsets; 62 63 66 protected PDFObject rootID; 67 68 71 protected PDFObject infoID; 72 73 78 public PDFOutput(OutputStream os) throws IOException 79 { 80 this.os = os; 81 offset = 0; 82 offsets = new Vector(); 83 baos = new ByteArrayOutputStream(); 84 85 baos.write("%PDF-1.2\n".getBytes()); 90 91 baos.write("%\342\343\317\323\n".getBytes()); 94 95 offset = baos.size(); 96 baos.writeTo(os); 97 } 98 99 105 protected void write(PDFObject ob) throws IOException 106 { 107 if(ob instanceof PDFCatalog) rootID=ob; 110 if(ob instanceof PDFInfo) infoID=ob; 111 112 offsets.addElement(new PDFXref(ob.getSerialID(),offset)); 113 baos.reset(); 114 ob.write(baos); 115 offset+=baos.size(); 116 baos.writeTo(os); 117 } 118 119 122 protected void close() throws IOException 123 { 124 os.flush(); 126 127 baos.reset(); 131 baos.write("xref\n".getBytes()); 132 133 136 int firstid = 0; int lastid = -1; Vector block = new Vector(); 142 block.addElement(new PDFXref(0,0,65535)); 144 145 for(Enumeration en = offsets.elements(); en.hasMoreElements(); ) { 146 PDFXref x = (PDFXref)en.nextElement(); 147 148 if(firstid==-1) firstid=x.id; 149 150 if(lastid>-1 && x.id != (lastid+1)) { 152 writeblock(firstid,block); 154 block.removeAllElements(); 155 firstid=-1; 156 } 157 158 block.addElement(x); 160 lastid = x.id; 161 } 162 163 if(firstid>-1) 165 writeblock(firstid,block); 166 167 baos.write("trailer\n<<\n".getBytes()); 169 170 baos.write("/Size ".getBytes()); 172 baos.write(Integer.toString(offsets.size()+1).getBytes()); 173 baos.write("\n".getBytes()); 174 175 if(rootID != null) { 177 baos.write("/Root ".getBytes()); 178 baos.write(rootID.toString().getBytes()); 179 baos.write("\n".getBytes()); 180 } else 181 throw new IOException("Root object is not present in document"); 182 183 if(infoID != null) { 185 baos.write("/Info ".getBytes()); 186 baos.write(infoID.toString().getBytes()); 187 baos.write("\n".getBytes()); 188 } 189 190 baos.write(">>\nstartxref\n".getBytes()); 192 baos.write(Integer.toString(offset).getBytes()); 193 baos.write("\n%%EOF\n".getBytes()); 194 195 baos.writeTo(os); 197 os.flush(); 198 } 199 200 206 protected void writeblock(int firstid,Vector block) throws IOException 207 { 208 baos.write(Integer.toString(firstid).getBytes()); 209 baos.write(" ".getBytes()); 210 baos.write(Integer.toString(block.size()).getBytes()); 211 baos.write("\n".getBytes()); 212 214 for(Enumeration en=block.elements(); en.hasMoreElements(); ) { 215 baos.write(en.nextElement().toString().getBytes()); 216 baos.write("\n".getBytes()); 217 } 218 } 219 } | Popular Tags |