Beispiel #1
0
 /// <summary>PDF 2.0.</summary>
 /// <remarks>
 /// PDF 2.0. Sets an array of names of Viewer preference settings that
 /// shall be enforced by PDF processors and that shall not be overridden by
 /// subsequent selections in the application user interface
 /// </remarks>
 /// <param name="enforce">array of names specifying settings to enforce in the PDF processors</param>
 /// <returns>
 /// this
 /// <see cref="PdfViewerPreferences"/>
 /// instance
 /// </returns>
 public virtual iText.Kernel.Pdf.PdfViewerPreferences SetEnforce(PdfArray enforce)
 {
     for (int i = 0; i < enforce.Size(); i++)
     {
         PdfName curEnforce = enforce.GetAsName(i);
         if (curEnforce == null)
         {
             throw new ArgumentException("Enforce array shall contain PdfName entries");
         }
         else
         {
             if (PdfName.PrintScaling.Equals(curEnforce))
             {
                 // This name may appear in the Enforce array only if the corresponding entry in
                 // the viewer preferences dictionary specifies a valid value other than AppDefault
                 PdfName curPrintScaling = GetPdfObject().GetAsName(PdfName.PrintScaling);
                 if (curPrintScaling == null || PdfName.AppDefault.Equals(curPrintScaling))
                 {
                     throw new PdfException(PdfException.PrintScalingEnforceEntryInvalid);
                 }
             }
         }
     }
     return(Put(PdfName.Enforce, enforce));
 }
Beispiel #2
0
        public virtual void TestContains()
        {
            PdfDocument doc   = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
            PdfArray    array = new PdfArray();

            array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
            array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
            array.Add(new PdfNumber(3).MakeIndirect(doc));
            array.Add(new PdfNumber(4).MakeIndirect(doc));
            array.Add(new PdfNumber(5));
            array.Add(new PdfNumber(6));
            PdfArray array2 = new PdfArray();

            array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
            array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
            array2.Add(new PdfNumber(3).MakeIndirect(doc));
            array2.Add(new PdfNumber(4).MakeIndirect(doc));
            array2.Add(new PdfNumber(5));
            array2.Add(new PdfNumber(6));
            foreach (PdfObject obj in array2)
            {
                NUnit.Framework.Assert.IsTrue(array.Contains(obj));
            }
            for (int i = 0; i < array2.Size(); i++)
            {
                NUnit.Framework.Assert.IsTrue(array.Contains(array2.Get(i)));
            }
        }
Beispiel #3
0
 private void MarkArrayContentToFlush(PdfArray array)
 {
     for (int i = 0; i < array.Size(); i++)
     {
         MarkObjectToFlush(array.Get(i, false));
     }
 }
Beispiel #4
0
        public virtual void TestRemove2()
        {
            PdfDocument doc   = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
            PdfArray    array = new PdfArray();

            array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
            array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
            array.Add(new PdfNumber(3).MakeIndirect(doc));
            array.Add(new PdfNumber(4).MakeIndirect(doc));
            array.Add(new PdfNumber(5));
            array.Add(new PdfNumber(6));
            PdfArray array2 = new PdfArray();

            array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
            array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
            array2.Add(new PdfNumber(3).MakeIndirect(doc));
            array2.Add(new PdfNumber(4).MakeIndirect(doc));
            array2.Add(new PdfNumber(5));
            array2.Add(new PdfNumber(6));
            for (int i = 0; i < array2.Size(); i++)
            {
                array.Remove(array2.Get(i));
            }
            NUnit.Framework.Assert.AreEqual(0, array.Size());
        }
