コード例 #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
        // 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);
        }
コード例 #3
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();
            }
        }
コード例 #4
0
ファイル: PdfA2Checker.cs プロジェクト: tbrion/itextsharp
        protected override void CheckGState(PdfWriter writer, int key, Object obj1)
        {
            PdfDictionary gs  = (PdfDictionary)obj1;
            PdfObject     obj = gs.Get(PdfName.BM);

            if (obj != null && !allowedBlendModes.Contains((PdfName)obj))
            {
                throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("blend.mode.1.not.allowed", obj.ToString()));
            }
        }
コード例 #5
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);
        }
コード例 #6
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());
                }
            }
コード例 #7
0
 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);
         }
     }
 }
コード例 #8
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;
            }
        }
コード例 #9
0
ファイル: BindingExpression.cs プロジェクト: Kr3m/CSHTML5
 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);
     }
 }
コード例 #10
0
        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);
            }
        }
コード例 #11
0
        private String GetParentDirection()
        {
            String result = null;

            foreach (Tag tag in tree)
            {
                if (!ignoreDirAttribute.Contains(tag.Name.ToLower()))
                {
                    tag.Attributes.TryGetValue(HTML.Attribute.DIR, out result);

                    if (result != null)
                    {
                        break;
                    }
                    // Nested tables need this check
                    tag.CSS.TryGetValue(CSS.Property.DIRECTION, out result);
                    if (result != null)
                    {
                        break;
                    }
                }
            }
            return(result);
        }
コード例 #12
0
ファイル: Timeline.cs プロジェクト: qasimnaeem/CSHTML5
 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());
     }
 }
コード例 #13
0
        private void WritePath(String operatorStr, PdfContentByte canvas, PdfName strokeColorSpace)
        {
            if (nwFillOperators.Contains(operatorStr))
            {
                WritePath(cleanUpStrategy.CurrentFillPath, f, canvas);
            }
            else if (eoFillOperators.Contains(operatorStr))
            {
                WritePath(cleanUpStrategy.CurrentFillPath, eoF, canvas);
            }

            if (strokeOperators.Contains(operatorStr))
            {
                WriteStroke(canvas, cleanUpStrategy.CurrentStrokePath, strokeColorSpace);
            }

            if (cleanUpStrategy.Clipped)
            {
                if (!cleanUpStrategy.NewClipPath.IsEmpty())
                {
                    byte[] clippingOperator = (cleanUpStrategy.ClippingRule == PathPaintingRenderInfo.NONZERO_WINDING_RULE) ? W : eoW;
                    WritePath(cleanUpStrategy.NewClipPath, clippingOperator, canvas);
                }
                else
                {
                    // If the clipping path from the source document is cleaned (it happens when reduction
                    // area covers the path completely), then you should treat it as an empty set (no points
                    // are included in the path). Then the current clipping path (which is the intersection
                    // between previous clipping path and the new one) is also empty set, which means that
                    // there is no visible content at all. But at the same time as we removed the clipping
                    // path, the invisible content would become visible. So, to emulate the correct result,
                    // we would simply put a degenerate clipping path which consists of a single point at (0, 0).
                    Path degeneratePath = new Path();
                    degeneratePath.MoveTo(0, 0);
                    WritePath(degeneratePath, W, canvas);
                }
                canvas.InternalBuffer.Append(n);
                cleanUpStrategy.Clipped = false;
            }
        }
コード例 #14
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);
 }
コード例 #15
0
        protected override void CheckFileSpec(PdfWriter writer, int key, Object obj1)
        {
            if (obj1 is PdfFileSpecification)
            {
                PdfDictionary fileSpec = (PdfFileSpecification)obj1;
                if (!fileSpec.Contains(PdfName.UF) || !fileSpec.Contains(PdfName.F) ||
                    !fileSpec.Contains(PdfName.DESC))
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("file.specification.dictionary.shall.contain.f.uf.and.desc.entries"));
                }

                PdfObject obj = fileSpec.Get(PdfName.AFRELATIONSHIP);

                if (obj == null || !obj.IsName() || !allowedAFRelationships.Contains(obj as PdfName))
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("file.specification.dictionary.shall.contain.correct.afrelationship.key"));
                }

                if (fileSpec.Contains(PdfName.EF))
                {
                    PdfDictionary dict = GetDirectDictionary(fileSpec.Get(PdfName.EF));
                    if (dict == null || !dict.Contains(PdfName.F))
                    {
                        throw new PdfAConformanceException(obj1,
                                                           MessageLocalization.GetComposedMessage("ef.key.of.file.specification.dictionary.shall.contain.dictionary.with.valid.f.key"));
                    }

                    PdfDictionary embeddedFile = GetDirectDictionary(dict.Get(PdfName.F));
                    if (embeddedFile == null)
                    {
                        throw new PdfAConformanceException(obj1,
                                                           MessageLocalization.GetComposedMessage("ef.key.of.file.specification.dictionary.shall.contain.dictionary.with.valid.f.key"));
                    }

                    CheckEmbeddedFile(embeddedFile);
                }
            }
        }
