Пример #1
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);
 }
Пример #2
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();
 }
Пример #3
0
        virtual public void SetAppearance(PdfName ap, string state, PdfTemplate template)
        {
            PdfDictionary dicAp = (PdfDictionary)Get(PdfName.AP);

            if (dicAp == null)
            {
                dicAp = new PdfDictionary();
            }

            PdfDictionary dic;
            PdfObject     obj = dicAp.Get(ap);

            if (obj != null && obj.IsDictionary())
            {
                dic = (PdfDictionary)obj;
            }
            else
            {
                dic = new PdfDictionary();
            }
            dic.Put(new PdfName(state), template.IndirectReference);
            dicAp.Put(ap, dic);
            Put(PdfName.AP, dicAp);
            if (!form)
            {
                return;
            }
            if (templates == null)
            {
                templates = new HashSet2 <PdfTemplate>();
            }
            templates.Add(template);
        }
 static PdfCleanUpContentOperator()
 {
     pathPaintingOperators = new HashSet2 <string>(strokeOperators);
     pathPaintingOperators.AddAll(nwFillOperators);
     pathPaintingOperators.AddAll(eoFillOperators);
     pathPaintingOperators.Add("n");
 }
Пример #5
0
        internal void NotifyStoryboardOfTimelineEnd(Timeline timeline)
        {
            HashSet2 <Guid> completedguids = timeline.CompletedGuids;
            List <Guid>     guidsDealtWith = new List <Guid>();

            foreach (Guid guid in completedguids)
            {
                bool raiseEvent = false;
                lock (thisLock)
                {
                    if (_expectedAmountOfTimelineEndsDict.ContainsKey(guid))
                    {
                        int expectedAmount = _expectedAmountOfTimelineEndsDict[guid];
                        --_expectedAmountOfTimelineEnds;
                        --expectedAmount;
                        _expectedAmountOfTimelineEndsDict[guid] = expectedAmount;
                        guidsDealtWith.Add(guid);
                        if (expectedAmount <= 0)
                        {
                            raiseEvent = true;
                        }
                    }
                }
                if (raiseEvent)
                {
                    OnIterationCompleted(_guidToIterationParametersDict[guid]);
                    _guidToIterationParametersDict.Remove(guid);
                }
            }
            foreach (Guid guid in guidsDealtWith)
            {
                timeline.CompletedGuids.Remove(guid);
            }
        }
        public static void StopListeningToAncestorsVisibilityChanged(DependencyObject listeningElement)
        {
            // Get the list of elements that the element was listening to:
            HashSet2 <DependencyObject> listenedElements = null;

            if (ElementsToListened.ContainsKey(listeningElement))
            {
                listenedElements = ElementsToListened[listeningElement];
            }

            // Unsubscribe from each listened element (the ancestors):
            if (listenedElements != null)
            {
                foreach (DependencyObject listenedElement in listenedElements)
                {
                    RemoveFromDictionaryIfFound(ElementsToListeners, listenedElement, listeningElement);
                }
            }

            // Remove the entry that stores the listened elements:
            if (listenedElements != null)
            {
                ElementsToListened.Remove(listeningElement);
            }

            // Remove the callback:
            if (ListenersToCallbacks.ContainsKey(listeningElement))
            {
                ListenersToCallbacks.Remove(listeningElement);
            }
        }
