static PdfCleanUpContentOperator()
 {
     textShowingOperators = new HashSet2 <string>();
     textShowingOperators.Add("TJ");
     textShowingOperators.Add("Tj");
     textShowingOperators.Add("'");
     textShowingOperators.Add("\"");
 }
예제 #2
0
        protected override HashSet2 <PdfName> InitKeysForCheck()
        {
            HashSet2 <PdfName> keysForCheck = base.InitKeysForCheck();

            keysForCheck.Add(PdfName.PARAMS);
            keysForCheck.Add(PdfName.MODDATE);
            keysForCheck.Add(PdfName.F);
            return(keysForCheck);
        }
 static PdfCleanUpContentOperator()
 {
     pathPaintingOperators = new HashSet2 <string>(strokeOperators);
     pathPaintingOperators.AddAll(nwFillOperators);
     pathPaintingOperators.AddAll(eoFillOperators);
     pathPaintingOperators.Add("n");
 }
예제 #4
0
 /// <summary>
 /// Removes layers from a PDF document </summary>
 /// <param name="reader">	a PdfReader containing a PDF document </param>
 /// <param name="layers">	a sequence of names of OCG layers </param>
 /// <exception cref="IOException"> </exception>
 public virtual void RemoveLayers(PdfReader reader, params string[] layers)
 {
     int n = reader.NumberOfPages;
     ICollection<string> ocgs = new HashSet2<string>();
     for (int i = 0; i < layers.Length; i++)
     {
         ocgs.Add(layers[i]);
     }
     OCGParser parser = new OCGParser(ocgs);
     for (int i = 1; i <= n; i++)
     {
         PdfDictionary page = reader.GetPageN(i);
         Parse(parser, page);
         page.Remove(new PdfName("PieceInfo"));
         RemoveAnnots(page, ocgs);
         RemoveProperties(page, ocgs);
     }
     PdfDictionary root = reader.Catalog;
     PdfDictionary ocproperties = root.GetAsDict(PdfName.OCPROPERTIES);
     RemoveOCGsFromArray(ocproperties, PdfName.OCGS, ocgs);
     PdfDictionary d = ocproperties.GetAsDict(PdfName.D);
     if (d != null)
     {
         RemoveOCGsFromArray(d, PdfName.ON, ocgs);
         RemoveOCGsFromArray(d, PdfName.OFF, ocgs);
         RemoveOCGsFromArray(d, PdfName.LOCKED, ocgs);
         RemoveOCGsFromArray(d, PdfName.RBGROUPS, ocgs);
         RemoveOCGsFromArray(d, PdfName.ORDER, ocgs);
         RemoveOCGsFromArray(d, PdfName.AS, ocgs);
     }
     reader.RemoveUnusedObjects();
 }
예제 #5
0
 Dictionary <DependencyProperty, Setter> _dictionaryOfSetters; //todo: set this to null if a setter is changed, added or removed or make the corresponding change to it. In fact, the list of setters is not an ObservableCollection so we are unable to detect when the list changes.
 internal Dictionary <DependencyProperty, Setter> GetDictionaryOfSettersFromStyle()
 {
     if (_dictionaryOfSetters == null)
     {
         _dictionaryOfSetters = new Dictionary <DependencyProperty, Setter>();
         Style            currentStyle         = this;
         HashSet2 <Style> stylesAlreadyVisited = new HashSet2 <Style>(); // This is to prevent an infinite loop below.
         while (currentStyle != null && !stylesAlreadyVisited.Contains(currentStyle))
         {
             if (currentStyle.Setters != null)
             {
                 foreach (Setter setter in currentStyle.Setters)
                 {
                     if (setter.Property != null) // Note: it can be null for example in the XAML text editor during design time, because the "DependencyPropertyConverter" class returns "null".
                     {
                         if (!_dictionaryOfSetters.ContainsKey(setter.Property))
                         {
                             _dictionaryOfSetters.Add(setter.Property, setter);
                         }
                     }
                 }
             }
             stylesAlreadyVisited.Add(currentStyle);
             currentStyle = currentStyle.BasedOn;
         }
     }
     return(_dictionaryOfSetters);
 }
예제 #6
0
        internal static void OnClickOnPopupOrWindow(object sender, PointerRoutedEventArgs e)
#endif
        {
            // Note: If a popup has StayOpen=True, the value of "StayOpen" of its parents is ignored.
            // In other words, the parents of a popup that has StayOpen=True will always stay open
            // regardless of the value of their "StayOpen" property.

            HashSet2 <Popup> listOfPopupThatMustBeClosed = new HashSet2 <Popup>();
            List <PopupRoot> popupRootList = new List <PopupRoot>();

            foreach (object obj in GetAllRootUIElements())
            {
                if (obj is PopupRoot)
                {
                    PopupRoot root = (PopupRoot)obj;
                    popupRootList.Add(root);

                    if (root.INTERNAL_LinkedPopup != null)
                    {
                        listOfPopupThatMustBeClosed.Add(root.INTERNAL_LinkedPopup);
                    }
                }
            }

            // We determine which popup needs to stay open after this click
            foreach (PopupRoot popupRoot in popupRootList)
            {
                if (popupRoot.INTERNAL_LinkedPopup != null)
                {
                    // We must prevent all the parents of a popup to be closed when:
                    // - this popup is set to StayOpen
                    // - or the click happend in this popup

                    Popup popup = popupRoot.INTERNAL_LinkedPopup;

                    if (popup.StayOpen || sender == popupRoot)
                    {
                        do
                        {
                            if (!listOfPopupThatMustBeClosed.Contains(popup))
                            {
                                break;
                            }

                            listOfPopupThatMustBeClosed.Remove(popup);

                            popup = popup.ParentPopup;
                        } while (popup != null);
                    }
                }
            }

            foreach (Popup popup in listOfPopupThatMustBeClosed)
            {
                popup.CloseFromAnOutsideClick();
            }
        }
예제 #7
0
        virtual public void SetAppearance(PdfName ap, PdfTemplate template)
        {
            PdfDictionary dic = (PdfDictionary)Get(PdfName.AP);

            if (dic == null)
            {
                dic = new PdfDictionary();
            }
            dic.Put(ap, template.IndirectReference);
            Put(PdfName.AP, dic);
            if (!form)
            {
                return;
            }
            if (templates == null)
            {
                templates = new HashSet2 <PdfTemplate>();
            }
            templates.Add(template);
        }
