Пример #1
0
        public virtual void CopySelfContainedObject()
        {
            ByteArrayOutputStream inputBytes        = new ByteArrayOutputStream();
            PdfDocument           prepInputDoc      = new PdfDocument(new PdfWriter(inputBytes));
            PdfDictionary         selfContainedDict = new PdfDictionary();
            PdfName randDictName = PdfName.Sound;
            PdfName randEntry1   = PdfName.R;
            PdfName randEntry2   = PdfName.S;

            selfContainedDict.Put(randEntry1, selfContainedDict);
            selfContainedDict.Put(randEntry2, selfContainedDict);
            prepInputDoc.AddNewPage().Put(randDictName, selfContainedDict.MakeIndirect(prepInputDoc));
            prepInputDoc.Close();
            PdfDocument srcDoc  = new PdfDocument(new PdfReader(new MemoryStream(inputBytes.ToArray())));
            PdfDocument destDoc = new PdfDocument(new PdfWriter(destinationFolder + "copySelfContainedObject.pdf"));

            srcDoc.CopyPagesTo(1, 1, destDoc);
            PdfDictionary destPageObj            = destDoc.GetFirstPage().GetPdfObject();
            PdfDictionary destSelfContainedDict  = destPageObj.GetAsDictionary(randDictName);
            PdfDictionary destSelfContainedDictR = destSelfContainedDict.GetAsDictionary(randEntry1);
            PdfDictionary destSelfContainedDictS = destSelfContainedDict.GetAsDictionary(randEntry2);

            NUnit.Framework.Assert.AreEqual(destSelfContainedDict.GetIndirectReference(), destSelfContainedDictR.GetIndirectReference
                                                ());
            NUnit.Framework.Assert.AreEqual(destSelfContainedDict.GetIndirectReference(), destSelfContainedDictS.GetIndirectReference
                                                ());
            destDoc.Close();
            srcDoc.Close();
        }
Пример #2
0
        public virtual void Copying3()
        {
            FileStream    fos         = new FileStream(destinationFolder + "copying3_1.pdf", FileMode.Create);
            PdfWriter     writer      = new PdfWriter(fos);
            PdfDocument   pdfDoc      = new PdfDocument(writer);
            PdfDictionary helloWorld  = ((PdfDictionary) new PdfDictionary().MakeIndirect(pdfDoc));
            PdfDictionary helloWorld1 = ((PdfDictionary) new PdfDictionary().MakeIndirect(pdfDoc));

            helloWorld.Put(new PdfName("Hello"), new PdfString("World"));
            helloWorld.Put(new PdfName("HelloWrld"), helloWorld);
            helloWorld.Put(new PdfName("HelloWrld1"), helloWorld1);
            PdfPage page = pdfDoc.AddNewPage();

            page.GetPdfObject().Put(new PdfName("HelloWorld"), helloWorld);
            page.GetPdfObject().Put(new PdfName("HelloWorldClone"), (PdfObject)helloWorld.Clone());
            pdfDoc.Close();
            PdfReader reader = new PdfReader(destinationFolder + "copying3_1.pdf");

            NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt");
            pdfDoc = new PdfDocument(reader);
            PdfDictionary dic0 = pdfDoc.GetPage(1).GetPdfObject().GetAsDictionary(new PdfName("HelloWorld"));

            NUnit.Framework.Assert.AreEqual(4, dic0.GetIndirectReference().GetObjNumber());
            NUnit.Framework.Assert.AreEqual(0, dic0.GetIndirectReference().GetGenNumber());
            PdfDictionary dic1 = pdfDoc.GetPage(1).GetPdfObject().GetAsDictionary(new PdfName("HelloWorldClone"));

            NUnit.Framework.Assert.AreEqual(8, dic1.GetIndirectReference().GetObjNumber());
            NUnit.Framework.Assert.AreEqual(0, dic1.GetIndirectReference().GetGenNumber());
            PdfString str0 = dic0.GetAsString(new PdfName("Hello"));
            PdfString str1 = dic1.GetAsString(new PdfName("Hello"));

            NUnit.Framework.Assert.AreEqual(str0.GetValue(), str1.GetValue());
            NUnit.Framework.Assert.AreEqual(str0.GetValue(), "World");
            PdfDictionary dic01 = dic0.GetAsDictionary(new PdfName("HelloWrld"));
            PdfDictionary dic11 = dic1.GetAsDictionary(new PdfName("HelloWrld"));

            NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetObjNumber(), dic11.GetIndirectReference().
                                            GetObjNumber());
            NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetGenNumber(), dic11.GetIndirectReference().
                                            GetGenNumber());
            NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetObjNumber(), 4);
            NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetGenNumber(), 0);
            PdfDictionary dic02 = dic0.GetAsDictionary(new PdfName("HelloWrld1"));
            PdfDictionary dic12 = dic1.GetAsDictionary(new PdfName("HelloWrld1"));

            NUnit.Framework.Assert.AreEqual(dic02.GetIndirectReference().GetObjNumber(), dic12.GetIndirectReference().
                                            GetObjNumber());
            NUnit.Framework.Assert.AreEqual(dic02.GetIndirectReference().GetGenNumber(), dic12.GetIndirectReference().
                                            GetGenNumber());
            NUnit.Framework.Assert.AreEqual(dic12.GetIndirectReference().GetObjNumber(), 5);
            NUnit.Framework.Assert.AreEqual(dic12.GetIndirectReference().GetGenNumber(), 0);
            reader.Close();
        }