Пример #7
0
        // Exceptions:
        //   System.ArgumentNullException:
        //     The System.Uri that is passed to System.Windows.Application.GetResourceStream(System.Uri)
        //     is null.
        //
        //   System.ArgumentException:
        //     The System.Uri.OriginalString property of the System.Uri that is passed to
        //     System.Windows.Application.GetResourceStream(System.Uri) is null.
        //
        //   System.ArgumentException:
        //     The System.Uri that is passed to System.Windows.Application.GetResourceStream(System.Uri)
        //     is either not relative, or is absolute but not in the pack://application:,,,/
        //     form.
        //
        //   System.IO.IOException:
        //     The System.Uri that is passed to System.Windows.Application.GetResourceStream(System.Uri)
        //     cannot be found.
        /// <summary>
        /// Returns a string that contains the content of the file that is located at the
        /// specified System.Uri.
        /// </summary>
        /// <param name="uriResource">The System.Uri that maps to an embedded resource.</param>
        /// <returns>
        /// A string that contains the content of the file that is located at the specified System.Uri.
        /// </returns>
        public static Task <string> GetResourceString(Uri uriResource)
        {
            if (_resourcesCache == null)
            {
                _resourcesCache = new Dictionary <string, string>();
            }
            TaskCompletionSource <string> tcs = new TaskCompletionSource <string>();

            if (_resourcesCache.ContainsKey(uriResource.OriginalString.ToLower()))
            {
                tcs.SetResult(_resourcesCache[uriResource.OriginalString.ToLower()]);
                return(tcs.Task);
            }
            HashSet2 <string> supportedExtensions = new HashSet2 <string>(new string[] { ".txt", ".xml", ".config", ".json", ".clientconfig" });

            string uriAsString = uriResource.OriginalString;
            string extension   = uriAsString.Substring(uriAsString.LastIndexOf('.'));

            if (!supportedExtensions.Contains(extension.ToLower())) //todo: when we will be able to handle more extensions, add them to supportedExtensions and do not forget to update GetResourceStream as well.
            {
                throw new NotSupportedException("Application.GetResourceString is currently not supported for files with an extension different than .txt, .xml, .json, .config, or .clientconfig.");
            }
            List <string> uris = new List <string>();

            uris.Add(uriAsString + ".g.js");
            if (uriResource.OriginalString.ToLower() == "ms-appx://app.config")
            {
                CSHTML5.Interop.LoadJavaScriptFilesAsync(
                    uris,
                    (Action)(() =>
                {
                    tcs.SetResult(Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("window.AppConfig")));
                })
                    );
            }
            else if (uriResource.OriginalString.ToLower() == "ms-appx://servicereferences.clientconfig")
            {
                CSHTML5.Interop.LoadJavaScriptFilesAsync(
                    uris,
                    (Action)(() =>
                {
                    tcs.SetResult(Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("window.ServiceReferencesClientConfig")));
                })
                    );
            }
            else
            {
                CSHTML5.Interop.LoadJavaScriptFilesAsync(
                    uris,
                    (Action)(() =>
                {
                    string result = Convert.ToString(CSHTML5.Interop.ExecuteJavaScript("window.FileContent"));
                    _resourcesCache.Add(uriResource.OriginalString.ToLower(), result);
                    tcs.SetResult(result);
                })
                    );
            }
            //return Convert.ToString(Interop.ExecuteJavaScript("window.FileContent"));
            return(tcs.Task);
        }
 static PdfCleanUpContentOperator()
 {
     textShowingOperators = new HashSet2 <string>();
     textShowingOperators.Add("TJ");
     textShowingOperators.Add("Tj");
     textShowingOperators.Add("'");
     textShowingOperators.Add("\"");
 }
Пример #9
0
            internal ByteStore(PRStream str, HashSet2 <PdfObject> serialized)
            {
                ByteBuffer bb    = new ByteBuffer();
                int        level = 100;

                SerObject(str, level, bb, serialized);
                this.b = bb.ToByteArray();
                hash   = CalculateHash(this.b);
            }
Пример #10
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);
        }
Пример #11
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();
            }
        }