예제 #8
0
            private void SerObject(PdfObject obj, int level, ByteBuffer bb, HashSet2 <PdfObject> serialized)
            {
                if (level <= 0)
                {
                    return;
                }
                if (obj == null)
                {
                    bb.Append("$Lnull");
                    return;
                }

                if (obj.IsIndirect())
                {
                    if (serialized.Contains(obj))
                    {
                        return;
                    }
                    else
                    {
                        serialized.Add(obj);
                    }
                }
                obj = PdfReader.GetPdfObject(obj);
                if (obj.IsStream())
                {
                    bb.Append("$B");
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                    if (level > 0)
                    {
                        bb.Append(DigestAlgorithms.Digest("MD5", PdfReader.GetStreamBytesRaw((PRStream)obj)));
                    }
                }
                else if (obj.IsDictionary())
                {
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                }
                else if (obj.IsArray())
                {
                    SerArray((PdfArray)obj, level - 1, bb, serialized);
                }
                else if (obj.IsString())
                {
                    bb.Append("$S").Append(obj.ToString());
                }
                else if (obj.IsName())
                {
                    bb.Append("$N").Append(obj.ToString());
                }
                else
                {
                    bb.Append("$L").Append(obj.ToString());
                }
            }
예제 #9
0
        private void RecursivelyUnregisterFromStyleChangedEvents(Style oldStyle)
        {
            // We traverse the Style hierarchy with the "BasedOn" property:
            HashSet2 <Style> stylesAlreadyVisited = new HashSet2 <Style>(); // This is to prevent an infinite loop below.

            while (oldStyle != null && !stylesAlreadyVisited.Contains(oldStyle))
            {
                oldStyle.SetterValueChanged -= StyleSetterValueChanged;
                stylesAlreadyVisited.Add(oldStyle);
                oldStyle = oldStyle.BasedOn;
            }
        }
예제 #10
0
        /// <summary>
        /// Removes layers from a PDF document </summary>
        /// <param name="reader">	a PdfReader containing a PDF document </param>
        /// <param name="layers">	a sequence of names of OCG layers </param>
        /// <exception cref="IOException"> </exception>
        public virtual void RemoveLayers(PdfReader reader, params string[] layers)
        {
            int n = reader.NumberOfPages;

            for (int i = 1; i <= n; i++)
            {
                reader.SetPageContent(i, reader.GetPageContent(i));
            }
            ICollection <string> ocgs = new HashSet2 <string>();

            for (int i = 0; i < layers.Length; i++)
            {
                ocgs.Add(layers[i]);
            }
            OCGParser parser = new OCGParser(ocgs);

            for (int i = 1; i <= n; i++)
            {
                PdfDictionary page = reader.GetPageN(i);
                Parse(parser, page);
                page.Remove(PdfName.PIECEINFO);
                RemoveAnnots(page, ocgs);
                RemoveProperties(page, ocgs);
            }
            PdfDictionary root         = reader.Catalog;
            PdfDictionary ocproperties = root.GetAsDict(PdfName.OCPROPERTIES);

            if (ocproperties != null)
            {
                RemoveOCGsFromArray(ocproperties, PdfName.OCGS, ocgs);
                PdfDictionary d = ocproperties.GetAsDict(PdfName.D);
                if (d != null)
                {
                    RemoveOCGsFromArray(d, PdfName.ON, ocgs);
                    RemoveOCGsFromArray(d, PdfName.OFF, ocgs);
                    RemoveOCGsFromArray(d, PdfName.LOCKED, ocgs);
                    RemoveOCGsFromArray(d, PdfName.RBGROUPS, ocgs);
                    RemoveOCGsFromArray(d, PdfName.ORDER, ocgs);
                    RemoveOCGsFromArray(d, PdfName.AS, ocgs);
                }
                PdfArray ocgsArray = ocproperties.GetAsArray(PdfName.OCGS);
                if (ocgsArray != null && ocgsArray.IsEmpty())
                {
                    root.Remove(PdfName.OCPROPERTIES);
                    if (PdfName.USEOC.Equals(root.GetAsName(PdfName.PAGEMODE)))
                    {
                        root.Remove(PdfName.PAGEMODE);
                    }
                }
            }
            reader.RemoveUnusedObjects();
        }
예제 #11
0
        private String MergeTextDecorationRules(String oldRule, String newRule)
        {
            if (CSS.Value.NONE.Equals(newRule))
            {
                return(newRule);
            }

            HashSet2 <String> attrSet = new HashSet2 <String>();

            if (oldRule != null)
            {
                foreach (String attr in new Regex(@"\s+").Split(oldRule))
                {
                    attrSet.Add(attr);
                }
            }
            if (newRule != null)
            {
                foreach (String attr in new Regex(@"\s+").Split(newRule))
                {
                    attrSet.Add(attr);
                }
            }
            StringBuilder resultantStr = new StringBuilder();

            foreach (String attr in attrSet)
            {
                if (attr.Equals(CSS.Value.NONE) || attr.Equals(CSS.Value.INHERIT))
                {
                    continue;
                }
                if (resultantStr.Length > 0)
                {
                    resultantStr.Append(' ');
                }
                resultantStr.Append(attr);
            }
            return(resultantStr.Length == 0 ? null : resultantStr.ToString());
        }
        virtual protected void FlatGlyphs()
        {
            int[] tableLocation;
            tableDirectory.TryGetValue("glyf", out tableLocation);
            if (tableLocation == null)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("table.1.does.not.exist.in.2", "glyf", fileName));
            }
            int glyph0 = 0;

            if (!glyphsUsed.Contains(glyph0))
            {
                glyphsUsed.Add(glyph0);
                glyphsInList.Add(glyph0);
            }
            tableGlyphOffset = tableLocation[TABLE_OFFSET];
            for (int k = 0; k < glyphsInList.Count; ++k)
            {
                int glyph = glyphsInList[k];
                CheckGlyphComposite(glyph);
            }
        }
예제 #13
0
 internal void INTERNAL_RaiseCompletedEvent(Guid guid)
 {
     if (CompletedGuids == null)
     {
         CompletedGuids = new HashSet2 <Guid>();
     }
     if (!CompletedGuids.Contains(guid))
     {
         CompletedGuids.Add(guid);
     }
     if (Completed != null)
     {
         Completed(this, new EventArgs());
     }
 }
예제 #14
0
 private void fillOrderRecursively(PdfArray orderArray, HashSet2 <PdfObject> order)
 {
     for (int i = 0; i < orderArray.Size; i++)
     {
         PdfArray orderChild = orderArray.GetAsArray(i);
         if (orderChild == null)
         {
             order.Add(orderArray[i]);
         }
         else
         {
             fillOrderRecursively(orderChild, order);
         }
     }
 }
