| 1 52 package com.lowagie.text.pdf; 53 54 import java.io.IOException ; 55 import java.io.OutputStream ; 56 import java.util.HashMap ; 57 58 import com.lowagie.text.Document; 59 import com.lowagie.text.DocumentException; 60 import java.util.Arrays ; 61 62 70 71 public class PdfSmartCopy extends PdfCopy { 72 73 74 private HashMap streamMap = null; 75 76 77 public PdfSmartCopy(Document document, OutputStream os) throws DocumentException { 78 super(document, os); 79 this.streamMap = new HashMap (); 80 } 81 93 protected PdfIndirectReference copyIndirect(PRIndirectReference in) throws IOException , BadPdfFormatException { 94 PdfObject srcObj = PdfReader.getPdfObjectRelease(in); 95 ByteStore streamKey = null; 96 if (srcObj.type == PdfObject.STREAM) { 97 streamKey = new ByteStore((PRStream)srcObj); 99 PdfIndirectReference streamRef = (PdfIndirectReference) streamMap.get(streamKey); 100 if (streamRef != null) { 101 return streamRef; 102 } 103 } 104 105 PdfIndirectReference theRef; 106 RefKey key = new RefKey(in); 107 IndirectReferences iRef = (IndirectReferences) indirects.get(key); 108 if (iRef != null) { 109 theRef = iRef.getRef(); 110 if (iRef.getCopied()) { 111 return theRef; 112 } 113 } else { 114 theRef = body.getPdfIndirectReference(); 115 iRef = new IndirectReferences(theRef); 116 indirects.put(key, iRef); 117 } 118 iRef.setCopied(); 119 120 if (srcObj.type == PdfObject.STREAM) { 121 streamMap.put(streamKey, theRef); 122 } 123 124 PdfObject obj = copyObject(srcObj); 125 addToBody(obj, theRef); 126 return theRef; 127 } 128 129 static class ByteStore { 130 private byte[] b; 131 private int hash; 132 133 ByteStore(PRStream str) throws IOException { 134 byte[] streamContent = PdfReader.getStreamBytesRaw(str); 135 Object [] keys = str.getKeys().toArray(); 136 Arrays.sort(keys); 137 ByteBuffer bb = new ByteBuffer(); 138 for (int k = 0; k < keys.length; ++k) { 139 bb.append(keys[k].toString()); 140 } 141 bb.append(streamContent); 142 this.b = bb.toByteArray(); 143 } 144 145 public boolean equals(Object obj) { 146 if (!(obj instanceof ByteStore)) 147 return false; 148 if (hashCode() != obj.hashCode()) 149 return false; 150 return Arrays.equals(b, ((ByteStore)obj).b); 151 } 152 153 public int hashCode() { 154 if (hash == 0) { 155 int len = b.length; 156 for (int k = 0; k < len; ++k) { 157 hash = hash * 31 + (b[k] & 0xff); 158 } 159 } 160 return hash; 161 } 162 } 163 } | Popular Tags |