Пример #12
0
            internal ByteStore(PdfDictionary dict, HashSet2 <PdfObject> serialized)
            {
                ByteBuffer bb    = new ByteBuffer();
                int        level = 100;

                SerObject(dict, level, bb, serialized);
                this.b = bb.ToByteArray();
                hash   = CalculateHash(this.b);
            }
 /** Creates a new TrueTypeFontSubSet
  * @param directoryOffset The offset from the start of the file to the table directory
  * @param fileName the file name of the font
  * @param glyphsUsed the glyphs used
  * @param includeCmap <CODE>true</CODE> if the table cmap is to be included in the generated font
  */
 public TrueTypeFontSubSet(string fileName, RandomAccessFileOrArray rf, HashSet2 <int> glyphsUsed, int directoryOffset, bool includeCmap, bool includeExtras)
 {
     this.fileName        = fileName;
     this.rf              = rf;
     this.glyphsUsed      = glyphsUsed;
     this.includeCmap     = includeCmap;
     this.includeExtras   = includeExtras;
     this.directoryOffset = directoryOffset;
     glyphsInList         = new List <int>(glyphsUsed);
 }
        private static Path ApplyDashPattern(Path path, LineDashPattern lineDashPattern)
        {
            HashSet2 <int> modifiedSubpaths = new HashSet2 <int>(path.ReplaceCloseWithLine());
            Path           dashedPath       = new Path();
            int            currentSubpath   = 0;

            foreach (Subpath subpath in path.Subpaths)
            {
                IList <Point2D> subpathApprox = subpath.GetPiecewiseLinearApproximation();

                if (subpathApprox.Count > 1)
                {
                    dashedPath.MoveTo((float)subpathApprox[0].GetX(), (float)subpathApprox[0].GetY());
                    float remainingDist  = 0;
                    bool  remainingIsGap = false;

                    for (int i = 1; i < subpathApprox.Count; ++i)
                    {
                        Point2D nextPoint = null;

                        if (remainingDist != 0)
                        {
                            nextPoint     = GetNextPoint(subpathApprox[i - 1], subpathApprox[i], remainingDist);
                            remainingDist = ApplyDash(dashedPath, subpathApprox[i - 1], subpathApprox[i], nextPoint, remainingIsGap);
                        }

                        while ((Util.Compare(remainingDist, 0) == 0) && !dashedPath.CurrentPoint.Equals(subpathApprox[i]))
                        {
                            LineDashPattern.DashArrayElem currentElem = lineDashPattern.Next();
                            nextPoint      = GetNextPoint(nextPoint ?? subpathApprox[i - 1], subpathApprox[i], currentElem.Value);
                            remainingDist  = ApplyDash(dashedPath, subpathApprox[i - 1], subpathApprox[i], nextPoint, currentElem.IsGap);
                            remainingIsGap = currentElem.IsGap;
                        }
                    }

                    // If true, then the line closing the subpath was explicitly added (see Path.ReplaceCloseWithLine).
                    // This causes a loss of a visual effect of line join style parameter, so in this clause
                    // we simply add overlapping dash (or gap, no matter), which continues the last dash and equals to
                    // the first dash (or gap) of the path.
                    if (modifiedSubpaths.Contains(currentSubpath))
                    {
                        lineDashPattern.Reset();
                        LineDashPattern.DashArrayElem currentElem = lineDashPattern.Next();
                        Point2D nextPoint = GetNextPoint(subpathApprox[0], subpathApprox[1], currentElem.Value);
                        ApplyDash(dashedPath, subpathApprox[0], subpathApprox[1], nextPoint, currentElem.IsGap);
                    }
                }

                // According to PDF spec. line dash pattern should be restarted for each new subpath.
                lineDashPattern.Reset();
                ++currentSubpath;
            }

            return(dashedPath);
        }
 static void RemoveFromDictionaryIfFound(Dictionary <DependencyObject, HashSet2 <DependencyObject> > dictionary, DependencyObject key, DependencyObject value)
 {
     if (dictionary.ContainsKey(key))
     {
         HashSet2 <DependencyObject> list = dictionary[key];
         if (list.Contains(value))
         {
             list.Remove(value);
         }
     }
 }
Пример #16
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());
                }
            }
Пример #17
0
        internal void StyleSetterValueChanged(object sender, RoutedEventArgs e)
        {
            Setter setter = (Setter)sender;

            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".
            {
                INTERNAL_PropertyStorage storage = INTERNAL_PropertyStore.GetStorage(this, setter.Property, createAndSaveNewStorageIfNotExists: true); //the createAndSaveNewStorageIfNotExists's value should have no actual meaning here because the PropertyStorage should have been created when applying the style.
                HashSet2 <Style>         stylesAlreadyVisited = new HashSet2 <Style>();                                                                // Note: "stylesAlreadyVisited" is here to prevent an infinite recursion.
                INTERNAL_PropertyStore.SetLocalStyleValue(storage, Style.GetActiveValue(setter.Property, stylesAlreadyVisited));
            }
        }
Пример #18
0
        internal void StyleSetterValueChanged(object sender, RoutedEventArgs e)
        {
            Setter setter = (Setter)sender;

            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".
            {
                INTERNAL_PropertyStorage storage = INTERNAL_PropertyStore.GetStorageOrCreateNewIfNotExists(this, setter.Property);
                HashSet2 <Style>         stylesAlreadyVisited = new HashSet2 <Style>(); // Note: "stylesAlreadyVisited" is here to prevent an infinite recursion.
                INTERNAL_PropertyStore.SetLocalStyleValue(storage, Style.GetActiveValue(setter.Property, stylesAlreadyVisited));
            }
        }