예제 #15
0
 /// <summary>
 /// Removes layers from a PDF document </summary>
 /// <param name="reader">	a PdfReader containing a PDF document </param>
 /// <param name="layers">	a sequence of names of OCG layers </param>
 /// <exception cref="IOException"> </exception>
 public virtual void RemoveLayers(PdfReader reader, params string[] layers) {
     int n = reader.NumberOfPages;
     for (int i = 1; i <= n; i++)
         reader.SetPageContent(i, reader.GetPageContent(i));
     ICollection<string> ocgs = new HashSet2<string>();
     for (int i = 0; i < layers.Length; i++) {
         ocgs.Add(layers[i]);
     }
     OCGParser parser = new OCGParser(ocgs);
     for (int i = 1; i <= n; i++) {
         PdfDictionary page = reader.GetPageN(i);
         Parse(parser, page);
         page.Remove(PdfName.PIECEINFO);
         RemoveAnnots(page, ocgs);
         RemoveProperties(page, ocgs);
     }
     PdfDictionary root = reader.Catalog;
     PdfDictionary ocproperties = root.GetAsDict(PdfName.OCPROPERTIES);
     if (ocproperties != null) {
         RemoveOCGsFromArray(ocproperties, PdfName.OCGS, ocgs);
         PdfDictionary d = ocproperties.GetAsDict(PdfName.D);
         if (d != null) {
             RemoveOCGsFromArray(d, PdfName.ON, ocgs);
             RemoveOCGsFromArray(d, PdfName.OFF, ocgs);
             RemoveOCGsFromArray(d, PdfName.LOCKED, ocgs);
             RemoveOCGsFromArray(d, PdfName.RBGROUPS, ocgs);
             RemoveOCGsFromArray(d, PdfName.ORDER, ocgs);
             RemoveOCGsFromArray(d, PdfName.AS, ocgs);
         }
         PdfArray ocgsArray = ocproperties.GetAsArray(PdfName.OCGS);
         if (ocgsArray != null && ocgsArray.IsEmpty()) {
             root.Remove(PdfName.OCPROPERTIES);
             if (PdfName.USEOC.Equals(root.GetAsName(PdfName.PAGEMODE))) {
                 root.Remove(PdfName.PAGEMODE);
             }
         }
     }
     reader.RemoveUnusedObjects();
 }
예제 #16
0
 internal object GetActiveValue(DependencyProperty dependencyProperty, HashSet2 <Style> stylesAlreadyVisited) // Note: "stylesAlreadyVisited" is here to prevent an infinite recursion.
 {
     stylesAlreadyVisited.Add(this);
     if (Setters != null)
     {
         foreach (Setter setter in Setters)
         {
             if (setter.Property != null) // Note: it can be null for example in the XAML text editor during design time, because the "DependencyPropertyConverter" class returns "null".
             {
                 if (setter.Property == dependencyProperty)
                 {
                     return(setter.Value);
                 }
             }
         }
     }
     if (BasedOn != null && !stylesAlreadyVisited.Contains(BasedOn)) // Note: "stylesAlreadyVisited" is here to prevent an infinite recursion.
     {
         return(BasedOn.GetActiveValue(dependencyProperty, stylesAlreadyVisited));
     }
     return(null);
 }
예제 #17
0
        /// <summary>
        /// Removes layers from a PDF document </summary>
        /// <param name="reader">	a PdfReader containing a PDF document </param>
        /// <param name="layers">	a sequence of names of OCG layers </param>
        /// <exception cref="IOException"> </exception>
        public virtual void RemoveLayers(PdfReader reader, params string[] layers)
        {
            int n = reader.NumberOfPages;
            ICollection <string> ocgs = new HashSet2 <string>();

            for (int i = 0; i < layers.Length; i++)
            {
                ocgs.Add(layers[i]);
            }
            OCGParser parser = new OCGParser(ocgs);

            for (int i = 1; i <= n; i++)
            {
                PdfDictionary page = reader.GetPageN(i);
                Parse(parser, page);
                page.Remove(new PdfName("PieceInfo"));
                RemoveAnnots(page, ocgs);
                RemoveProperties(page, ocgs);
            }
            PdfDictionary root         = reader.Catalog;
            PdfDictionary ocproperties = root.GetAsDict(PdfName.OCPROPERTIES);

            RemoveOCGsFromArray(ocproperties, PdfName.OCGS, ocgs);
            PdfDictionary d = ocproperties.GetAsDict(PdfName.D);

            if (d != null)
            {
                RemoveOCGsFromArray(d, PdfName.ON, ocgs);
                RemoveOCGsFromArray(d, PdfName.OFF, ocgs);
                RemoveOCGsFromArray(d, PdfName.LOCKED, ocgs);
                RemoveOCGsFromArray(d, PdfName.RBGROUPS, ocgs);
                RemoveOCGsFromArray(d, PdfName.ORDER, ocgs);
                RemoveOCGsFromArray(d, PdfName.AS, ocgs);
            }
            reader.RemoveUnusedObjects();
        }
예제 #18
0
        internal static List <CSSEquivalent> MergeCSSEquivalentsOfTheParentsProperties(Brush brush, Func <CSSEquivalent, ValueToHtmlConverter> parentPropertyToValueToHtmlConverter) // note: "CSSEquivalent" here stands for the CSSEquicalent of the parent property.
        {
            List <CSSEquivalent> result = new List <CSSEquivalent>();
            //We copy brush.PropertiesWhereUsed in a local variable because we need to modify it in the foreach:
            HashSet2 <KeyValuePair <DependencyObject, DependencyProperty> > propertiesWhereUsed = new HashSet2 <KeyValuePair <DependencyObject, DependencyProperty> >();

            foreach (KeyValuePair <DependencyObject, DependencyProperty> tuple in brush.PropertiesWhereUsed)
            {
                propertiesWhereUsed.Add(tuple);
            }

            foreach (KeyValuePair <DependencyObject, DependencyProperty> tuple in propertiesWhereUsed)
            {
                UIElement          uiElement          = tuple.Key as UIElement;
                DependencyProperty dependencyProperty = tuple.Value;
                if (uiElement != null)
                {
                    if (!INTERNAL_VisualTreeManager.IsElementInVisualTree(uiElement))
                    {
                        brush.PropertiesWhereUsed.Remove(tuple);
                    }
                    else
                    {
                        PropertyMetadata propertyMetadata = dependencyProperty.GetTypeMetaData(uiElement.GetType());
                        if (propertyMetadata.GetCSSEquivalent != null) // If the parent has a CSSEquivalent, we use it, otherwise we use the parent PropertyChanged method.
                        {
                            var           parentPropertyCSSEquivalent = propertyMetadata.GetCSSEquivalent(uiElement);
                            CSSEquivalent newCSSEquivalent            = new CSSEquivalent()
                            {
                                Name = parentPropertyCSSEquivalent.Name,
                                ApplyAlsoWhenThereIsAControlTemplate = parentPropertyCSSEquivalent.ApplyAlsoWhenThereIsAControlTemplate,

                                Value      = parentPropertyToValueToHtmlConverter(parentPropertyCSSEquivalent),
                                DomElement = parentPropertyCSSEquivalent.DomElement,
                                UIElement  = uiElement
                            };
                            if (newCSSEquivalent.DomElement == null)
                            {
                                newCSSEquivalent.DomElement = uiElement.INTERNAL_OuterDomElement;
                            }
                            result.Add(newCSSEquivalent);
                        }
                        else
                        {
                            //we want to create a CSSEquivalent that will just make the UIElement call the property callback if any:
                            if (propertyMetadata.PropertyChangedCallback != null)
                            {
                                result.Add(new CSSEquivalent()
                                {
                                    UIElement          = uiElement,
                                    CallbackMethod     = propertyMetadata.PropertyChangedCallback,
                                    DependencyProperty = dependencyProperty
                                });
                            }
                        }
                    }
                }
                else
                {
                    //Commented because it could be a Setter in a Style
                    //throw new NotSupportedException("A solidColorBrush cannot currently be set inside a class that desn't inherit from UIElement.");
                }
            }
            return(result);
        }