Пример #3
0
        public virtual void GetFontWithDirectFontDictionaryTest()
        {
            PdfDictionary initialFontDict = new PdfDictionary();

            initialFontDict.Put(PdfName.Subtype, PdfName.Type3);
            initialFontDict.Put(PdfName.FontMatrix, new PdfArray(new float[] { 0.001F, 0, 0, 0.001F, 0, 0 }));
            initialFontDict.Put(PdfName.Widths, new PdfArray());
            PdfDictionary encoding = new PdfDictionary();

            initialFontDict.Put(PdfName.Encoding, encoding);
            PdfArray differences = new PdfArray();

            differences.Add(new PdfNumber(AdobeGlyphList.NameToUnicode("a")));
            differences.Add(new PdfName("a"));
            encoding.Put(PdfName.Differences, differences);
            NUnit.Framework.Assert.IsNull(initialFontDict.GetIndirectReference());
            using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
                // prevent no pages exception on close
                doc.AddNewPage();
                PdfType3Font font1 = (PdfType3Font)doc.GetFont(initialFontDict);
                NUnit.Framework.Assert.IsNotNull(font1);
                // prevent no glyphs for type3 font on close
                font1.AddGlyph('a', 0, 0, 0, 0, 0);
            }
        }
Пример #4
0
        public virtual void SmartModeObjectSelfReferencingTest()
        {
            PdfDocument   document = new PdfDocument(new PdfWriter(new MemoryStream()));
            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);
            //It is essential to serialize object with huge amount of memory
            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("\x0");
            }
            stringBytes.Append(end);
            SerializedObjectContent expected = new SerializedObjectContent(stringBytes.ToString().GetBytes(System.Text.Encoding
                                                                                                           .UTF8));

            NUnit.Framework.Assert.AreEqual(expected, serializedObject);
        }
Пример #5
0
        public virtual void FreeReferencesInObjectStream()
        {
            PdfReader     reader   = new PdfReader(sourceFolder + "styledLineArts_Redacted.pdf");
            PdfWriter     writer   = new PdfWriter(new MemoryStream());
            PdfDocument   document = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
            PdfDictionary dict     = new PdfDictionary();

            dict.MakeIndirect(document);
            NUnit.Framework.Assert.IsTrue(dict.GetIndirectReference().GetObjNumber() > 0);
        }