Beispiel #5
0
        public virtual void TestRemove()
        {
            PdfDocument doc   = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
            PdfArray    array = new PdfArray();

            array.Add(((PdfNumber) new PdfNumber(1).MakeIndirect(doc)).GetIndirectReference());
            array.Add(((PdfNumber) new PdfNumber(2).MakeIndirect(doc)).GetIndirectReference());
            array.Add(((PdfNumber) new PdfNumber(3).MakeIndirect(doc)));
            array.Add(((PdfNumber) new PdfNumber(4).MakeIndirect(doc)));
            array.Add(new PdfNumber(5));
            array.Add(new PdfNumber(6));
            PdfArray array2 = new PdfArray();

            array2.Add(((PdfNumber) new PdfNumber(1).MakeIndirect(doc)).GetIndirectReference());
            array2.Add(((PdfNumber) new PdfNumber(2).MakeIndirect(doc)).GetIndirectReference());
            array2.Add(((PdfNumber) new PdfNumber(3).MakeIndirect(doc)));
            array2.Add(((PdfNumber) new PdfNumber(4).MakeIndirect(doc)));
            array2.Add(new PdfNumber(5));
            array2.Add(new PdfNumber(6));
            foreach (PdfObject obj in array2)
            {
                array.Remove(obj);
            }
            NUnit.Framework.Assert.AreEqual(0, array.Size());
        }
 private void ArrayFlushIfModified(PdfArray contentsArr)
 {
     for (int i = 0; i < contentsArr.Size(); ++i)
     {
         PdfObject c = contentsArr.Get(i, false);
         FlushIfModified(c);
     }
 }
Beispiel #7
0
        public virtual void ReadFreeRefReusingInIncrementTest()
        {
            PdfDocument document = new PdfDocument(new PdfReader(sourceFolder + "readFreeRefReusingInIncrement.pdf"));
            PdfArray    array    = (PdfArray)document.GetCatalog().GetPdfObject().Get(new PdfName("CustomKey"));

            NUnit.Framework.Assert.IsTrue(array is PdfArray);
            NUnit.Framework.Assert.AreEqual(0, array.Size());
        }
Beispiel #8
0
        public virtual int GetAnnotsSize()
        {
            PdfArray annots = GetAnnots(false);

            if (annots == null)
            {
                return(0);
            }
            return(annots.Size());
        }
Beispiel #9
0
        private PdfString IterateItems(PdfDictionary dictionary, IDictionary <String, PdfObject> items, PdfString leftOver
                                       )
        {
            PdfArray names = dictionary.GetAsArray(PdfName.Names);

            if (names != null)
            {
                for (int k = 0; k < names.Size(); k++)
                {
                    PdfString name;
                    if (leftOver == null)
                    {
                        name = names.GetAsString(k++);
                    }
                    else
                    {
                        name     = leftOver;
                        leftOver = null;
                    }
                    if (k < names.Size())
                    {
                        items.Put(name.ToUnicodeString(), names.Get(k));
                    }
                    else
                    {
                        return(name);
                    }
                }
            }
            else
            {
                if ((names = dictionary.GetAsArray(PdfName.Kids)) != null)
                {
                    for (int k = 0; k < names.Size(); k++)
                    {
                        PdfDictionary kid = names.GetAsDictionary(k);
                        leftOver = IterateItems(kid, items, leftOver);
                    }
                }
            }
            return(null);
        }
Beispiel #10
0
        private PdfNumber IterateItems(PdfDictionary dictionary, PdfNumber leftOver)
        {
            PdfArray nums = dictionary.GetAsArray(PdfName.Nums);

            if (nums != null)
            {
                for (int k = 0; k < nums.Size(); k++)
                {
                    PdfNumber number;
                    if (leftOver == null)
                    {
                        number = nums.GetAsNumber(k++);
                    }
                    else
                    {
                        number   = leftOver;
                        leftOver = null;
                    }
                    if (k < nums.Size())
                    {
                        items.Put(number.IntValue(), nums.Get(k));
                    }
                    else
                    {
                        return(number);
                    }
                }
            }
            else
            {
                if ((nums = dictionary.GetAsArray(PdfName.Kids)) != null)
                {
                    for (int k = 0; k < nums.Size(); k++)
                    {
                        PdfDictionary kid = nums.GetAsDictionary(k);
                        leftOver = IterateItems(kid, leftOver);
                    }
                }
            }
            return(null);
        }