예제 #19
0
        static object ConvertCSharpObjectToJavaScriptObject(object cSharpObject, bool ignoreErrors, HashSet2 <object> listOfParentsToAvoidCyclicReferences)
        {
            if (cSharpObject != null && listOfParentsToAvoidCyclicReferences.Contains(cSharpObject))
            {
                return(null); //to avoid circular references, which "JSON.stringify" does not handle without specifying what to do in case of circulare reference (cf. https://stackoverflow.com/questions/10392293/stringify-convert-to-json-a-javascript-object-with-circular-reference )
            }
            else
            {
                listOfParentsToAvoidCyclicReferences.Add(cSharpObject);
                object returnValue;

                if (cSharpObject is Enum || cSharpObject is Guid || cSharpObject is long)
                {
                    returnValue = cSharpObject.ToString();
                }
                else if (cSharpObject is DateTime)
                {
                    //Uncomment when fully supported by CSHTML5:
                    //return ((DateTime)cSharpObject).ToUniversalTime().ToString("s", System.Globalization.CultureInfo.InvariantCulture);

                    var      dateTimeUtc           = ((DateTime)cSharpObject).ToUniversalTime();
                    TimeSpan timeSince1970         = (dateTimeUtc - new DateTime(1970, 1, 1, 0, 0, 0));
                    double   millisecondsSince1970 = timeSince1970.TotalMilliseconds;
                    var      jsDate = Interop.ExecuteJavaScript("new Date($0)", millisecondsSince1970);
                    string   json   = Convert.ToString(Interop.ExecuteJavaScript("$0.toJSON()", jsDate));
                    returnValue = json;
                }
                else if (cSharpObject is string
#if !BRIDGE
                         || (cSharpObject != null && cSharpObject.GetType().IsValueType)
#endif
                         )
                {
                    returnValue = cSharpObject;
                }
#if BRIDGE
                else if (cSharpObject != null && cSharpObject.GetType().IsValueType)
                {
                    returnValue = Interop.ExecuteJavaScript("$0.v", cSharpObject);
                }
#endif
                else if (cSharpObject is IEnumerable && !(cSharpObject is string))
                {
                    //----------------
                    // ARRAY
                    //----------------

                    // Create the JS array:
                    var jsArray = Interop.ExecuteJavaScript("[]");

                    // Traverse the enumerable:
                    foreach (var cSharpItem in (IEnumerable)cSharpObject)
                    {
                        var jsItem = ConvertCSharpObjectToJavaScriptObject(cSharpItem, ignoreErrors, listOfParentsToAvoidCyclicReferences);
                        Interop.ExecuteJavaScript("$0.push($1)", jsArray, jsItem);
                    }

                    returnValue = jsArray;
                }
                else if (cSharpObject != null)
                {
                    //----------------
                    // OBJECT
                    //----------------

                    var jsObject = Interop.ExecuteJavaScript(@"new Object()");

                    // Traverse all properties:
                    foreach (PropertyInfo property in cSharpObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                    {
                        string propertyName  = property.Name;
                        object propertyValue = property.GetValue(cSharpObject);

                        if (propertyValue != null)
                        {
                            var recursionResult = ConvertCSharpObjectToJavaScriptObject(propertyValue, ignoreErrors, listOfParentsToAvoidCyclicReferences);
                            if (recursionResult != null)
                            {
                                Interop.ExecuteJavaScript(@"$0[$1] = $2;", jsObject, propertyName, recursionResult);
                            }
                        }
                    }

                    returnValue = jsObject;
                }
                else
                {
                    returnValue = Interop.ExecuteJavaScript("undefined");
                }

                listOfParentsToAvoidCyclicReferences.Remove(cSharpObject);

                return(returnValue);
            }
        }
예제 #20
0
 protected override void CheckLayer(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is IPdfOCG)
     {
     }
     else if (obj1 is PdfOCProperties)
     {
         PdfOCProperties      properties  = (PdfOCProperties)obj1;
         List <PdfDictionary> configsList = new List <PdfDictionary>();
         PdfDictionary        d           = properties.GetAsDict(PdfName.D);
         if (d != null)
         {
             configsList.Add(d);
         }
         PdfArray configs = properties.GetAsArray(PdfName.CONFIGS);
         if (configs != null)
         {
             for (int i = 0; i < configs.Size; i++)
             {
                 PdfDictionary config = configs.GetAsDict(i);
                 if (config != null)
                 {
                     configsList.Add(config);
                 }
             }
         }
         HashSet2 <PdfObject> ocgs      = new HashSet2 <PdfObject>();
         PdfArray             ocgsArray = properties.GetAsArray(PdfName.OCGS);
         if (ocgsArray != null)
         {
             for (int i = 0; i < ocgsArray.Size; i++)
             {
                 ocgs.Add(ocgsArray[i]);
             }
         }
         HashSet2 <String>    names = new HashSet2 <String>();
         HashSet2 <PdfObject> order = new HashSet2 <PdfObject>();
         foreach (PdfDictionary config in configsList)
         {
             PdfString name = config.GetAsString(PdfName.NAME);
             if (name == null)
             {
                 throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("optional.content.configuration.dictionary.shall.contain.name.entry"));
             }
             String name1 = name.ToUnicodeString();
             if (names.Contains(name1))
             {
                 throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("value.of.name.entry.shall.be.unique.amongst.all.optional.content.configuration.dictionaries"));
             }
             names.Add(name1);
             if (config.Contains(PdfName.AS))
             {
                 throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.as.key.shall.not.appear.in.any.optional.content.configuration.dictionary"));
             }
             PdfArray orderArray = config.GetAsArray(PdfName.ORDER);
             if (orderArray != null)
             {
                 fillOrderRecursively(orderArray, order);
             }
         }
         if (order.Count != ocgs.Count)
         {
             throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("order.array.shall.contain.references.to.all.ocgs"));
         }
         ocgs.RetainAll(order);
         if (order.Count != ocgs.Count)
         {
             throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("order.array.shall.contain.references.to.all.ocgs"));
         }
     }
     else
     {
     }
 }
        static object DeserializeToCSharpObject_Object_WithRecursion(IEnumerable <XNode> content, Type resultType, XElement parentElement, IReadOnlyList <Type> knownTypes, bool ignoreErrors, bool useXmlSerializerFormat)
        {
            // Quit if attempting to deserialize to an interface: //todo: investigate why this may happen.
            if (!resultType.IsInterface)
            {
                string resultTypeFullName = resultType.FullName; // For debugging only, can be removed.

                // Create the resulting class:
                object resultInstance = Activator.CreateInstance(resultType); //todo: replace with "System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type)" so that the type does not require a parameterless constructor.

                // Call the "OnDeserializing" method if any:
                CallOnDeserializingMethod(resultInstance, resultType);

                // Get the type information (namespace, etc.) by reading the DataContractAttribute and similar attributes, if present:
                TypeInformation typeInformation = DataContractSerializer_Helpers.GetTypeInformationByReadingAttributes(resultType, null);

                // Read the members of the target type:
                IEnumerable <MemberInformation> membersInformation = DataContractSerializer_Helpers.GetDataContractMembers(resultType, typeInformation.serializationType, useXmlSerializerFormat);

                // Make a dictionary of the members of the target type for faster lookup:
                Dictionary <string, MemberInformation> memberNameToMemberInformation = new Dictionary <string, MemberInformation>();
                foreach (var memberInformation in membersInformation)
                {
                    string memberName = memberInformation.Name;
                    if (resultType.FullName.StartsWith("System.Collections.Generic.KeyValuePair"))
                    {
                        if (memberName == "key")
                        {
                            memberName = "Key";
                        }
                        else if (memberName == "value")
                        {
                            memberName = "Value";
                        }
                    }
                    if (!memberNameToMemberInformation.ContainsKey(memberName))
                    {
                        memberNameToMemberInformation.Add(memberName, memberInformation);
                    }
                    else
                    {
                        MemberInformation collidingMemberInformation = memberNameToMemberInformation[memberName];
                        throw new InvalidDataContractException(
                                  string.Format(
                                      "Type '{0}' contains two members '{1}' 'and '{2}' with the same data member name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using DataMemberAttribute attribute.",
                                      resultType.ToString(),
                                      memberInformation.MemberInfo.Name,
                                      collidingMemberInformation.MemberInfo.Name,
                                      memberName
                                      ));
                    }
                }

                // Populate the values of the properties/members of the class:
                HashSet2 <string> membersForWhichWeSuccessfullSetTheValue = new HashSet2 <string>();
                foreach (XNode node in content)
                {
                    if (node is XElement) // Normally an object property was serialized as an XElement.
                    {
                        XElement xElement    = (XElement)node;
                        XName    elementName = xElement.Name;
                        string   elementNameWithoutNamespace = elementName.LocalName;

                        // Find the member that has the name of the XNode:
                        MemberInformation memberInformation;
                        if (memberNameToMemberInformation.TryGetValue(elementNameWithoutNamespace, out memberInformation))
                        {
                            // Avoid processing nodes that have the same name as other nodes already processed (this can happen in case of [XmlElement] attribute on enumerable members - cf. "special case" below - but it is handled differently):
                            if (!membersForWhichWeSuccessfullSetTheValue.Contains(memberInformation.Name))
                            {
                                object memberValue      = null;
                                Type   memberActualType = memberInformation.MemberType; // Note: this is the initial value. It may be modified below.
                                if (DataContractSerializer_Helpers.IsElementNil(xElement))
                                {
                                    //----------------------
                                    // XNode is "Nil", so we return the default value of the result type
                                    //----------------------

                                    memberValue = DataContractSerializer_Helpers.GetDefault(memberInformation.MemberType);
                                }
                                else
                                {
                                    bool isNull = false;

                                    //foreach (XAttribute attribute in xElement.Attributes(XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance").GetName("nil"))) //doesn't work...
                                    //todo: try removing this foreach since it should be handled in the "if(IsElementDefaut(xElement))" above.
                                    foreach (XAttribute attribute in xElement.Attributes("nil")) //We have to do this here because those usually do not have nodes, which causes problems when doing the recursion.
                                    {
                                        isNull = Convert.ToBoolean(attribute.Value);
                                        if (isNull)
                                        {
                                            memberValue = null;
                                        }
                                    }

                                    if (!isNull)
                                    {
                                        memberActualType = DataContractSerializer_KnownTypes.GetCSharpTypeForNode(xElement, memberInformation.MemberInfo.DeclaringType, memberActualType, knownTypes, memberInformation);

                                        //if the type is nullable, we get the undelying type:
                                        Type nonNullableMemberType = memberActualType;
                                        if (memberActualType.FullName.StartsWith("System.Nullable`1"))
                                        {
                                            nonNullableMemberType = Nullable.GetUnderlyingType(memberActualType);
                                        }

                                        // Recursively create the value for the property:
                                        IEnumerable <XNode> propertyChildNodes = xElement.Nodes();

                                        //********** RECURSION **********
                                        memberValue = DeserializeToCSharpObject(propertyChildNodes, nonNullableMemberType, xElement, knownTypes, ignoreErrors, useXmlSerializerFormat);
                                    }

                                    //---------------------------------
                                    // Handle the special case where there is an [XmlElement] attribute on an enumerable member (XmlSerializer compatibility mode only):
                                    //
                                    // Example:
                                    //      <MyObject>
                                    //         <MyEnumerablePropertyName/>
                                    //         <MyEnumerablePropertyName/>
                                    //         <MyEnumerablePropertyName/>
                                    //      </MyObject>
                                    //
                                    // obtained via:
                                    //      class MyObject
                                    //      {
                                    //          [XmlElement]
                                    //          List<MyType> MyEnumerablePropertyName { get; set; }
                                    //      }
                                    //
                                    // cf. https://docs.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes
                                    //---------------------------------
                                    Type itemsType = null;
                                    bool specialCaseWhereAnEnumerableHasTheXmlElementAttribute =
                                        (useXmlSerializerFormat &&
                                         memberInformation.HasXmlElementAttribute &&
                                         DataContractSerializer_Helpers.IsAssignableToGenericEnumerableOrArray(memberActualType, out itemsType));
                                    if (specialCaseWhereAnEnumerableHasTheXmlElementAttribute)
                                    {
                                        object deserializedEnumerable = DeserializeToCSharpObject_Enumerable_WithRecursion_SpecialCase(
                                            memberInformation.Name,
                                            content, memberActualType, knownTypes, ignoreErrors, itemsType, useXmlSerializerFormat);
                                        memberValue = deserializedEnumerable;
                                    }

                                    //---------------------------------
                                    // Set the value of the member:
                                    //---------------------------------

                                    DataContractSerializer_Helpers.SetMemberValue(resultInstance, memberInformation, memberValue);
                                    membersForWhichWeSuccessfullSetTheValue.Add(memberInformation.Name);
                                }
                            }
                        }
                        else
                        {
                            //-----------
                            // We ignore missing members, to mimic the behavior of the .NET DataContractSerializer.
                            //-----------
                            //throw new Exception("Member '" + memberName + "' not found in type '" + resultType.Name + "'.");
                        }
                    }
                }

                // In case of XmlSerializer compatibility mode, and [XmlAttribute] attribute on a class member, we also need to deserialize the XAttributes (cf. https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributeattribute(v=vs.110).aspx ):
                if (useXmlSerializerFormat)
                {
                    foreach (XAttribute attribute in parentElement.Attributes())
                    {
                        XName attributeName = attribute.Name;
                        // We assume that the object properties have no namespace //todo: fix this assumption, cf. "XmlAttributeAttribute.Namespace" for example (note: repetition of "Attribute" is intended)
                        if (string.IsNullOrEmpty(attributeName.NamespaceName))
                        {
                            string attributeNameWithoutNamespace = attributeName.LocalName;

                            // Find the member that has the name of the XAttribute:
                            MemberInformation memberInformation;
                            if (memberNameToMemberInformation.TryGetValue(attributeNameWithoutNamespace, out memberInformation) &&
                                memberInformation.HasXmlAttributeAttribute)
                            {
                                // Avoid processing members that have already been processed (just in case):
                                if (!membersForWhichWeSuccessfullSetTheValue.Contains(memberInformation.Name))
                                {
                                    string attributeValue = attribute.Value;

                                    // Check to see if the expected type is a value type:
                                    if (DataContractSerializer_ValueTypesHandler.TypesToNames.ContainsKey(memberInformation.MemberType))
                                    {
                                        // Attempt to deserialize the string:
                                        object memberValue = DataContractSerializer_ValueTypesHandler.ConvertStringToValueType(attributeValue, memberInformation.MemberType);

                                        // Set the value of the member:
                                        DataContractSerializer_Helpers.SetMemberValue(resultInstance, memberInformation, memberValue);
                                        membersForWhichWeSuccessfullSetTheValue.Add(memberInformation.Name);
                                    }
                                    else
                                    {
                                        //todo: report the error?
                                        if (memberInformation.MemberType == typeof(List <int>))
                                        {
                                            string[] splittedElements = attributeValue.Split(' ');

#if !BRIDGE
                                            List <int> listint = splittedElements.Select(Int32.Parse).ToList();
#else
                                            List <int> listint = new List <int>();

                                            foreach (string str in splittedElements)
                                            {
                                                listint.Add(Int32.Parse(str));
                                            }
#endif


                                            DataContractSerializer_Helpers.SetMemberValue(resultInstance, memberInformation, listint);
                                            membersForWhichWeSuccessfullSetTheValue.Add(memberInformation.Name);
                                        }
                                    }
                                }
                                else
                                {
                                    //todo: report the error?
                                }
                            }
                            else
                            {
                                //todo: report the error?
                            }
                        }
                    }
                }

                // Verify that the values of all the members marked as "IsRequired" have been set:
                foreach (var memberInformation in membersInformation)
                {
                    if (memberInformation.IsRequired &&
                        !membersForWhichWeSuccessfullSetTheValue.Contains(memberInformation.Name))
                    {
                        throw new SerializationException(string.Format("The member '{0}' is required but it was not found in the document being deserialized.", memberInformation.Name));
                    }
                }

                // Call the "OnDeserialized" method if any:
                CallOnDeserializedMethod(resultInstance, resultType);

                return(resultInstance);
            }
            else
            {
                return(null);
            }
        }