Пример #6
0
        public virtual void PdtIndirectReferenceLateInitializing3()
        {
            MemoryStream baos     = new MemoryStream();
            PdfWriter    writer   = new PdfWriter(baos);
            PdfDocument  document = new PdfDocument(writer);

            document.AddNewPage();
            PdfDictionary        catalog = document.GetCatalog().GetPdfObject();
            PdfIndirectReference indRef1 = document.CreateNextIndirectReference();
            PdfIndirectReference indRef2 = document.CreateNextIndirectReference();
            PdfArray             array   = new PdfArray();

            catalog.Put(new PdfName("array1"), array);
            PdfString @string = new PdfString("array string");

            array.Add(@string);
            array.Add(indRef1);
            array.Add(indRef2);
            PdfDictionary dict = new PdfDictionary();

            dict.MakeIndirect(document, indRef1);
            PdfArray  arrayClone = (PdfArray)array.Clone();
            PdfObject object0    = arrayClone.Get(0, false);
            PdfObject object1    = arrayClone.Get(1, false);
            PdfObject object2    = arrayClone.Get(2, false);

            NUnit.Framework.Assert.IsTrue(object0 is PdfString);
            NUnit.Framework.Assert.IsTrue(object1 is PdfDictionary);
            NUnit.Framework.Assert.IsTrue(object2 is PdfNull);
            PdfString string1 = (PdfString)object0;

            NUnit.Framework.Assert.IsTrue(@string != string1);
            NUnit.Framework.Assert.IsTrue(@string.GetValue().Equals(string1.GetValue()));
            PdfDictionary dict1 = (PdfDictionary)object1;

            NUnit.Framework.Assert.IsTrue(dict1.GetIndirectReference().GetObjNumber() == dict.GetIndirectReference().GetObjNumber
                                              ());
            NUnit.Framework.Assert.IsTrue(dict1.GetIndirectReference().GetGenNumber() == dict.GetIndirectReference().GetGenNumber
                                              ());
            NUnit.Framework.Assert.IsTrue(dict1 == dict);
            document.Close();
        }
        /// <summary>
        /// Creates a
        /// <see cref="MemoryLimitsAwareOutputStream"/>
        /// which will be used for decompression of the passed pdf stream.
        /// </summary>
        /// <param name="streamDictionary">the pdf stream which is going to be decompressed.</param>
        /// <returns>
        /// the
        /// <see cref="System.IO.MemoryStream"/>
        /// which will be used for decompression of the passed pdf stream
        /// </returns>
        public virtual MemoryStream EnableMemoryLimitsAwareHandler(PdfDictionary streamDictionary)
        {
            MemoryLimitsAwareOutputStream outputStream             = new MemoryLimitsAwareOutputStream();
            MemoryLimitsAwareHandler      memoryLimitsAwareHandler = null;

            if (null != streamDictionary.GetIndirectReference())
            {
                memoryLimitsAwareHandler = streamDictionary.GetIndirectReference().GetDocument().memoryLimitsAwareHandler;
            }
            else
            {
                // We do not reuse some static instance because one can process pdfs in different threads.
                memoryLimitsAwareHandler = new MemoryLimitsAwareHandler();
            }
            if (null != memoryLimitsAwareHandler && memoryLimitsAwareHandler.considerCurrentPdfStream)
            {
                outputStream.SetMaxStreamSize(memoryLimitsAwareHandler.GetMaxSizeOfSingleDecompressedPdfStream());
            }
            return(outputStream);
        }
Пример #8
0
        /// <summary>
        /// Returns the index of the first occurrence of the page in this tree
        /// specified by it's PdfDictionary, or 0 if this tree does not contain the page.
        /// </summary>
        public virtual int GetPageNumber(PdfDictionary pageDictionary)
        {
            int pageNum = pageRefs.IndexOf(pageDictionary.GetIndirectReference());

            if (pageNum >= 0)
            {
                return(pageNum + 1);
            }
            for (int i = 0; i < pageRefs.Count; i++)
            {
                if (pageRefs[i] == null)
                {
                    LoadPage(i);
                }
                if (pageRefs[i].Equals(pageDictionary.GetIndirectReference()))
                {
                    return(i + 1);
                }
            }
            return(0);
        }