Beispiel #11
0
 private void SerArray(PdfArray array, int level, ByteBufferOutputStream bb)
 {
     bb.Append("$A");
     if (level <= 0)
     {
         return;
     }
     for (int k = 0; k < array.Size(); ++k)
     {
         SerObject(array.Get(k, false), level, bb);
     }
 }
Beispiel #12
0
        private static int GetAmountOfReadPages(PdfArray pageIndRefArray)
        {
            int amountOfLoadedPages = 0;

            for (int i = 0; i < pageIndRefArray.Size(); i++)
            {
                if (((PdfIndirectReference)pageIndRefArray.Get(i, false)).refersTo != null)
                {
                    amountOfLoadedPages++;
                }
            }
            return(amountOfLoadedPages);
        }
Beispiel #13
0
 private void Write(PdfArray pdfArray)
 {
     WriteByte('[');
     for (int i = 0; i < pdfArray.Size(); i++)
     {
         PdfObject            value = pdfArray.Get(i, false);
         PdfIndirectReference indirectReference;
         if ((indirectReference = value.GetIndirectReference()) != null)
         {
             Write(indirectReference);
         }
         else
         {
             Write(value);
         }
         if (i < pdfArray.Size() - 1)
         {
             WriteSpace();
         }
     }
     WriteByte(']');
 }
 private void SerArray(PdfArray array, ByteBuffer bb, int level, IDictionary <PdfIndirectReference, byte[]>
                       serializedCache)
 {
     bb.Append("$A");
     if (level <= 0)
     {
         return;
     }
     for (int k = 0; k < array.Size(); ++k)
     {
         SerObject(array.Get(k, false), bb, level, serializedCache);
     }
     bb.Append("$\\A");
 }
Beispiel #15
0
        /// <summary>
        /// Performs a check if the
        /// <see cref="PdfStream"/>
        /// with provided setup of the filters requires
        /// memory limits awareness during decompression.
        /// </summary>
        /// <param name="filters">
        /// is an
        /// <see cref="PdfArray"/>
        /// of names of filters
        /// </param>
        /// <returns>true if PDF stream is suspicious and false otherwise</returns>
        public virtual bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters)
        {
            HashSet <PdfName> filterSet = new HashSet <PdfName>();

            for (int index = 0; index < filters.Size(); index++)
            {
                PdfName filterName = filters.GetAsName(index);
                if (!filterSet.Add(filterName))
                {
                    return(true);
                }
            }
            return(false);
        }
        public virtual void RemovePageWithFormFieldsTest()
        {
            String      filename = sourceFolder + "docWithFields.pdf";
            PdfDocument pdfDoc   = new PdfDocument(new PdfReader(filename));

            pdfDoc.RemovePage(1);
            PdfArray fields = pdfDoc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.AcroForm).GetAsArray(PdfName.
                                                                                                              Fields);
            PdfDictionary field = (PdfDictionary)fields.Get(0);
            PdfDictionary kid   = (PdfDictionary)field.GetAsArray(PdfName.Kids).Get(0);

            NUnit.Framework.Assert.AreEqual(6, kid.KeySet().Count);
            NUnit.Framework.Assert.AreEqual(3, fields.Size());
        }
Beispiel #17
0
        public virtual IList <PdfAnnotation> GetAnnotations()
        {
            IList <PdfAnnotation> annotations = new List <PdfAnnotation>();
            PdfArray annots = GetPdfObject().GetAsArray(PdfName.Annots);

            if (annots != null)
            {
                for (int i = 0; i < annots.Size(); i++)
                {
                    PdfDictionary annot = annots.GetAsDictionary(i);
                    annotations.Add(PdfAnnotation.MakeAnnotation(annot).SetPage(this));
                }
            }
            return(annotations);
        }