コード例 #16
0
        private void WritePath(String operatorStr, PdfContentByte canvas, PdfName strokeColorSpace)
        {
            if (nwFillOperators.Contains(operatorStr))
            {
                WritePath(cleanUpStrategy.CurrentFillPath, f, canvas);
            }
            else if (eoFillOperators.Contains(operatorStr))
            {
                WritePath(cleanUpStrategy.CurrentFillPath, eoF, canvas);
            }

            if (strokeOperators.Contains(operatorStr))
            {
                WriteStroke(canvas, cleanUpStrategy.CurrentStrokePath, strokeColorSpace);
            }

            if (cleanUpStrategy.Clipped && !cleanUpStrategy.NewClipPath.IsEmpty())
            {
                byte[] clippingOperator = (cleanUpStrategy.ClippingRule == PathPaintingRenderInfo.NONZERO_WINDING_RULE) ? W : eoW;
                WritePath(cleanUpStrategy.NewClipPath, clippingOperator, canvas);
                canvas.InternalBuffer.Append(n);
                cleanUpStrategy.Clipped = false;
            }
        }
コード例 #17
0
ファイル: PdfAChecker.cs プロジェクト: zeespogeira/itextsharp
        private PdfObject CleverPdfDictionaryClone(PdfDictionary dict)
        {
            PdfDictionary newDict;

            if (dict.IsStream())
            {
                newDict = new PdfStream(emptyByteArray);
                newDict.Remove(PdfName.LENGTH);
            }
            else
            {
                newDict = new PdfDictionary();
            }

            foreach (PdfName key in dict.Keys)
            {
                if (keysForCheck.Contains(key))
                {
                    newDict.Put(key, dict.Get(key));
                }
            }

            return(newDict);
        }
コード例 #18
0
ファイル: PdfA1Checker.cs プロジェクト: tomaszmat/code
 protected override void CheckAction(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is PdfAction)
     {
         PdfAction action = (PdfAction)obj1;
         PdfName   s      = action.GetAsName(PdfName.S);
         if (setState.Equals(s) || noOp.Equals(s))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("deprecated.setstate.and.noop.actions.are.not.allowed"));
         }
         if (restrictedActions.Contains(s))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("launch.sound.movie.resetform.importdata.and.javascript.actions.are.not.allowed"));
         }
         if (PdfName.NAMED.Equals(s))
         {
             PdfName n = action.GetAsName(PdfName.N);
             if (n != null && !allowedNamedActions.Contains(n))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("named.action.type.1.not.allowed", n.ToString()));
             }
         }
     }
 }
コード例 #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
        private void RunLargeTableTest(String name, int headerRows, int footerRows, int rows, params int[] flushIndexes)
        {
            String outPdf = outFolder + name + ".pdf";
            String cmpPdf = cmpFolder + "cmp_" + name + ".pdf";
            String diff   = "diff_" + name + "_";

            Document  document  = new Document();
            Stream    outStream = File.Create(outPdf);
            PdfWriter writer    = PdfWriter.GetInstance(document, outStream);

            document.SetPageSize(PageSize.A4);
            document.Open();

            PdfPTable table = new PdfPTable(1);

            table.Complete  = false;
            table.SplitRows = false;
            table.SplitLate = false;

            int fullHeader = 0;

            if (headerRows > 0)
            {
                for (int i = 0; i < headerRows; ++i)
                {
                    PdfPCell header = new PdfPCell();
                    header.AddElement(new Phrase("Header " + i));
                    table.AddCell(header);
                }
                fullHeader += headerRows;
            }
            if (footerRows > 0)
            {
                for (int i = 0; i < footerRows; ++i)
                {
                    PdfPCell footer = new PdfPCell();
                    footer.AddElement(new Phrase("Footer " + i));
                    table.AddCell(footer);
                }
                fullHeader      += footerRows;
                table.FooterRows = footerRows;
            }
            table.HeaderRows = fullHeader;

            HashSet2 <int> indexes = new HashSet2 <int>(flushIndexes);

            for (int i = 0; i < rows; ++i)
            {
                PdfPCell cell = new PdfPCell();
                cell.AddElement(new Phrase(i.ToString(CultureInfo.InvariantCulture)));
                table.AddCell(cell);

                if (indexes.Contains(i))
                {
                    document.Add(table);
                }
            }

            table.Complete = true;
            document.Add(table);

            document.Close();
            writer.Close();
            outStream.Close();

            Assert.Null(new CompareTool().CompareByContent(outPdf, cmpPdf, outFolder, diff));
        }
コード例 #21
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;
                     }
                 }
             }
         }
     }
 }
コード例 #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 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;
 }
コード例 #24
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;
        }