Пример #9
0
 private static bool OrderBranchContainsSetElements(PdfObject arrayObj, PdfArray array, int currentIndex, ICollection
     <PdfIndirectReference> ocgs, PdfArray toOcgs, PdfDocument toDocument) {
     if (arrayObj.IsDictionary()) {
         if (ocgs.Contains(arrayObj.GetIndirectReference())) {
             return true;
         }
         else {
             if (currentIndex < (array.Size() - 1) && array.Get(currentIndex + 1).IsArray()) {
                 PdfArray nextArray = array.GetAsArray(currentIndex + 1);
                 if (!nextArray.Get(0).IsString()) {
                     bool result = iText.Kernel.Pdf.OcgPropertiesCopier.OrderBranchContainsSetElements(nextArray, array, currentIndex
                          + 1, ocgs, toOcgs, toDocument);
                     if (result && toOcgs != null && !ocgs.Contains(arrayObj.GetIndirectReference())) {
                         // Add the OCG to the OCGs array to register the OCG in document, since it is not used
                         // directly in the document, but is used as a parent for the order group. If it is not added
                         // to the OCGs array, then the OCG will be deleted at the 3rd stage of the /Order entry coping.
                         toOcgs.Add(arrayObj.CopyTo(toDocument, false));
                     }
                     return result;
                 }
             }
         }
     }
     else {
         if (arrayObj.IsArray()) {
             PdfArray arrayItem = (PdfArray)arrayObj;
             for (int i = 0; i < arrayItem.Size(); i++) {
                 PdfObject obj = arrayItem.Get(i);
                 if (iText.Kernel.Pdf.OcgPropertiesCopier.OrderBranchContainsSetElements(obj, arrayItem, i, ocgs, toOcgs, toDocument
                     )) {
                     return true;
                 }
             }
             if (!arrayItem.IsEmpty() && !arrayItem.Get(0).IsString()) {
                 if (currentIndex > 0 && array.Get(currentIndex - 1).IsDictionary()) {
                     PdfDictionary previousDict = (PdfDictionary)array.Get(currentIndex - 1);
                     return ocgs.Contains(previousDict.GetIndirectReference());
                 }
             }
         }
     }
     return false;
 }
Пример #10
0
 private static void GetUsedNonFlushedOCGsFromOcDict(PdfObject toObj, PdfObject fromObj, ICollection<PdfIndirectReference
     > fromUsedOcgs, PdfDictionary toOcProperties) {
     if (toObj != null && toObj.IsDictionary() && !toObj.IsFlushed()) {
         PdfDictionary toCurrDict = (PdfDictionary)toObj;
         PdfDictionary fromCurrDict = (PdfDictionary)fromObj;
         PdfName typeName = toCurrDict.GetAsName(PdfName.Type);
         if (PdfName.OCG.Equals(typeName) && !iText.Kernel.Pdf.OcgPropertiesCopier.OcgAlreadyInOCGs(toCurrDict.GetIndirectReference
             (), toOcProperties)) {
             fromUsedOcgs.Add(fromCurrDict.GetIndirectReference());
         }
         else {
             if (PdfName.OCMD.Equals(typeName)) {
                 PdfArray toOcgs = null;
                 PdfArray fromOcgs = null;
                 if (toCurrDict.GetAsDictionary(PdfName.OCGs) != null) {
                     toOcgs = new PdfArray();
                     toOcgs.Add(toCurrDict.GetAsDictionary(PdfName.OCGs));
                     fromOcgs = new PdfArray();
                     fromOcgs.Add(fromCurrDict.GetAsDictionary(PdfName.OCGs));
                 }
                 else {
                     if (toCurrDict.GetAsArray(PdfName.OCGs) != null) {
                         toOcgs = toCurrDict.GetAsArray(PdfName.OCGs);
                         fromOcgs = fromCurrDict.GetAsArray(PdfName.OCGs);
                     }
                 }
                 if (toOcgs != null && !toOcgs.IsFlushed()) {
                     for (int i = 0; i < toOcgs.Size(); i++) {
                         iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromOcDict(toOcgs.Get(i), fromOcgs.Get(i), fromUsedOcgs
                             , toOcProperties);
                     }
                 }
             }
         }
     }
 }