예제 #22
0
 //return new found objects
 private List<PdfIndirectReference> FindActiveParents(HashSet2<RefKey> activeKeys){
     List<PdfIndirectReference> newRefs = new List<PdfIndirectReference>();
     List<PdfCopy.RefKey> tmpActiveKeys = new List<PdfCopy.RefKey>(activeKeys);
     for (int i = 0; i < tmpActiveKeys.Count; ++i) {
         PdfIndirectObject iobj;
         if (!indirectObjects.TryGetValue(tmpActiveKeys[i], out iobj)
             || !iobj.objecti.IsDictionary())
             continue;
         PdfObject parent = ((PdfDictionary)iobj.objecti).Get(PdfName.P);
         if (parent != null && parent.Type == 0) {
             PdfCopy.RefKey key = new PdfCopy.RefKey((PdfIndirectReference)parent);
             if (!activeKeys.Contains(key)) {
                 activeKeys.Add(key);
                 tmpActiveKeys.Add(key);
                 newRefs.Add((PdfIndirectReference) parent);
             }
         }
     }
     return newRefs;
 }
예제 #23
0
        private String MergeTextDecorationRules(String oldRule, String newRule) {
            if (CSS.Value.NONE.Equals(newRule))
                return newRule;

            HashSet2<String> attrSet = new HashSet2<String>();
            if (oldRule != null)
                foreach (String attr in new Regex(@"\s+").Split(oldRule))
                    attrSet.Add(attr);
            if (newRule != null)
                foreach (String attr in new Regex(@"\s+").Split(newRule))
                    attrSet.Add(attr);
            StringBuilder resultantStr = new StringBuilder();
            foreach (String attr in attrSet) {
                if (attr.Equals(CSS.Value.NONE) || attr.Equals(CSS.Value.INHERIT))
                    continue;
                if (resultantStr.Length > 0)
                    resultantStr.Append(' ');
                resultantStr.Append(attr);
            }
            return resultantStr.Length == 0 ? null : resultantStr.ToString();
        }