Beispiel #18
0
        public virtual void PdfNumberInPageContentArrayTest()
        {
            String      src    = sourceFolder + "pdfNumberInPageContentArray.pdf";
            String      dest   = destinationFolder + "pdfNumberInPageContentArray_saved.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));

            pdfDoc.Close();
            // test is mainly to ensure document is successfully opened-and-closed without exceptions
            pdfDoc = new PdfDocument(new PdfReader(dest));
            PdfObject pageDictWithInvalidContents = pdfDoc.GetPdfObject(10);
            PdfArray  invalidContentsArray        = ((PdfDictionary)pageDictWithInvalidContents).GetAsArray(PdfName.Contents);

            NUnit.Framework.Assert.AreEqual(5, invalidContentsArray.Size());
            NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(0).IsStream());
            NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(1).IsStream());
            NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(2).IsStream());
            NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(3).IsStream());
            NUnit.Framework.Assert.IsTrue(invalidContentsArray.Get(4).IsStream());
        }
Beispiel #19
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;
 }
Beispiel #20
0
        public virtual void TestValuesIndirectRemove()
        {
            PdfDocument doc   = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
            PdfArray    array = new PdfArray();

            array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
            array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
            array.Add(new PdfNumber(3).MakeIndirect(doc));
            array.Add(new PdfNumber(4).MakeIndirect(doc));
            array.Add(new PdfNumber(5));
            array.Add(new PdfNumber(6));
            array.Remove(array.Get(0, false));
            array.Remove(array.Get(0, false));
            array.Remove(array.Get(0).GetIndirectReference());
            array.Remove(array.Get(0).GetIndirectReference());
            array.Remove(array.Get(0));
            array.Remove(array.Get(0));
            NUnit.Framework.Assert.AreEqual(0, array.Size());
        }
Beispiel #21
0
        public virtual Rectangle GetPageSize()
        {
            PdfArray box = GetPdfObject().GetAsArray(PdfName.MediaBox);

            if (box == null || box.Size() != 4)
            {
                throw new ArgumentException("MediaBox");
            }
            PdfNumber llx = box.GetAsNumber(0);
            PdfNumber lly = box.GetAsNumber(1);
            PdfNumber urx = box.GetAsNumber(2);
            PdfNumber ury = box.GetAsNumber(3);

            if (llx == null || lly == null || urx == null || ury == null)
            {
                throw new ArgumentException("MediaBox");
            }
            return(new Rectangle(Math.Min(llx.FloatValue(), urx.FloatValue()), Math.Min(lly.FloatValue(), ury.FloatValue
                                                                                            ()), Math.Abs(urx.FloatValue() - llx.FloatValue()), Math.Abs(ury.FloatValue() - lly.FloatValue())));
        }
Beispiel #22
0
        private bool IsEqualSameNameDestExist(IDictionary <PdfPage, PdfPage> page2page, PdfDocument toDocument, String
                                              srcDestName, PdfArray srcDestArray, PdfPage oldPage)
        {
            PdfArray sameNameDest = (PdfArray)toDocument.GetCatalog().GetNameTree(PdfName.Dests).GetNames().Get(srcDestName
                                                                                                                );
            bool equalSameNameDestExists = false;

            if (sameNameDest != null && sameNameDest.GetAsDictionary(0) != null)
            {
                PdfIndirectReference existingDestPageRef = sameNameDest.GetAsDictionary(0).GetIndirectReference();
                PdfIndirectReference newDestPageRef      = page2page.Get(oldPage).GetPdfObject().GetIndirectReference();
                if (equalSameNameDestExists = existingDestPageRef.Equals(newDestPageRef) && sameNameDest.Size() == srcDestArray
                                              .Size())
                {
                    for (int i = 1; i < sameNameDest.Size(); ++i)
                    {
                        equalSameNameDestExists = equalSameNameDestExists && sameNameDest.Get(i).Equals(srcDestArray.Get(i));
                    }
                }
            }
            return(equalSameNameDestExists);
        }