Пример #19
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;
            }
        }
Пример #20
0
 private void SerArray(PdfArray array, int level, ByteBuffer bb, HashSet2 <PdfObject> serialized)
 {
     bb.Append("$A");
     if (level <= 0)
     {
         return;
     }
     for (int k = 0; k < array.Size; ++k)
     {
         SerObject(array[k], level, bb, serialized);
     }
 }
Пример #21
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();
        }
Пример #22
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());
     }
 }
Пример #23
0
        internal void StyleSetterValueChanged(object sender, RoutedEventArgs e)
        {
            Setter setter = (Setter)sender;

            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".
            {
                HashSet2 <Style> stylesAlreadyVisited = new HashSet2 <Style>(); // Note: "stylesAlreadyVisited" is here to prevent an infinite recursion.
                object           value = Style.GetActiveValue(setter.Property, stylesAlreadyVisited);
                // just ignore the value change if it is a BindingExpression
                if (!(value is BindingExpression))
                {
                    this.SetLocalStyleValue(setter.Property, value);
                }
            }
        }
Пример #24
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);
         }
     }
 }
Пример #25
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);
 }
Пример #26
0
 private void SerDic(PdfDictionary dic, int level, ByteBuffer bb, HashSet2 <PdfObject> serialized)
 {
     bb.Append("$D");
     if (level <= 0)
     {
         return;
     }
     PdfName[] keys = new PdfName[dic.Size];
     dic.Keys.CopyTo(keys, 0);
     Array.Sort <PdfName>(keys);
     for (int k = 0; k < keys.Length; ++k)
     {
         SerObject(keys[k], level, bb, serialized);
         SerObject(dic.Get(keys[k]), level, bb, serialized);
     }
 }
Пример #27
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 void AddToDictionaryIfNotAlreadyThere(Dictionary <DependencyObject, HashSet2 <DependencyObject> > dictionary, DependencyObject key, DependencyObject value)
        {
            HashSet2 <DependencyObject> list;

            if (dictionary.ContainsKey(key))
            {
                list = dictionary[key];
            }
            else
            {
                list            = new HashSet2 <DependencyObject>();
                dictionary[key] = list;
            }
            if (!list.Contains(value))
            {
                list.Add(value);
            }
        }
Пример #29
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);
        }
Пример #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
        /**
         * Returns a <CODE>bool</CODE> indicating whether the subpath is degenerate or not.
         * A degenerate subpath is the subpath consisting of a single-point closed path or of
         * two or more points at the same coordinates.
         *
         * @return <CODE>bool</CODE> value indicating whether the path is degenerate or not.
         * @since 5.5.6
         */
        public virtual bool IsDegenerate()
        {
            if (segments.Count > 0 && closed)
            {
                return(false);
            }

            foreach (IShape segment in segments)
            {
                HashSet2 <Point2D> points = new HashSet2 <Point2D>(segment.GetBasePoints());

                // The first segment of a subpath always starts at startPoint, so...
                if (points.Count != 1)
                {
                    return(false);
                }
            }

            // the second clause is for case when we have single point
            return(segments.Count > 0 || closed);
        }
Пример #32
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();
 }