예제 #24
0
 protected void FlushIndirectObjects()
 {
     foreach (PdfIndirectObject iobj in savedObjects)
         indirectObjects.Remove(new PdfCopy.RefKey(iobj.Number, iobj.Generation));
     HashSet2<RefKey> inactives = new HashSet2<RefKey>();
     foreach (KeyValuePair<RefKey, PdfIndirectObject> entry in indirectObjects) {
         if (entry.Value != null)
             WriteObjectToBody(entry.Value);
         else inactives.Add(entry.Key);
     }
     List<PdfBody.PdfCrossReference> xrefs = new List<PdfBody.PdfCrossReference>();
     foreach (PdfBody.PdfCrossReference xref in body.xrefs.Keys)
         xrefs.Add(xref);
     foreach (PdfBody.PdfCrossReference cr in xrefs) {
         if (cr == null)
             continue;
         RefKey key = new RefKey(cr.Refnum, 0);
         if (inactives.Contains(key))
             body.xrefs.Remove(cr);
     }
     indirectObjects = null;
 }
예제 #25
0
            private void SerObject(PdfObject obj, int level, ByteBuffer bb, HashSet2<PdfObject> serialized)
            {
                if (level <= 0)
                    return;
                if (obj == null) {
                    bb.Append("$Lnull");
                    return;
                }

                if (obj.IsIndirect()) {
                    if (serialized.Contains(obj))
                        return;
                    else
                        serialized.Add(obj);
                }
                obj = PdfReader.GetPdfObject(obj);
                if (obj.IsStream()) {
                    bb.Append("$B");
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                    if (level > 0) {
                        bb.Append(DigestAlgorithms.Digest("MD5", PdfReader.GetStreamBytesRaw((PRStream)obj)));
                    }
                }
                else if (obj.IsDictionary()) {
                    SerDic((PdfDictionary)obj, level - 1, bb,serialized);
                }
                else if (obj.IsArray()) {
                    SerArray((PdfArray)obj, level - 1, bb,serialized);
                }
                else if (obj.IsString()) {
                    bb.Append("$S").Append(obj.ToString());
                }
                else if (obj.IsName()) {
                    bb.Append("$N").Append(obj.ToString());
                }
                else
                    bb.Append("$L").Append(obj.ToString());
            }