コード例 #25
0
        public virtual void Invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral oper, List <PdfObject> operands)
        {
            String         operatorStr   = oper.ToString();
            PdfContentByte canvas        = cleanUpStrategy.Context.Canvas;
            PRStream       xFormStream   = null;
            bool           disableOutput = pathConstructionOperators.Contains(operatorStr) || pathPaintingOperators.Contains(operatorStr) || clippingPathOperators.Contains(operatorStr);
            GraphicsState  gs            = pdfContentStreamProcessor.Gs();

            // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0.
            // BE AWARE: zero-length strings are ignored!!!
            IDictionary <int, float> structuredTJoperands = null;

            if ("Do" == operatorStr)
            {
                if (operands.Count == 2 && operands[0].IsName())
                {
                    PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT);

                    if (xObjResources != null)
                    {
                        PdfStream xObj = xObjResources.GetAsStream((PdfName)operands[0]);

                        if (xObj is PRStream && xObj.GetAsName(PdfName.SUBTYPE) != null &&
                            xObj.GetAsName(PdfName.SUBTYPE).CompareTo(PdfName.FORM) == 0)
                        {
                            xFormStream = (PRStream)xObj;
                            cleanUpStrategy.RegisterNewContext(xObj.GetAsDict(PdfName.RESOURCES), null);
                        }
                    }
                }
            }

            originalContentOperator.Invoke(pdfContentStreamProcessor, oper, operands);
            IList <PdfCleanUpContentChunk> chunks = cleanUpStrategy.Chunks;

            if (xFormStream != null)
            {
                xFormStream.SetData(cleanUpStrategy.Context.Canvas.ToPdf(cleanUpStrategy.Context.Canvas.PdfWriter));
                cleanUpStrategy.PopContext();
                canvas = cleanUpStrategy.Context.Canvas;
            }

            if ("Do" == operatorStr)
            {
                if (chunks.Count > 0 && chunks[0] is PdfCleanUpContentChunk.Image)
                {
                    PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image)chunks[0];

                    if (chunk.Visible)
                    {
                        PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT);
                        PRStream      imageStream   = (PRStream)xObjResources.GetAsStream((PdfName)operands[0]);
                        UpdateImageStream(imageStream, chunk.NewImageData);
                    }
                    else
                    {
                        disableOutput = true;
                    }
                }
            }
            else if (lineStyleOperators.Contains(operatorStr))
            {
                disableOutput = true;
            }
            else if (textShowingOperators.Contains(operatorStr) && !AllChunksAreVisible(cleanUpStrategy.Chunks))
            {
                disableOutput = true;

                if ("'" == operatorStr)
                {
                    canvas.InternalBuffer.Append(TStar);
                }
                else if ("\"" == operatorStr)
                {
                    operands[0].ToPdf(canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(Tw);

                    operands[1].ToPdf(canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(TcTStar);
                }
                else if ("TJ" == operatorStr)
                {
                    structuredTJoperands = StructureTJarray((PdfArray)operands[0]);
                }

                WriteTextChunks(structuredTJoperands, chunks, canvas, gs.CharacterSpacing, gs.WordSpacing,
                                gs.FontSize, gs.HorizontalScaling);
            }
            else if (pathPaintingOperators.Contains(operatorStr))
            {
                WritePath(operatorStr, canvas, gs.ColorSpaceStroke);
            }
            else if (strokeColorOperators.Contains(operatorStr))
            {
                // Replace current color with the new one.
                cleanUpStrategy.Context.PopStrokeColor();
                cleanUpStrategy.Context.PushStrokeColor(operands);
            }
            else if ("q" == operatorStr)
            {
                cleanUpStrategy.Context.PushStrokeColor(cleanUpStrategy.Context.PeekStrokeColor());
            }
            else if ("Q" == operatorStr)
            {
                cleanUpStrategy.Context.PopStrokeColor();
            }

            if (!disableOutput)
            {
                WriteOperands(canvas, operands);
            }

            cleanUpStrategy.ClearChunks();
        }
コード例 #26
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());
            }