Пример #33
0
 static bool AreNumericTypes(Type type, object obj)
 {
     if (NumericTypes == null)
     {
         NumericTypes = new HashSet2 <Type>
         {
             typeof(Byte),
             typeof(SByte),
             typeof(UInt16),
             typeof(UInt32),
             typeof(UInt64),
             typeof(Int16),
             typeof(Int32),
             typeof(Int64),
             typeof(Decimal),
             typeof(Double),
             typeof(Single),
             typeof(Byte?),
             typeof(SByte?),
             typeof(UInt16?),
             typeof(UInt32?),
             typeof(UInt64?),
             typeof(Int16?),
             typeof(Int32?),
             typeof(Int64?),
             typeof(Decimal?),
             typeof(Double?),
             typeof(Single?),
         };
     }
     if (type != null && NumericTypes.Contains(type) && obj != null && NumericTypes.Contains(obj.GetType()))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #34
0
        private static Path ApplyDashPattern(Path path, LineDashPattern lineDashPattern) {
            HashSet2<int> modifiedSubpaths = new HashSet2<int>(path.ReplaceCloseWithLine());
            Path dashedPath = new Path();
            int currentSubpath = 0;

            foreach (Subpath subpath in path.Subpaths) {
                IList<Point2D> subpathApprox = subpath.GetPiecewiseLinearApproximation();

                if (subpathApprox.Count > 1) {
                    dashedPath.MoveTo((float) subpathApprox[0].GetX(), (float) subpathApprox[0].GetY());
                    float remainingDist = 0;
                    bool remainingIsGap = false;

                    for (int i = 1; i < subpathApprox.Count; ++i) {
                        Point2D nextPoint = null;

                        if (remainingDist != 0) {
                            nextPoint = GetNextPoint(subpathApprox[i - 1], subpathApprox[i], remainingDist);
                            remainingDist = ApplyDash(dashedPath, subpathApprox[i - 1], subpathApprox[i], nextPoint, remainingIsGap);
                        }

                        while ((Util.compare(remainingDist, 0) == 0) && !dashedPath.CurrentPoint.Equals(subpathApprox[i])) {
                            LineDashPattern.DashArrayElem currentElem = lineDashPattern.Next();
                            nextPoint = GetNextPoint(nextPoint ?? subpathApprox[i - 1], subpathApprox[i], currentElem.Value);
                            remainingDist = ApplyDash(dashedPath, subpathApprox[i - 1], subpathApprox[i], nextPoint, currentElem.IsGap);
                            remainingIsGap = currentElem.IsGap;
                        }
                    }

                    // If true, then the line closing the subpath was explicitly added (see Path.ReplaceCloseWithLine).
                    // This causes a loss of a visual effect of line join style parameter, so in this clause
                    // we simply add overlapping dash (or gap, no matter), which continues the last dash and equals to 
                    // the first dash (or gap) of the path.
                    if (modifiedSubpaths.Contains(currentSubpath)) {
                        lineDashPattern.Reset();
                        LineDashPattern.DashArrayElem currentElem = lineDashPattern.Next();
                        Point2D nextPoint = GetNextPoint(subpathApprox[0], subpathApprox[1], currentElem.Value);
                        ApplyDash(dashedPath, subpathApprox[0], subpathApprox[1], nextPoint, currentElem.IsGap);
                    }
                }

                // According to PDF spec. line dash pattern should be restarted for each new subpath.
                lineDashPattern.Reset();
                ++currentSubpath;
            }

            return dashedPath;
        }
Пример #35
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();
        }
Пример #36
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 {

            }
        }
Пример #37
0
 internal PdfAChecker(PdfAConformanceLevel conformanceLevel) {
     keysForCheck = InitKeysForCheck();
     this.conformanceLevel = conformanceLevel;
 }
Пример #38
0
        virtual public void SetAppearance(PdfName ap, string state, PdfTemplate template) {
            PdfDictionary dicAp = (PdfDictionary)Get(PdfName.AP);
            if (dicAp == null)
                dicAp = new PdfDictionary();

            PdfDictionary dic;
            PdfObject obj = dicAp.Get(ap);
            if (obj != null && obj.IsDictionary())
                dic = (PdfDictionary)obj;
            else
                dic = new PdfDictionary();
            dic.Put(new PdfName(state), template.IndirectReference);
            dicAp.Put(ap, dic);
            Put(PdfName.AP, dicAp);
            if (!form)
                return;
            if (templates == null)
                templates = new HashSet2<PdfTemplate>();
            templates.Add(template);
        }
