SmartModePdfObjectsSerializer implements Serializable { public SerializedObjectContent serializeObject(PdfObject obj) { if (!obj.isStream() && !obj.isDictionary()) { return null; } PdfIndirectReference indRef = obj.getIndirectReference(); assert indRef != null; Map<PdfIndirectReference, byte[]> serializedCache = indRef.getDocument().serializedObjectsCache; byte[] content = serializedCache.get(indRef); if (content == null) { ByteBuffer bb = new ByteBuffer(); int level = 100; try { serObject(obj, bb, level, serializedCache); } catch (SelfReferenceException e) { return null; } content = bb.toByteArray(); } return new SerializedObjectContent(content); } SmartModePdfObjectsSerializer(); void saveSerializedObject(SerializedObjectContent serializedContent, PdfIndirectReference objectReference); PdfIndirectReference getSavedSerializedObject(SerializedObjectContent serializedContent); SerializedObjectContent serializeObject(PdfObject obj);  }
@Test public void smartModeObjectSelfReferencingTest() { PdfDocument document = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); PdfDictionary dict1 = new PdfDictionary(); dict1.makeIndirect(document); PdfDictionary dict2 = new PdfDictionary(); dict2.makeIndirect(document); PdfArray array = new PdfArray(); array.makeIndirect(document); array.add(new PdfString(new byte[10000])); array.add(new PdfDictionary(dict2)); dict1.put(new PdfName("FirstDict"), array.getIndirectReference()); dict2.put(new PdfName("SecondDict"), dict1.getIndirectReference()); SmartModePdfObjectsSerializer serializer = new SmartModePdfObjectsSerializer(); SerializedObjectContent serializedObject = serializer.serializeObject(dict1); StringBuilder stringBytes = new StringBuilder().append("$D$N/FirstDict$A$S"); String end = "$D$\\D$\\A$\\D"; for (int i = 0; i < 10000; i++) { stringBytes.append("\0"); } stringBytes.append(end); SerializedObjectContent expected = new SerializedObjectContent( stringBytes.toString().getBytes(StandardCharsets.UTF_8)); Assert.assertEquals(expected, serializedObject); }