예제 #26
0
        private void FindActivesFromReference(PdfIndirectReference iref, List<PdfIndirectReference> actives, HashSet2<PdfCopy.RefKey> activeKeys) {
            PdfCopy.RefKey key = new PdfCopy.RefKey(iref);
            PdfIndirectObject iobj;
            if (indirectObjects.TryGetValue(key, out iobj)
                && iobj.objecti.IsDictionary() && ContainsInactivePg((PdfDictionary) iobj.objecti, activeKeys))
                return;

            if(!activeKeys.Contains(key)) {
                activeKeys.Add(key);
                actives.Add(iref);
            }
        }
예제 #27
0
 private void FindActivesFromDict(PdfDictionary dict, List<PdfIndirectReference> actives, HashSet2<PdfCopy.RefKey> activeKeys,  HashSet2<PdfName> activeClassMaps) {
     if (ContainsInactivePg(dict, activeKeys))
         return;
     foreach (PdfName key in dict.Keys) {
         PdfObject obj = dict.Get(key);
         if (key.Equals(PdfName.P))
             continue;
         else if (key.Equals(PdfName.C)) { //classmap
             if (obj.IsArray()) {
                 foreach (PdfObject cm in (PdfArray)obj) {
                     if (cm.IsName())
                         activeClassMaps.Add((PdfName)cm);
                 }
             }
             else if (obj.IsName()) activeClassMaps.Add((PdfName)obj);
             continue;
         }
         switch (obj.Type) {
             case 0://PdfIndirectReference
                 FindActivesFromReference((PdfIndirectReference)obj, actives, activeKeys);
                 break;
             case PdfObject.ARRAY:
                 FindActivesFromArray((PdfArray)obj, actives, activeKeys, activeClassMaps);
                 break;
             case PdfObject.DICTIONARY:
             case PdfObject.STREAM:
                 FindActivesFromDict((PdfDictionary)obj, actives, activeKeys, activeClassMaps);
                 break;
         }
     }
 }
예제 #28
0
 static PdfA2Checker()
 {
     allowedBlendModes = new HashSet2 <PdfName>();
     allowedBlendModes.Add(PdfGState.BM_NORMAL);
     allowedBlendModes.Add(PdfGState.BM_COMPATIBLE);
     allowedBlendModes.Add(PdfGState.BM_MULTIPLY);
     allowedBlendModes.Add(PdfGState.BM_SCREEN);
     allowedBlendModes.Add(PdfGState.BM_OVERLAY);
     allowedBlendModes.Add(PdfGState.BM_DARKEN);
     allowedBlendModes.Add(PdfGState.BM_LIGHTEN);
     allowedBlendModes.Add(PdfGState.BM_COLORDODGE);
     allowedBlendModes.Add(PdfGState.BM_COLORBURN);
     allowedBlendModes.Add(PdfGState.BM_HARDLIGHT);
     allowedBlendModes.Add(PdfGState.BM_SOFTLIGHT);
     allowedBlendModes.Add(PdfGState.BM_DIFFERENCE);
     allowedBlendModes.Add(PdfGState.BM_EXCLUSION);
 }
 static PdfCleanUpContentOperator() {
     pathPaintingOperators = new HashSet2<string>(strokeOperators);
     pathPaintingOperators.AddAll(nwFillOperators);
     pathPaintingOperators.AddAll(eoFillOperators);
     pathPaintingOperators.Add("n");
 }
예제 #30
0
        static PathGeometry()
        {
            _commandCharacters = new HashSet2 <char>();
            _commandCharacters.Add('m');
            _commandCharacters.Add('M');
            _commandCharacters.Add('l');
            _commandCharacters.Add('L');
            _commandCharacters.Add('h');
            _commandCharacters.Add('H');
            _commandCharacters.Add('v');
            _commandCharacters.Add('V');
            _commandCharacters.Add('c');
            _commandCharacters.Add('C');
            _commandCharacters.Add('s');
            _commandCharacters.Add('S');
            _commandCharacters.Add('q');
            _commandCharacters.Add('Q');
            _commandCharacters.Add('t');
            _commandCharacters.Add('T');
            _commandCharacters.Add('a');
            _commandCharacters.Add('A');
            _commandCharacters.Add('z');
            _commandCharacters.Add('Z');

            _numberCharacters = new HashSet2 <char>();
            _numberCharacters.Add('0');
            _numberCharacters.Add('1');
            _numberCharacters.Add('2');
            _numberCharacters.Add('3');
            _numberCharacters.Add('4');
            _numberCharacters.Add('5');
            _numberCharacters.Add('6');
            _numberCharacters.Add('7');
            _numberCharacters.Add('8');
            _numberCharacters.Add('9');
            _numberCharacters.Add('.');
            _numberCharacters.Add('+');
            _numberCharacters.Add('-');
            _numberCharacters.Add('E');
            _numberCharacters.Add('e');
        }
예제 #31
0
 static PdfA2Checker() {
     allowedBlendModes = new HashSet2<PdfName>();
     allowedBlendModes.Add(PdfGState.BM_NORMAL);
     allowedBlendModes.Add(PdfGState.BM_COMPATIBLE);
     allowedBlendModes.Add(PdfGState.BM_MULTIPLY);
     allowedBlendModes.Add(PdfGState.BM_SCREEN);
     allowedBlendModes.Add(PdfGState.BM_OVERLAY);
     allowedBlendModes.Add(PdfGState.BM_DARKEN);
     allowedBlendModes.Add(PdfGState.BM_LIGHTEN);
     allowedBlendModes.Add(PdfGState.BM_COLORDODGE);
     allowedBlendModes.Add(PdfGState.BM_COLORBURN);
     allowedBlendModes.Add(PdfGState.BM_HARDLIGHT);
     allowedBlendModes.Add(PdfGState.BM_SOFTLIGHT);
     allowedBlendModes.Add(PdfGState.BM_DIFFERENCE);
     allowedBlendModes.Add(PdfGState.BM_EXCLUSION);
 }