Пример #39
0
 private void FindActives(List<PdfIndirectReference> actives, HashSet2<RefKey> activeKeys, HashSet2<PdfName> activeClassMaps){
     //collect all active objects from current active set (include kids, classmap, attributes)
     for (int i = 0; i < actives.Count; ++i) {
         PdfCopy.RefKey key = new PdfCopy.RefKey(actives[i]);
         PdfIndirectObject iobj;
         if (!indirectObjects.TryGetValue(key, out iobj) || iobj.objecti == null)
             continue;
         switch (iobj.objecti.Type){
             case 0://PdfIndirectReference
                 FindActivesFromReference((PdfIndirectReference)iobj.objecti, actives, activeKeys);
                 break;
             case PdfObject.ARRAY:
                 FindActivesFromArray((PdfArray)iobj.objecti, actives, activeKeys, activeClassMaps);
                 break;
             case PdfObject.DICTIONARY:
             case PdfObject.STREAM:
                 FindActivesFromDict((PdfDictionary)iobj.objecti, actives, activeKeys, activeClassMaps);
                 break;
         }
     }
 }
Пример #40
0
 /** Creates a new TrueTypeFontSubSet
  * @param directoryOffset The offset from the start of the file to the table directory
  * @param fileName the file name of the font
  * @param glyphsUsed the glyphs used
  * @param includeCmap <CODE>true</CODE> if the table cmap is to be included in the generated font
  */
 public TrueTypeFontSubSet(string fileName, RandomAccessFileOrArray rf, HashSet2<int> glyphsUsed, int directoryOffset, bool includeCmap, bool includeExtras) {
     this.fileName = fileName;
     this.rf = rf;
     this.glyphsUsed = glyphsUsed;
     this.includeCmap = includeCmap;
     this.includeExtras = includeExtras;
     this.directoryOffset = directoryOffset;
     glyphsInList = new List<int>(glyphsUsed);
 }
Пример #41
0
 private void FindActivesFromArray(PdfArray array, List<PdfIndirectReference> actives, HashSet2<PdfCopy.RefKey> activeKeys, HashSet2<PdfName> activeClassMaps) {
     foreach (PdfObject obj in array) {
         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;
         }
     }
 }
Пример #42
0
 public void SetMergeFields() {
     mergeFields = true;
     resources = new PdfDictionary();
     fields = new List<AcroFields>();
     calculationOrder = new List<String>();
     fieldTree = new Dictionary<string, object>();
     unmergedMap = new Dictionary<int, PdfIndirectObject>();
     unmergedSet = new HashSet2<PdfIndirectObject>();
     mergedMap = new Dictionary<int, PdfIndirectObject>();
     mergedSet = new HashSet2<PdfIndirectObject>();
 }
Пример #43
0
 internal ByteStore(PRStream str, HashSet2<PdfObject> serialized)
 {
     ByteBuffer bb = new ByteBuffer();
     int level = 100;
     SerObject(str, level, bb, serialized);
     this.b = bb.ToByteArray();
     hash = CalculateHash(this.b);
 }
Пример #44
0
        /**
        * Constructor
        * @param document
        * @param os outputstream
        */
        public PdfCopy(Document document, Stream os) : base(new PdfDocument(), os) {
            document.AddDocListener(pdf);
            pdf.AddWriter(this);
            indirectMap = new Dictionary<PdfReader,Dictionary<RefKey,IndirectReferences>>();
            parentObjects = new Dictionary<PdfObject, PdfObject>();
            disableIndirects = new HashSet2<PdfObject>();

            indirectObjects = new Dictionary<RefKey, PdfIndirectObject>();
            savedObjects = new List<PdfIndirectObject>();
            importedPages = new List<ImportedPage>();
        }
Пример #45
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;
 }
Пример #46
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;
         }
     }
 }
Пример #47
0
 internal ByteStore(PdfDictionary dict, HashSet2<PdfObject> serialized)
 {
     ByteBuffer bb = new ByteBuffer();
     int level = 100;
     SerObject(dict, level, bb, serialized);
     this.b = bb.ToByteArray();
     hash = CalculateHash(this.b);
 }
Пример #48
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());
            }
Пример #49
0
        internal void FixStructureTreeRoot(HashSet2<RefKey> activeKeys, HashSet2<PdfName> activeClassMaps)
        {
            Dictionary<PdfName, PdfObject> newClassMap = new Dictionary<PdfName, PdfObject>(activeClassMaps.Count);
            foreach (PdfName key in activeClassMaps)
            {
                PdfObject cm = structureTreeRoot.classes[key];
                if (cm != null)
                    newClassMap[key] = cm;
            }

            structureTreeRoot.classes = newClassMap;

            PdfArray kids = structureTreeRoot.GetAsArray(PdfName.K);
            if (kids != null)
                for (int i = 0; i < kids.Size; ++i)
                {
                    PdfIndirectReference iref = (PdfIndirectReference) kids[i];
                    RefKey key = new RefKey(iref);
                    if (!activeKeys.Contains(key))
                        kids.Remove(i--);
                }
        }