Beispiel #23
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);
                // null values not allowed in pages tree.
                if (page == null)
                {
                    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 (document.GetReader().IsMemorySavingMode() && !findPdfPages && parent.GetFrom() + i != pageNum)
                {
                    page.Release();
                }
            }
            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++)
                {
                    /*
                     * We don't release pdfPagesObject in the end of each loop because we enter this for-cycle only when parent has PdfPages kids.
                     * If all of the kids are PdfPages, then there's nothing to release, because we don't release PdfPages at this point.
                     * If there are kids that are instances of PdfPage, then there's no sense in releasing them:
                     * in this case ParentTreeStructure is being rebuilt by inserting an intermediate PdfPages between the parent and a PdfPage,
                     * thus modifying the page object by resetting its parent, thus making it impossible to release the object.
                     */
                    PdfDictionary pdfPagesObject = kids.GetAsDictionary(i);
                    if (pdfPagesObject.GetAsArray(PdfName.Kids) == null)
                    {
                        // pdfPagesObject is PdfPage
                        // possible if only first kid is PdfPage
                        if (lastPdfPages == null)
                        {
                            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++)
                {
                    PdfObject kid = kids.Get(i, false);
                    if (kid is PdfIndirectReference)
                    {
                        pageRefs[from + i] = (PdfIndirectReference)kid;
                    }
                    else
                    {
                        pageRefs[from + i] = kid.GetIndirectReference();
                    }
                }
            }
        }
Beispiel #24
0
 private static void CopyDArrayField(PdfName fieldToCopy, ICollection<PdfIndirectReference> fromOcgsToCopy, 
     PdfDictionary fromDict, PdfDictionary toDict, PdfDocument toDocument) {
     if (fromDict.GetAsArray(fieldToCopy) == null) {
         return;
     }
     PdfArray fromArray = fromDict.GetAsArray(fieldToCopy);
     if (toDict.GetAsArray(fieldToCopy) == null) {
         toDict.Put(fieldToCopy, new PdfArray());
     }
     PdfArray toArray = toDict.GetAsArray(fieldToCopy);
     ICollection<PdfIndirectReference> toOcgsToCopy = new HashSet<PdfIndirectReference>();
     foreach (PdfIndirectReference fromRef in fromOcgsToCopy) {
         toOcgsToCopy.Add(fromRef.GetRefersTo().CopyTo(toDocument, false).GetIndirectReference());
     }
     if (PdfName.Order.Equals(fieldToCopy)) {
         // Stage 1: delete all Order the entire branches from the output document in which the copied OCGs were
         IList<int> removeIndex = new List<int>();
         for (int i = 0; i < toArray.Size(); i++) {
             PdfObject toOrderItem = toArray.Get(i);
             if (iText.Kernel.Pdf.OcgPropertiesCopier.OrderBranchContainsSetElements(toOrderItem, toArray, i, toOcgsToCopy
                 , null, null)) {
                 removeIndex.Add(i);
             }
         }
         for (int i = removeIndex.Count - 1; i > -1; i--) {
             toArray.Remove(removeIndex[i]);
         }
         PdfArray toOcgs = toDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.OCProperties).GetAsArray(
             PdfName.OCGs);
         // Stage 2: copy all the Order the entire branches in which the copied OСGs were
         for (int i = 0; i < fromArray.Size(); i++) {
             PdfObject fromOrderItem = fromArray.Get(i);
             if (iText.Kernel.Pdf.OcgPropertiesCopier.OrderBranchContainsSetElements(fromOrderItem, fromArray, i, fromOcgsToCopy
                 , toOcgs, toDocument)) {
                 toArray.Add(fromOrderItem.CopyTo(toDocument, false));
             }
         }
     }
     else {
         // Stage 3: remove from Order OCGs not presented in the output document. When forming
         // the Order dictionary in the PdfOcProperties constructor, only those OCGs that are
         // in the OCProperties/OCGs array will be taken into account
         if (PdfName.RBGroups.Equals(fieldToCopy)) {
             // Stage 1: delete all RBGroups from the output document in which the copied OCGs were
             for (int i = toArray.Size() - 1; i > -1; i--) {
                 PdfArray toRbGroup = (PdfArray)toArray.Get(i);
                 foreach (PdfObject toRbGroupItemObj in toRbGroup) {
                     if (toOcgsToCopy.Contains(toRbGroupItemObj.GetIndirectReference())) {
                         toArray.Remove(i);
                         break;
                     }
                 }
             }
             // Stage 2: copy all the RBGroups in which the copied OCGs were
             foreach (PdfObject fromRbGroupObj in fromArray) {
                 PdfArray fromRbGroup = (PdfArray)fromRbGroupObj;
                 foreach (PdfObject fromRbGroupItemObj in fromRbGroup) {
                     if (fromOcgsToCopy.Contains(fromRbGroupItemObj.GetIndirectReference())) {
                         toArray.Add(fromRbGroup.CopyTo(toDocument, false));
                         break;
                     }
                 }
             }
         }
         else {
             // Stage 3: remove from RBGroups OCGs not presented in the output
             // document (is in the PdfOcProperties#fillDictionary method)
             foreach (PdfObject fromObj in fromArray) {
                 iText.Kernel.Pdf.OcgPropertiesCopier.AttemptToAddObjectToArray(fromOcgsToCopy, fromObj, toArray, toDocument
                     );
             }
         }
     }
     if (toArray.IsEmpty()) {
         toDict.Remove(fieldToCopy);
     }
 }