Пример #11
0
        public virtual void SmartModeSameResourcesCopyingModifyingAndFlushing_ensureObjectFresh()
        {
            String outFile = destinationFolder + "smartModeSameResourcesCopyingModifyingAndFlushing_ensureObjectFresh.pdf";
            String cmpFile = sourceFolder + "cmp_smartModeSameResourcesCopyingModifyingAndFlushing_ensureObjectFresh.pdf";

            String[]    srcFiles    = new String[] { sourceFolder + "indirectResourcesStructure.pdf", sourceFolder + "indirectResourcesStructure2.pdf" };
            PdfDocument outputDoc   = new PdfDocument(new PdfWriter(outFile, new WriterProperties().UseSmartMode()));
            int         lastPageNum = 1;
            PdfFont     font        = PdfFontFactory.CreateFont();

            foreach (String srcFile in srcFiles)
            {
                PdfDocument sourceDoc = new PdfDocument(new PdfReader(srcFile));
                for (int i = 1; i <= sourceDoc.GetNumberOfPages(); ++i)
                {
                    PdfDictionary srcRes = sourceDoc.GetPage(i).GetPdfObject().GetAsDictionary(PdfName.Resources);
                    // Ensures that objects copied to the output document are fresh,
                    // i.e. are not reused from already copied objects cache.
                    bool ensureObjectIsFresh = true;
                    // it's crucial to copy first inner objects and then the container object!
                    foreach (PdfObject v in srcRes.Values())
                    {
                        if (v.GetIndirectReference() != null)
                        {
                            // We are not interested in returned copied objects instances, they will be picked up by
                            // general copying mechanism from copied objects cache by default.
                            v.CopyTo(outputDoc, ensureObjectIsFresh);
                        }
                    }
                    if (srcRes.GetIndirectReference() != null)
                    {
                        srcRes.CopyTo(outputDoc, ensureObjectIsFresh);
                    }
                }
                sourceDoc.CopyPagesTo(1, sourceDoc.GetNumberOfPages(), outputDoc);
                sourceDoc.Close();
                int i_1;
                for (i_1 = lastPageNum; i_1 <= outputDoc.GetNumberOfPages(); ++i_1)
                {
                    PdfPage   page   = outputDoc.GetPage(i_1);
                    PdfCanvas canvas = new PdfCanvas(page);
                    canvas.BeginText().MoveText(36, 36).SetFontAndSize(font, 12).ShowText("Page " + i_1).EndText();
                }
                lastPageNum = i_1;
                outputDoc.FlushCopiedObjects(sourceDoc);
            }
            outputDoc.Close();
            PdfDocument          assertDoc       = new PdfDocument(new PdfReader(outFile));
            PdfIndirectReference page1ResFontObj = assertDoc.GetPage(1).GetPdfObject().GetAsDictionary(PdfName.Resources
                                                                                                       ).GetAsDictionary(PdfName.Font).GetIndirectReference();
            PdfIndirectReference page2ResFontObj = assertDoc.GetPage(2).GetPdfObject().GetAsDictionary(PdfName.Resources
                                                                                                       ).GetAsDictionary(PdfName.Font).GetIndirectReference();
            PdfIndirectReference page3ResFontObj = assertDoc.GetPage(3).GetPdfObject().GetAsDictionary(PdfName.Resources
                                                                                                       ).GetAsDictionary(PdfName.Font).GetIndirectReference();

            NUnit.Framework.Assert.IsFalse(page1ResFontObj.Equals(page2ResFontObj));
            NUnit.Framework.Assert.IsFalse(page1ResFontObj.Equals(page3ResFontObj));
            NUnit.Framework.Assert.IsFalse(page2ResFontObj.Equals(page3ResFontObj));
            assertDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder));
        }