예제 #32
0
        protected void FixTaggedStructure()
        {
            Dictionary<int, PdfIndirectReference> numTree = structureTreeRoot.NumTree;
            HashSet2<PdfCopy.RefKey> activeKeys = new HashSet2<PdfCopy.RefKey>();
            List<PdfIndirectReference> actives = new List<PdfIndirectReference>();
            int pageRefIndex = 0;

            if (mergeFields && acroForm != null) {
                actives.Add(acroForm);
                activeKeys.Add(new RefKey(acroForm));
            }
            foreach (PdfIndirectReference page in pageReferences) {
                actives.Add(page);
                activeKeys.Add(new RefKey(page));
            }

            //from end, because some objects can appear on several pages because of MCR (out16.pdf)
            for (int i = numTree.Count - 1; i >= 0; --i) {
                PdfIndirectReference currNum = numTree[i];
                PdfCopy.RefKey numKey = new PdfCopy.RefKey(currNum);
                PdfObject obj = indirectObjects[numKey].objecti;
                if (obj.IsDictionary()) {
                    bool addActiveKeys = false;
                    if (pageReferences.Contains((PdfIndirectReference) ((PdfDictionary) obj).Get(PdfName.PG))) {
                        addActiveKeys = true;
                    }
                    else {
                        PdfDictionary k = PdfStructTreeController.GetKDict((PdfDictionary) obj);
                        if (k != null && pageReferences.Contains((PdfIndirectReference) k.Get(PdfName.PG))) {
                            addActiveKeys = true;
                        }
                    }
                    if (addActiveKeys) {
                        activeKeys.Add(numKey);
                        actives.Add(currNum);
                    }
                    else {
                        numTree.Remove(i);
                    }
                }
                else if (obj.IsArray()) {
                    activeKeys.Add(numKey);
                    actives.Add(currNum);
                    PdfArray currNums = (PdfArray) obj;
                    PdfIndirectReference currPage = pageReferences[pageRefIndex++];
                    actives.Add(currPage);
                    activeKeys.Add(new RefKey(currPage));
                    PdfIndirectReference prevKid = null;
                    for (int j = 0; j < currNums.Size; j++) {
                        PdfIndirectReference currKid = (PdfIndirectReference) currNums.GetDirectObject(j);
                        if (currKid.Equals(prevKid))
                            continue;
                        PdfCopy.RefKey kidKey = new PdfCopy.RefKey(currKid);
                        activeKeys.Add(kidKey);
                        actives.Add(currKid);

                        PdfIndirectObject iobj = indirectObjects[kidKey];
                        if (iobj.objecti.IsDictionary()) {
                            PdfDictionary dict = (PdfDictionary) iobj.objecti;
                            PdfIndirectReference pg = (PdfIndirectReference) dict.Get(PdfName.PG);
                            //if pg is real page - do nothing, else set correct pg and remove first MCID if exists
                            if (!pageReferences.Contains(pg) && !pg.Equals(currPage)) {
                                dict.Put(PdfName.PG, currPage);
                                PdfArray kids = dict.GetAsArray(PdfName.K);
                                if (kids != null) {
                                    PdfObject firstKid = kids.GetDirectObject(0);
                                    if (firstKid.IsNumber()) kids.Remove(0);
                                }
                            }
                        }
                        prevKid = currKid;
                    }
                }
            }

            HashSet2<PdfName> activeClassMaps = new HashSet2<PdfName>();
            //collect all active objects from current active set (include kids, classmap, attributes)
            FindActives(actives, activeKeys, activeClassMaps);
            //find parents of active objects
            List<PdfIndirectReference> newRefs = FindActiveParents(activeKeys);
            //find new objects with incorrect Pg; if find, set Pg from first correct kid. This correct kid must be.
            FixPgKey(newRefs, activeKeys);
            //remove unused kids of StructTreeRoot and remove unused objects from class map
            FixStructureTreeRoot(activeKeys, activeClassMaps);
            List<RefKey> inactiveKeys = new List<RefKey>();
            foreach(KeyValuePair<RefKey, PdfIndirectObject> entry in indirectObjects) {
                if (!activeKeys.Contains(entry.Key)) {
                    inactiveKeys.Add(entry.Key);
                }
                else {
                    if (entry.Value.objecti.IsArray()) {
                        RemoveInactiveReferences((PdfArray)entry.Value.objecti, activeKeys);
                    } else if (entry.Value.objecti.IsDictionary()) {
                        PdfObject kids = ((PdfDictionary)entry.Value.objecti).Get(PdfName.K);
                        if (kids != null && kids.IsArray())
                            RemoveInactiveReferences((PdfArray)kids, activeKeys);
                    }
                }
            }

            //because of cîncurêent modification detected by CLR
            foreach (RefKey key in inactiveKeys)
                indirectObjects[key] = null;
        }
예제 #33
0
 private void FillOrderRecursively(PdfArray orderArray, HashSet2<PdfObject> order) {
     for (int i = 0; i < orderArray.Size; i++) {
         PdfArray orderChild = GetDirectArray(orderArray[i]);
         if (orderChild == null) {
             order.Add(orderArray[i]);
         } else {
             FillOrderRecursively(orderChild, order);
         }
     }
 }
예제 #34
0
        protected override void CheckLayer(PdfWriter writer, int key, Object obj1) {
            if (obj1 is IPdfOCG) {

            } else if (obj1 is PdfOCProperties) {
                PdfOCProperties properties = (PdfOCProperties)obj1;
                List<PdfDictionary> configsList = new List<PdfDictionary>();
                PdfDictionary d = GetDirectDictionary(properties.Get(PdfName.D));
                if (d != null)
                    configsList.Add(d);
                PdfArray configs = GetDirectArray(properties.Get(PdfName.CONFIGS));
                if (configs != null) {
                    for (int i = 0; i < configs.Size; i++) {
                        PdfDictionary config = GetDirectDictionary(configs[i]);
                        if (config != null)
                            configsList.Add(config);
                    }
                }
                HashSet2<PdfObject> ocgs = new HashSet2<PdfObject>();
                PdfArray ocgsArray = GetDirectArray(properties.Get(PdfName.OCGS));
                if (ocgsArray != null)
                    for (int i = 0; i < ocgsArray.Size; i++)
                        ocgs.Add(ocgsArray[i]);
                HashSet2<String> names = new HashSet2<String>();
                HashSet2<PdfObject> order = new HashSet2<PdfObject>();
                foreach (PdfDictionary config in configsList) {
                    PdfString name = config.GetAsString(PdfName.NAME);
                    if (name == null) {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("optional.content.configuration.dictionary.shall.contain.name.entry"));
                    }
                    String name1 = name.ToUnicodeString();
                    if (names.Contains(name1)) {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("value.of.name.entry.shall.be.unique.amongst.all.optional.content.configuration.dictionaries"));
                    }
                    names.Add(name1);
                    if (config.Contains(PdfName.AS)) {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.as.key.shall.not.appear.in.any.optional.content.configuration.dictionary"));
                    }
                    PdfArray orderArray = GetDirectArray(config.Get(PdfName.ORDER));
                    if (orderArray != null)
                        FillOrderRecursively(orderArray, order);
                }
                if (order.Count != ocgs.Count) {
                    throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("order.array.shall.contain.references.to.all.ocgs"));
                }
                ocgs.RetainAll(order);
                if (order.Count != ocgs.Count) {
                    throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("order.array.shall.contain.references.to.all.ocgs"));
                }
            } else {

            }
        }