Beispiel #25
0
        private void LoadPage(int pageNum)
        {
            PdfDictionary 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.GetObjectType() == PdfObject.ARRAY)
                    {
                        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_1 = 0; i_1 < kids.Size() && kidsCount > 0; i_1++)
                {
                    PdfDictionary pdfPagesObject = kids.GetAsDictionary(i_1);
                    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_1, lastPdfPages.GetPdfObject());
                            newParents.Add(lastPdfPages);
                        }
                        lastPdfPages.AddPage(pdfPagesObject);
                        kids.Remove(i_1);
                        i_1--;
                        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_2 = newParents.Count - 1; i_2 >= 0; i_2--)
                {
                    parents.Add(parentIndex, newParents[i_2]);
                }
                // 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_1 = 0; i_1 < parent.GetCount(); i_1++)
                {
                    pageRefs[from + i_1] = kids.GetAsDictionary(i_1);
                }
            }
        }
        private void FlushObjectRecursively(PdfObject obj, PageFlushingHelper.DeepFlushingContext context)
        {
            if (obj == null)
            {
                return;
            }
            bool avoidReleaseForIndirectObjInstance = false;

            if (obj.IsIndirectReference())
            {
                PdfIndirectReference indRef = (PdfIndirectReference)obj;
                if (indRef.refersTo == null || indRef.CheckState(PdfObject.FLUSHED))
                {
                    return;
                }
                obj = indRef.GetRefersTo();
            }
            else
            {
                if (obj.IsFlushed())
                {
                    return;
                }
                else
                {
                    if (release && obj.IsIndirect())
                    {
                        // We should avoid the case when object is going to be released but is stored in containing object
                        // not as indirect reference. This can happen when containing object is somehow modified.
                        // Generally containing objects should not contain released read-only object instance.
                        System.Diagnostics.Debug.Assert(obj.IsReleaseForbidden() || obj.GetIndirectReference() == null);
                        avoidReleaseForIndirectObjInstance = true;
                    }
                }
            }
            if (pdfDoc.IsDocumentFont(obj.GetIndirectReference()) || layersRefs.Contains(obj.GetIndirectReference()))
            {
                return;
            }
            if (obj.IsDictionary() || obj.IsStream())
            {
                if (!currNestedObjParents.Add(obj))
                {
                    return;
                }
                FlushDictRecursively((PdfDictionary)obj, context);
                currNestedObjParents.Remove(obj);
            }
            else
            {
                if (obj.IsArray())
                {
                    if (!currNestedObjParents.Add(obj))
                    {
                        return;
                    }
                    PdfArray array = (PdfArray)obj;
                    for (int i = 0; i < array.Size(); ++i)
                    {
                        FlushObjectRecursively(array.Get(i, false), context);
                    }
                    currNestedObjParents.Remove(obj);
                }
            }
            if (!avoidReleaseForIndirectObjInstance)
            {
                FlushOrRelease(obj);
            }
        }