コード例 #27
0
        public void Invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral @operator, List <PdfObject> operands)
        {
            String         operatorStr = @operator.ToString();
            PdfContentByte canvas      = cleanUpStrategy.Context.Canvas;
            PRStream       xFormStream = null;

            // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0.
            // BE AWARE: zero-length strings are ignored!!!
            IDictionary <int, float> structuredTJoperands = null;

            if ("Do" == operatorStr)
            {
                if (operands.Count == 2 && operands[0].IsName())
                {
                    PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT);

                    if (xObjResources != null)
                    {
                        PdfStream xObj = xObjResources.GetAsStream((PdfName)operands[0]);

                        if (xObj is PRStream && xObj.GetAsName(PdfName.SUBTYPE) != null &&
                            xObj.GetAsName(PdfName.SUBTYPE).CompareTo(PdfName.FORM) == 0)
                        {
                            xFormStream = (PRStream)xObj;
                            cleanUpStrategy.RegisterNewContext(xObj.GetAsDict(PdfName.RESOURCES), null);
                        }
                    }
                }
            }

            originalContentOperator.Invoke(pdfContentStreamProcessor, @operator, operands);
            IList <PdfCleanUpContentChunk> chunks = cleanUpStrategy.Chunks;
            bool disableOutput = false;

            if (xFormStream != null)
            {
                xFormStream.SetData(cleanUpStrategy.Context.Canvas.ToPdf(cleanUpStrategy.Context.Canvas.PdfWriter));
                cleanUpStrategy.PopContext();
                canvas = cleanUpStrategy.Context.Canvas;
            }

            if ("Do" == operatorStr)
            {
                if (chunks.Count > 0 && chunks[0].IsImage())
                {
                    PdfCleanUpContentChunk chunk = chunks[0];

                    if (chunk.IsVisible())
                    {
                        PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT);
                        PRStream      imageStream   = (PRStream)xObjResources.GetAsStream((PdfName)operands[0]);
                        UpdateImage(imageStream, chunk.NewImageData);
                    }
                    else
                    {
                        disableOutput = true;
                    }
                }
            }
            else if ("q" == operatorStr)
            {
                cleanUpStrategy.Context.SaveGraphicsState();
            }
            else if ("Q" == operatorStr)
            {
                cleanUpStrategy.Context.RestoreGraphicsState();
            }
            else if ("Tf" == operatorStr)
            {
                cleanUpStrategy.Context.FontSize = ((PdfNumber)operands[1]).FloatValue;
            }
            else if ("Tc" == operatorStr)
            {
                cleanUpStrategy.Context.CharacterSpacing = ((PdfNumber)operands[0]).FloatValue;
            }
            else if ("Tw" == operatorStr)
            {
                cleanUpStrategy.Context.WordSpacing = ((PdfNumber)operands[0]).FloatValue;
            }
            else if ("Tz" == operatorStr)
            {
                cleanUpStrategy.Context.HorizontalScaling = ((PdfNumber)operands[0]).FloatValue;
            }
            else if (textShowingOperators.Contains(operatorStr) && !AllChunksAreVisible(cleanUpStrategy.Chunks))
            {
                disableOutput = true;

                if ("'" == operatorStr)
                {
                    canvas.InternalBuffer.Append(TStar);
                }
                else if ("\"" == operatorStr)
                {
                    operands[0].ToPdf(canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(Tw);

                    operands[1].ToPdf(canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(TcTStar);

                    cleanUpStrategy.Context.CharacterSpacing = ((PdfNumber)operands[1]).FloatValue;
                }
                else if ("TJ" == operatorStr)
                {
                    structuredTJoperands = StructureTJarray((PdfArray)operands[0]);
                }

                RenderChunks(structuredTJoperands, chunks, canvas);
            }
            else if ("\"" == operatorStr)
            {
                cleanUpStrategy.Context.CharacterSpacing = ((PdfNumber)operands[1]).FloatValue;
            }

            if (!disableOutput)
            {
                int index = 0;

                foreach (PdfObject o in operands)
                {
                    ToPdf(o, canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(operands.Count > ++index ? (byte)' ' : (byte)'\n');
                }
            }

            cleanUpStrategy.ClearChunks();
        }
コード例 #28
0
ファイル: PathGeometry.cs プロジェクト: xiongzhaoxu/CSHTML5
        /// <summary>
        /// reads and returns the next number in the given string, starting at the given index.
        /// </summary>
        /// <param name="stringContainingNumber">The string in which to read the number.</param>
        /// <param name="startIndex">The index at which we start reading the number (note: the number MUST be the first thing after given index, white spaces are handled)</param>
        /// <param name="stopIndex">The index of the character right after the end of the number.</param>
        /// <returns>The number in the string at the given index as a double.</returns>
        private static double GetNextNumber(string stringContainingNumber, int startIndex, out int stopIndex)
        {
            //Todo: it is possible to have scientific notation for numbers apparently --> make it possible.
            int actualStartIndex   = startIndex;
            int exponentStartIndex = -1;
            int numberEndIndex     = -1;
            int currentIndex       = startIndex;

            //we go past the possible white spaces before the number:
            while (currentIndex < stringContainingNumber.Length && (stringContainingNumber[currentIndex] == ' '))
            {
                ++currentIndex;
            }
            if (currentIndex < stringContainingNumber.Length && (stringContainingNumber[currentIndex] == ','))
            {
                ++currentIndex;
            }
            actualStartIndex = currentIndex; //(got rid of useless spaces and the comma splitting this number and the previous one.)
            int dotIndex = -1;               //apparently, when two numbers follow each other, it is authorized to have no space between them if there is no questionning if they are the same number or not (something like 10..5 is authorized and is the same as 10.0 0.5)

            //if we find a character that does not belong to a number, then the string cannot be parsed (?)
            if (currentIndex >= stringContainingNumber.Length || !_numberCharacters.Contains(stringContainingNumber[currentIndex]))
            {
                throw new IndexOutOfRangeException("Invalid path data or non authorized character found.");
            }
            bool firstChar = true;

            //we find the end of the number
            while (currentIndex < stringContainingNumber.Length && _numberCharacters.Contains(stringContainingNumber[currentIndex]))
            {
                char c = stringContainingNumber[currentIndex];
                if (c == '.')
                {
                    if (dotIndex != -1)
                    {
                        if (dotIndex == currentIndex - 1)
                        {
                            numberEndIndex = currentIndex;
                            break;
                        }
                        else
                        {
                            //we have something like 10.4.5 --> we cannot know which numbers these are
                            throw new FormatException("String badly formatted");
                        }
                    }
                    else
                    {
                        dotIndex = currentIndex;
                    }
                }
                else if ((c == '+' || c == '-') && !firstChar)
                {
                    numberEndIndex = currentIndex;
                    break;
                }
                else if (c == 'E' || c == 'e')
                {
                    //Remember the end of the number before the scientific notation:
                    numberEndIndex = currentIndex;
                    //Read the exponent for scientific notation:
                    ++currentIndex;
                    exponentStartIndex = currentIndex;
                    firstChar          = true;
                    while (currentIndex < stringContainingNumber.Length && _numberCharacters.Contains(stringContainingNumber[currentIndex]))
                    {
                        if (c == '.')
                        {
                            break;
                        }
                        if ((c == '+' || c == '-') && !firstChar)
                        {
                            break;
                        }
                        if ((c == 'E' || c == 'e') && !firstChar)
                        {
                            break;
                        }
                        ++currentIndex;
                    }
                    break;
                }
                firstChar = false;
                ++currentIndex;
            }
            if (exponentStartIndex == -1)
            {
                string numberAsString = stringContainingNumber.Substring(actualStartIndex, currentIndex - actualStartIndex);
                stopIndex = currentIndex;
                return(double.Parse(numberAsString)); //todo: add CultureInfo.InvariantCulture to the parameters once it will be handled correctly.
            }
            else //the number is in scientific notation:
            {
                double basicNumber = 1.0;
                if (actualStartIndex != numberEndIndex) //else, we consider 1 as the basic number (the number is as follows: E-06 so we consider it as if it was 1E-06)
                {
                    string numberAsString = stringContainingNumber.Substring(actualStartIndex, numberEndIndex - actualStartIndex);
                    basicNumber = double.Parse(numberAsString); //todo: add CultureInfo.InvariantCulture to the parameters once it will be handled correctly.
                }
                string exponentAsString = stringContainingNumber.Substring(exponentStartIndex, currentIndex - exponentStartIndex);
                double exponent         = double.Parse(exponentAsString);
                basicNumber *= Math.Pow(10, exponent);
                stopIndex    = currentIndex;
                return(basicNumber);
            }
        }
コード例 #29
0
ファイル: PathGeometry.cs プロジェクト: xiongzhaoxu/CSHTML5
        private void ParseString(string pathAsString)
        {
            //TODO: in this, make a list of the actions to execute on the context, which will be kept. For performance, do not create the Figures while parsing, it should only be made when the user tries to access them.
            int        currentIndex              = 0;
            int        length                    = pathAsString.Length;
            Point      lastAbsolutePosition      = new Point();
            Point      lastStartAbsolutePosition = new Point();
            bool       lastIsCubicBezier         = false;
            bool       lastIsQuadraticBezier     = false;
            Point      lastBezierControlPoint    = new Point();
            PathFigure currentFigure             = null;
            char       c = ' ';

            Figures = new PathFigureCollection();

            while (currentIndex < length)
            {
                while (currentIndex < length && ((c = pathAsString[currentIndex]) == ' '))
                {
                    currentIndex++;
                }
                currentIndex++;
                bool relative = char.IsLower(c);

#if !BRIDGE
                switch (char.ToUpperInvariant(c)) //ToUpperInvariant so that we can handle both uppercase and lowercase in the same case in the switch.
#else
                switch (char.ToUpper(c))          //BRIDGETODO : verify this code matchs the code above
#endif
                {
                case 'F':
                    c = pathAsString[currentIndex];
                    if (c == '0')
                    {
                        FillRule = FillRule.EvenOdd;
                    }
                    else if (c == '1')
                    {
                        FillRule = FillRule.Nonzero;
                    }
                    else
                    {
                        FillRule = FillRule.EvenOdd;
                    }

                    currentIndex++;
                    c = pathAsString[currentIndex];
                    break;

                case 'M':     //move the start of a path figure to a specified position

                    if (currentFigure != null)
                    {
                        Figures.Add(currentFigure);
                    }

                    //we get the point for the move command:
                    Point point = GetPoint(pathAsString, currentIndex, out currentIndex);
                    if (relative)
                    {
                        //we translate the relative coordinates into absolute coordinates:
                        point.X = point.X + lastAbsolutePosition.X;
                        point.Y = point.Y + lastAbsolutePosition.Y;
                    }

                    //we remember this figure's starting position in case it needs to be closed:
                    lastStartAbsolutePosition.X = point.X;
                    lastStartAbsolutePosition.Y = point.Y;

                    //we create the new figure, which will start from the given point, and add it to this.Figures
                    currentFigure            = new PathFigure();
                    currentFigure.Segments   = new PathSegmentCollection();
                    currentFigure.StartPoint = point;

                    //we remember the last position for the case where the next command is in relative coordinates.
                    lastAbsolutePosition.X = point.X;
                    lastAbsolutePosition.Y = point.Y;

                    //if this is followed by points, we should make lines to these:
                    ReadLines(pathAsString, ref currentIndex, ref lastAbsolutePosition, currentFigure, relative);

                    lastIsCubicBezier     = false;
                    lastIsQuadraticBezier = false;


                    break;

                case 'L':                      //line to a specified position
                    if (currentFigure == null) //todo: remove all these tests (I assumed a move command was necessary but it apparently isn't)
                    {
                        throw new FormatException("Path badly formatted: a move command is required before any draw command.");
                    }
                    ReadLines(pathAsString, ref currentIndex, ref lastAbsolutePosition, currentFigure, relative);
                    lastIsCubicBezier     = false;
                    lastIsQuadraticBezier = false;
                    break;

                case 'H':     //horizontal line to a specified position
                    if (currentFigure == null)
                    {
                        throw new FormatException("Path badly formatted: a move command is required before any draw command.");
                    }
                    List <double> numbersForH = ReadNumbers(pathAsString, ref currentIndex);
                    if (numbersForH.Count == 0)
                    {
                        throw new FormatException("String Badly formatted: you cannot have the H or h draw command followed with no numbers.");
                    }
                    PolyLineSegment polyLineSegmentForH = new PolyLineSegment();
                    polyLineSegmentForH.Points = new PointCollection();
                    double Y = lastAbsolutePosition.Y;
                    foreach (double number in numbersForH)
                    {
                        double newX = number;
                        if (relative)
                        {
                            newX += lastAbsolutePosition.X;
                        }
                        polyLineSegmentForH.Points.Add(new Point(newX, Y));
                        lastAbsolutePosition.X = newX;
                    }
                    currentFigure.Segments.Add(polyLineSegmentForH);

                    lastIsCubicBezier     = false;
                    lastIsQuadraticBezier = false;
                    break;

                case 'V':     //vertical line to a specified position
                    if (currentFigure == null)
                    {
                        throw new FormatException("Path badly formatted: a move command is required before any draw command.");
                    }
                    List <double> numbersForV = ReadNumbers(pathAsString, ref currentIndex);
                    if (numbersForV.Count == 0)
                    {
                        throw new FormatException("String Badly formatted: you cannot have the H or h draw command followed with no numbers.");
                    }
                    PolyLineSegment polyLineSegmentForV = new PolyLineSegment();
                    polyLineSegmentForV.Points = new PointCollection();
                    double X = lastAbsolutePosition.X;
                    foreach (double number in numbersForV)
                    {
                        double newY = number;
                        if (relative)
                        {
                            newY += lastAbsolutePosition.Y;
                        }
                        polyLineSegmentForV.Points.Add(new Point(X, newY));
                        lastAbsolutePosition.Y = newY;
                    }
                    currentFigure.Segments.Add(polyLineSegmentForV);
                    lastIsCubicBezier     = false;
                    lastIsQuadraticBezier = false;
                    break;

                case 'C':     //cubic bezier curve
                    while (true)
                    {
                        while (currentIndex < length && pathAsString[currentIndex] == ' ')
                        {
                            ++currentIndex;
                        }
                        if (currentIndex < length && !_commandCharacters.Contains(pathAsString[currentIndex]))
                        {
                            Point controlPoint1 = GetPoint(pathAsString, currentIndex, out currentIndex);
                            Point controlPoint2 = GetPoint(pathAsString, currentIndex, out currentIndex);
                            Point endPoint      = GetPoint(pathAsString, currentIndex, out currentIndex);
                            if (relative)
                            {
                                controlPoint1.X += lastAbsolutePosition.X;
                                controlPoint1.Y += lastAbsolutePosition.Y;
                                controlPoint2.X += lastAbsolutePosition.X;
                                controlPoint2.Y += lastAbsolutePosition.Y;
                                endPoint.X      += lastAbsolutePosition.X;
                                endPoint.Y      += lastAbsolutePosition.Y;
                            }
                            BezierSegment bezierSegment = new BezierSegment();     //note: we do not use polyBezierSegment yet because I don't really know how it works.
                            bezierSegment.Point1   = controlPoint1;
                            bezierSegment.Point2   = controlPoint2;
                            bezierSegment.Point3   = endPoint;
                            lastBezierControlPoint = controlPoint2;
                            lastIsCubicBezier      = true;
                            currentFigure.Segments.Add(bezierSegment);
                            lastAbsolutePosition.X = endPoint.X;
                            lastAbsolutePosition.Y = endPoint.Y;
                        }
                        else
                        {
                            break;
                        }
                    }
                    lastIsQuadraticBezier = false;
                    break;

                case 'S':     //smooth cubic bezier curve
                    while (true)
                    {
                        while (currentIndex < length && pathAsString[currentIndex] == ' ')
                        {
                            ++currentIndex;
                        }
                        if (currentIndex < length && !_commandCharacters.Contains(pathAsString[currentIndex]))
                        {
                            Point controlPoint1 = new Point();
                            if (!lastIsCubicBezier)
                            {
                                controlPoint1 = new Point(lastAbsolutePosition.X, lastAbsolutePosition.Y);
                            }
                            else
                            {
                                Point diffPoint = new Point(lastAbsolutePosition.X - lastBezierControlPoint.X, lastAbsolutePosition.Y - lastBezierControlPoint.Y);
                                controlPoint1 = new Point(lastAbsolutePosition.X + diffPoint.X, lastAbsolutePosition.Y + diffPoint.Y);
                            }
                            Point controlPoint2 = GetPoint(pathAsString, currentIndex, out currentIndex);
                            Point endPoint      = GetPoint(pathAsString, currentIndex, out currentIndex);
                            if (relative)
                            {
                                controlPoint2.X += lastAbsolutePosition.X;
                                controlPoint2.Y += lastAbsolutePosition.Y;
                                endPoint.X      += lastAbsolutePosition.X;
                                endPoint.Y      += lastAbsolutePosition.Y;
                            }
                            BezierSegment bezierSegment = new BezierSegment();     //note: we do not use polyBezierSegment yet because I don't really know how it works.
                            bezierSegment.Point1   = controlPoint1;
                            bezierSegment.Point2   = controlPoint2;
                            bezierSegment.Point3   = endPoint;
                            lastBezierControlPoint = controlPoint2;
                            lastIsCubicBezier      = true;
                            currentFigure.Segments.Add(bezierSegment);
                            lastAbsolutePosition.X = endPoint.X;
                            lastAbsolutePosition.Y = endPoint.Y;
                        }
                        else
                        {
                            break;
                        }
                    }
                    lastIsQuadraticBezier = false;
                    break;

                case 'Q':     //quadratic bezier
                    while (true)
                    {
                        while (currentIndex < length && pathAsString[currentIndex] == ' ')
                        {
                            ++currentIndex;
                        }
                        if (currentIndex < length && !_commandCharacters.Contains(pathAsString[currentIndex]))
                        {
                            Point controlPoint1 = GetPoint(pathAsString, currentIndex, out currentIndex);

                            Point endPoint = GetPoint(pathAsString, currentIndex, out currentIndex);
                            if (relative)
                            {
                                controlPoint1.X += lastAbsolutePosition.X;
                                controlPoint1.Y += lastAbsolutePosition.Y;
                                endPoint.X      += lastAbsolutePosition.X;
                                endPoint.Y      += lastAbsolutePosition.Y;
                            }
                            QuadraticBezierSegment bezierSegment = new QuadraticBezierSegment();
                            bezierSegment.Point1 = controlPoint1;
                            bezierSegment.Point2 = endPoint;
                            currentFigure.Segments.Add(bezierSegment);
                            lastAbsolutePosition.X = endPoint.X;
                            lastAbsolutePosition.Y = endPoint.Y;
                            //we remember the position if the next segment is a smooth quadratic bezier segment.
                            lastBezierControlPoint.X = controlPoint1.X;
                            lastBezierControlPoint.Y = controlPoint1.Y;
                            lastIsCubicBezier        = false;
                            lastIsQuadraticBezier    = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                    lastIsCubicBezier = false;
                    break;

                case 'T':     //smooth quadratic bezier curve
                    while (true)
                    {
                        while (currentIndex < length && pathAsString[currentIndex] == ' ')
                        {
                            ++currentIndex;
                        }
                        if (currentIndex < length && !_commandCharacters.Contains(pathAsString[currentIndex]))
                        {
                            Point controlPoint1 = new Point();
                            if (!lastIsQuadraticBezier)
                            {
                                controlPoint1 = new Point(lastAbsolutePosition.X, lastAbsolutePosition.Y);
                            }
                            else
                            {
                                Point diffPoint = new Point(lastAbsolutePosition.X - lastBezierControlPoint.X, lastAbsolutePosition.Y - lastBezierControlPoint.Y);
                                controlPoint1 = new Point(lastAbsolutePosition.X + diffPoint.X, lastAbsolutePosition.Y + diffPoint.Y);
                            }
                            Point endPoint = GetPoint(pathAsString, currentIndex, out currentIndex);
                            if (relative)
                            {
                                endPoint.X += lastAbsolutePosition.X;
                                endPoint.Y += lastAbsolutePosition.Y;
                            }
                            QuadraticBezierSegment bezierSegment = new QuadraticBezierSegment();
                            bezierSegment.Point1 = controlPoint1;
                            bezierSegment.Point2 = endPoint;
                            currentFigure.Segments.Add(bezierSegment);
                            lastAbsolutePosition.X = endPoint.X;
                            lastAbsolutePosition.Y = endPoint.Y;

                            //we remember the position if the next segment is a smooth quadratic bezier segment.
                            lastBezierControlPoint.X = controlPoint1.X;
                            lastBezierControlPoint.Y = controlPoint1.Y;
                            lastIsCubicBezier        = false;
                            lastIsQuadraticBezier    = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                    lastIsCubicBezier = false;
                    break;

                case 'A':
                    //we ignore this one since we cannot handle it yet
                    //todo: remove the following once arcs will be supported:
                    //if (!CSharpXamlForHtml5.Environment.IsRunningInJavaScript)
                    //{
                    //    if (!_messageAboutArcsAlreadyShown)
                    //    {
                    //        //MessageBox.Show("Arcs are not supported yet. It has been replaced with a line.");
                    //        global::System.Diagnostics.Debug.WriteLine("Arcs are not supported yet. The arc has been replaced with a line.");
                    //        _messageAboutArcsAlreadyShown = true;
                    //    }
                    //}

                    while (true)
                    {
                        while (currentIndex < length && pathAsString[currentIndex] == ' ')
                        {
                            ++currentIndex;
                        }
                        if (currentIndex < length && !_commandCharacters.Contains(pathAsString[currentIndex]))
                        {
                            ArcSegment arc = new ArcSegment();

                            double pointForArcX = GetNextNumber(pathAsString, currentIndex, out currentIndex);
                            double pointForArcY = GetNextNumber(pathAsString, currentIndex, out currentIndex);
                            arc.Size = new Size(pointForArcX, pointForArcY);

                            arc.RotationAngle  = GetNextNumber(pathAsString, currentIndex, out currentIndex);
                            arc.IsLargeArc     = GetNextNumber(pathAsString, currentIndex, out currentIndex) == 1 ? true : false;
                            arc.SweepDirection = GetNextNumber(pathAsString, currentIndex, out currentIndex) == 1 ? SweepDirection.Clockwise : SweepDirection.Counterclockwise;

                            pointForArcX = GetNextNumber(pathAsString, currentIndex, out currentIndex);
                            pointForArcY = GetNextNumber(pathAsString, currentIndex, out currentIndex);
                            Point endPoint = new Point(pointForArcX, pointForArcY);
                            if (relative)
                            {
                                endPoint.X += lastAbsolutePosition.X;
                                endPoint.Y += lastAbsolutePosition.Y;
                            }
                            arc.Point = endPoint;
                            lastAbsolutePosition.X = endPoint.X;
                            lastAbsolutePosition.Y = endPoint.Y;
                            ////todo: remove the following lines and add the arc itself to the figure, instead of the replacement line.
                            //LineSegment replacementLine = new LineSegment();
                            //replacementLine.Point = endPoint;


                            //currentFigure.Segments.Add(replacementLine);
                            currentFigure.Segments.Add(arc);
                        }
                        else
                        {
                            break;
                        }
                    }
                    lastIsCubicBezier     = false;
                    lastIsQuadraticBezier = false;
                    break;

                case 'Z':
                    currentFigure.IsClosed = true;
                    lastAbsolutePosition.X = lastStartAbsolutePosition.X;
                    lastAbsolutePosition.Y = lastStartAbsolutePosition.Y;
                    Figures.Add(currentFigure);
                    currentFigure         = null; //so that we do not add it again when reaching a Move command for the next figure.
                    lastIsCubicBezier     = false;
                    lastIsQuadraticBezier = false;
                    break;

                default:
                    break;
                }
            }
            if (currentFigure != null)
            {
                Figures.Add(currentFigure);
            }
        }
コード例 #30
0
ファイル: PdfA2Checker.cs プロジェクト: tbrion/itextsharp
 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
     {
     }
 }
コード例 #31
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--);
     }
 }
コード例 #32
0
ファイル: PdfA2Checker.cs プロジェクト: smartleos/itextsharp
        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 {

            }
        }
コード例 #33
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;
 }