Пример #12
0
        private void LoadPage(int pageNum)
        {
            PdfIndirectReference targetPage = pageRefs[pageNum];

            if (targetPage != null)
            {
                return;
            }
            //if we go here, we have to split PdfPages that contains pageNum
            int      parentIndex = FindPageParent(pageNum);
            PdfPages parent      = parents[parentIndex];
            PdfArray kids        = parent.GetKids();

            if (kids == null)
            {
                throw new PdfException(PdfException.InvalidPageStructure1).SetMessageParams(pageNum + 1);
            }
            int kidsCount = parent.GetCount();
            // we should handle separated pages, it means every PdfArray kids must contain either PdfPage or PdfPages,
            // mix of PdfPage and PdfPages not allowed.
            bool findPdfPages = false;

            // NOTE optimization? when we already found needed index
            for (int i = 0; i < kids.Size(); i++)
            {
                PdfDictionary page = kids.GetAsDictionary(i);
                if (page == null)
                {
                    // null values not allowed in pages tree.
                    throw new PdfException(PdfException.InvalidPageStructure1).SetMessageParams(pageNum + 1);
                }
                PdfObject pageKids = page.Get(PdfName.Kids);
                if (pageKids != null)
                {
                    if (pageKids.IsArray())
                    {
                        findPdfPages = true;
                    }
                    else
                    {
                        // kids must be of type array
                        throw new PdfException(PdfException.InvalidPageStructure1).SetMessageParams(pageNum + 1);
                    }
                }
            }
            if (findPdfPages)
            {
                // handle mix of PdfPage and PdfPages.
                // handle count property!
                IList <PdfPages> newParents   = new List <PdfPages>(kids.Size());
                PdfPages         lastPdfPages = null;
                for (int i = 0; i < kids.Size() && kidsCount > 0; i++)
                {
                    PdfDictionary pdfPagesObject = kids.GetAsDictionary(i);
                    if (pdfPagesObject.GetAsArray(PdfName.Kids) == null)
                    {
                        // pdfPagesObject is PdfPage
                        if (lastPdfPages == null)
                        {
                            // possible if only first kid is PdfPage
                            lastPdfPages = new PdfPages(parent.GetFrom(), document, parent);
                            kids.Set(i, lastPdfPages.GetPdfObject());
                            newParents.Add(lastPdfPages);
                        }
                        else
                        {
                            // Only remove from kids if we did not replace the entry with new PdfPages
                            kids.Remove(i);
                            i--;
                        }
                        // decrement count first so that page is not counted twice when moved to lastPdfPages
                        parent.DecrementCount();
                        lastPdfPages.AddPage(pdfPagesObject);
                        kidsCount--;
                    }
                    else
                    {
                        // pdfPagesObject is PdfPages
                        int from = lastPdfPages == null?parent.GetFrom() : lastPdfPages.GetFrom() + lastPdfPages.GetCount();

                        lastPdfPages = new PdfPages(from, kidsCount, pdfPagesObject, parent);
                        newParents.Add(lastPdfPages);
                        kidsCount -= lastPdfPages.GetCount();
                    }
                }
                parents.JRemoveAt(parentIndex);
                for (int i = newParents.Count - 1; i >= 0; i--)
                {
                    parents.Add(parentIndex, newParents[i]);
                }
                // recursive call, to load needed pageRef.
                // NOTE optimization? add to loadPage startParentIndex.
                LoadPage(pageNum);
            }
            else
            {
                int from = parent.GetFrom();
                // Possible exception in case kids.getSize() < parent.getCount().
                // In any case parent.getCount() has higher priority.
                // NOTE optimization? when we already found needed index
                for (int i = 0; i < parent.GetCount(); i++)
                {
                    PdfDictionary kid = kids.GetAsDictionary(i);
                    if (kid != null)
                    {
                        // make sure it's a dictionary
                        pageRefs[from + i] = kid.GetIndirectReference();
                    }
                }
            }
        }