Beispiel #27
0
        protected internal virtual byte[] DecodeFlateBytes(PdfStream stream, byte[] bytes)
        {
            PdfObject filterObject = stream.Get(PdfName.Filter);

            if (filterObject == null)
            {
                return(bytes);
            }
            // check if flateDecode filter is on top
            PdfName  filterName;
            PdfArray filtersArray = null;

            if (filterObject is PdfName)
            {
                filterName = (PdfName)filterObject;
            }
            else
            {
                if (filterObject is PdfArray)
                {
                    filtersArray = (PdfArray)filterObject;
                    filterName   = filtersArray.GetAsName(0);
                }
                else
                {
                    throw new PdfException(PdfException.FilterIsNotANameOrArray);
                }
            }
            if (!PdfName.FlateDecode.Equals(filterName))
            {
                return(bytes);
            }
            // get decode params if present
            PdfDictionary decodeParams;
            PdfArray      decodeParamsArray  = null;
            PdfObject     decodeParamsObject = stream.Get(PdfName.DecodeParms);

            if (decodeParamsObject == null)
            {
                decodeParams = null;
            }
            else
            {
                if (decodeParamsObject.GetObjectType() == PdfObject.DICTIONARY)
                {
                    decodeParams = (PdfDictionary)decodeParamsObject;
                }
                else
                {
                    if (decodeParamsObject.GetObjectType() == PdfObject.ARRAY)
                    {
                        decodeParamsArray = (PdfArray)decodeParamsObject;
                        decodeParams      = decodeParamsArray.GetAsDictionary(0);
                    }
                    else
                    {
                        throw new PdfException(PdfException.DecodeParameterType1IsNotSupported).SetMessageParams(decodeParamsObject
                                                                                                                 .GetType().ToString());
                    }
                }
            }
            // decode
            byte[] res = FlateDecodeFilter.FlateDecode(bytes, true);
            if (res == null)
            {
                res = FlateDecodeFilter.FlateDecode(bytes, false);
            }
            bytes = FlateDecodeFilter.DecodePredictor(res, decodeParams);
            //remove filter and decode params
            filterObject = null;
            if (filtersArray != null)
            {
                filtersArray.Remove(0);
                if (filtersArray.Size() == 1)
                {
                    filterObject = filtersArray.Get(0);
                }
                else
                {
                    if (!filtersArray.IsEmpty())
                    {
                        filterObject = filtersArray;
                    }
                }
            }
            decodeParamsObject = null;
            if (decodeParamsArray != null)
            {
                decodeParamsArray.Remove(0);
                if (decodeParamsArray.Size() == 1 && decodeParamsArray.Get(0).GetObjectType() != PdfObject.NULL)
                {
                    decodeParamsObject = decodeParamsArray.Get(0);
                }
                else
                {
                    if (!decodeParamsArray.IsEmpty())
                    {
                        decodeParamsObject = decodeParamsArray;
                    }
                }
            }
            if (filterObject == null)
            {
                stream.Remove(PdfName.Filter);
            }
            else
            {
                stream.Put(PdfName.Filter, filterObject);
            }
            if (decodeParamsObject == null)
            {
                stream.Remove(PdfName.DecodeParms);
            }
            else
            {
                stream.Put(PdfName.DecodeParms, decodeParamsObject);
            }
            return(bytes);
        }