コード例 #34
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--);
                }
        }
コード例 #35
0
ファイル: PdfA1Checker.cs プロジェクト: tomaszmat/code
 protected override void CheckAnnotation(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is PdfFormField)
     {
         PdfFormField field = (PdfFormField)obj1;
         if (!field.Contains(PdfName.SUBTYPE))
         {
             return;
         }
         if (field.Contains(PdfName.AA) || field.Contains(PdfName.A))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("widget.annotation.dictionary.or.field.dictionary.shall.not.include.a.or.aa.entry"));
         }
     }
     if (obj1 is PdfAnnotation)
     {
         PdfAnnotation annot   = (PdfAnnotation)obj1;
         PdfName       subtype = annot.Get(PdfName.SUBTYPE) as PdfName;
         if (subtype != null && !allowedAnnotTypes.Contains(subtype))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("annotation.type.1.not.allowed", subtype.ToString()));
         }
         PdfNumber ca = annot.GetAsNumber(PdfName.CA);
         if (ca != null && ca.FloatValue != 1.0)
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("an.annotation.dictionary.shall.not.contain.the.ca.key.with.a.value.other.than.1"));
         }
         PdfNumber f = annot.GetAsNumber(PdfName.F);
         if (f == null)
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("an.annotation.dictionary.shall.contain.the.f.key"));
         }
         int flags = f.IntValue;
         if (CheckFlag(flags, PdfAnnotation.FLAGS_PRINT) == false || CheckFlag(flags, PdfAnnotation.FLAGS_HIDDEN) ||
             CheckFlag(flags, PdfAnnotation.FLAGS_INVISIBLE) || CheckFlag(flags, PdfAnnotation.FLAGS_NOVIEW))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.f.keys.print.flag.bit.shall.be.set.to.1.and.its.hidden.invisible.and.noview.flag.bits.shall.be.set.to.0"));
         }
         if (PdfName.TEXT.Equals(annot.GetAsName(PdfName.SUBTYPE)))
         {
             if (CheckFlag(flags, PdfAnnotation.FLAGS_NOZOOM) == false || CheckFlag(flags, PdfAnnotation.FLAGS_NOROTATE) == false)
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("text.annotations.should.set.the.nozoom.and.norotate.flag.bits.of.the.f.key.to.1"));
             }
         }
         if (annot.Contains(PdfName.C) || annot.Contains(PdfName.IC))
         {
             ICC_Profile colorProfile = ((PdfAWriter)writer).ColorProfile;
             String      cs           = "";
             cs = System.Text.Encoding.ASCII.GetString(colorProfile.Data, 16, 4);
             if (!"RGB".Equals(cs.ToUpper()))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("destoutputprofile.in.the.pdfa1.outputintent.dictionary.shall.be.rgb"));
             }
         }
         PdfDictionary ap = GetDirectDictionary(annot.Get(PdfName.AP));
         if (ap != null)
         {
             if (ap.Contains(PdfName.R) || ap.Contains(PdfName.D))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("appearance.dictionary.shall.contain.only.the.n.key.with.stream.value"));
             }
             PdfObject n = ap.Get(PdfName.N);
             if (!(n is PdfIndirectReference))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("appearance.dictionary.shall.contain.only.the.n.key.with.stream.value"));
             }
         }
         if (PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)) && (annot.Contains(PdfName.AA) || annot.Contains(PdfName.A)))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("widget.annotation.dictionary.or.field.dictionary.shall.not.include.a.or.aa.entry"));
         }
         if (CheckStructure(conformanceLevel))
         {
             if (contentAnnotations.Contains(subtype) && !annot.Contains(PdfName.CONTENTS))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("annotation.of.type.1.should.have.contents.key", subtype.ToString()));
             }
         }
     }
 }
コード例 #36
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;
        }
コード例 #37
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);
            }
        }
コード例 #38
0
        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);
            }
        }