Пример #50
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);
            }
        }
Пример #51
0
 private void SerArray(PdfArray array, int level, ByteBuffer bb, HashSet2<PdfObject> serialized)
 {
     bb.Append("$A");
     if (level <= 0)
         return;
     for (int k = 0; k < array.Size; ++k) {
         SerObject(array[k], level, bb, serialized);
     }
 }
Пример #52
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;
        }
Пример #53
0
 private void SerDic(PdfDictionary dic, int level, ByteBuffer bb, HashSet2<PdfObject> serialized)
 {
     bb.Append("$D");
     if (level <= 0)
         return;
     PdfName[] keys = new PdfName[dic.Size];
     dic.Keys.CopyTo(keys, 0);
     Array.Sort<PdfName>(keys);
     for (int k = 0; k < keys.Length; ++k) {
         SerObject(keys[k], level, bb, serialized);
         SerObject(dic.Get(keys[k]), level, bb, serialized);
     }
 }
Пример #54
0
 private void RemoveInactiveReferences(PdfArray array, HashSet2<PdfCopy.RefKey> activeKeys) {
     for (int i = 0; i < array.Size; ++i) {
         PdfObject obj = array[i];
         if ((obj.Type == 0 && !activeKeys.Contains(new PdfCopy.RefKey((PdfIndirectReference)obj))) ||
                 (obj.IsDictionary() && ContainsInactivePg((PdfDictionary)obj, activeKeys)))
             array.Remove(i--);
     }
 }
 static PdfCleanUpContentOperator() {
     pathPaintingOperators = new HashSet2<string>(strokeOperators);
     pathPaintingOperators.AddAll(nwFillOperators);
     pathPaintingOperators.AddAll(eoFillOperators);
     pathPaintingOperators.Add("n");
 }
Пример #56
0
 private bool ContainsInactivePg(PdfDictionary dict, HashSet2<PdfCopy.RefKey> activeKeys) {
     PdfObject pg = dict.Get(PdfName.PG);
     if (pg != null && !activeKeys.Contains(new PdfCopy.RefKey((PdfIndirectReference)pg)))
         return true;
     return false;
 }
Пример #57
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;
 }
Пример #58
0
 private void FixPgKey(List<PdfIndirectReference> newRefs, HashSet2<RefKey> activeKeys){
     foreach (PdfIndirectReference iref in newRefs) {
         PdfIndirectObject iobj;
         if (!indirectObjects.TryGetValue(new RefKey(iref), out iobj)
             || !iobj.objecti.IsDictionary())
             continue;
         PdfDictionary dict = (PdfDictionary)iobj.objecti;
         PdfObject pg = dict.Get(PdfName.PG);
         if (pg == null || activeKeys.Contains(new RefKey((PdfIndirectReference)pg))) continue;
         PdfArray kids = dict.GetAsArray(PdfName.K);
         if (kids == null) continue;
         for (int i = 0; i < kids.Size; ++i) {
             PdfObject obj = kids[i];
             if (obj.Type != 0) {
                 kids.Remove(i--);
             } else {
                 PdfIndirectObject kid;
                 if (indirectObjects.TryGetValue(new RefKey((PdfIndirectReference)obj), out kid)
                     && kid.objecti.IsDictionary())
                 {
                     PdfObject kidPg = ((PdfDictionary)kid.objecti).Get(PdfName.PG);
                     if (kidPg != null && activeKeys.Contains(new RefKey((PdfIndirectReference)kidPg))) {
                         dict.Put(PdfName.PG, kidPg);
                         break;
                     }
                 }
             }
         }
     }
 }
Пример #59
0
 protected internal byte[] GetSubSet(HashSet2<int> glyphs, bool subsetp)  {
     lock (head) {
         TrueTypeFontSubSet sb = new TrueTypeFontSubSet(fileName, new RandomAccessFileOrArray(rf), glyphs, directoryOffset, true, !subsetp);
         return sb.Process();
     }
 }
Пример #60
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);
         }
     }
 }