Example #1
0
 /// <summary>
 /// Reads the next symbol that must be the specified one.
 /// </summary>
 Symbol ReadSymbol(Symbol symbol)
 {
   Symbol current = this.lexer.ScanNextToken();
   if (symbol != current)
     throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
   return current;
 }
Example #2
0
        /// <summary>
        /// Checks whether a color mode and a color match.
        /// </summary>
        public static XColor EnsureColorMode(PdfColorMode colorMode, XColor color)
        {
#if true
            if (colorMode == PdfColorMode.Rgb && color.ColorSpace != XColorSpace.Rgb)
            {
                return(XColor.FromArgb((int)(color.A * 255), color.R, color.G, color.B));
            }

            if (colorMode == PdfColorMode.Cmyk && color.ColorSpace != XColorSpace.Cmyk)
            {
                return(XColor.FromCmyk(color.A, color.C, color.M, color.Y, color.K));
            }

            return(color);
#else
            if (colorMode == PdfColorMode.Rgb && color.ColorSpace != XColorSpace.Rgb)
            {
                throw new InvalidOperationException(PSSR.InappropriateColorSpace(colorMode, color.ColorSpace));
            }

            if (colorMode == PdfColorMode.Cmyk && color.ColorSpace != XColorSpace.Cmyk)
            {
                throw new InvalidOperationException(PSSR.InappropriateColorSpace(colorMode, color.ColorSpace));
            }
#endif
        }
Example #3
0
        // Useful stuff here: http://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code
        XImage(string path)
        {
            path = Path.GetFullPath(path);
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(PSSR.FileNotFound(path));
            }
            //throw new FileNotFoundException(PSSR.FileNotFound(path), path);

            _path = path;

            //FileStream file = new FileStream(filename, FileMode.Open);
            //BitsLength = (int)file.Length;
            //Bits = new byte[BitsLength];
            //file.Read(Bits, 0, BitsLength);
            //file.Close();
            try
            {
                Lock.EnterGdiPlus();
                _gdiImage = Image.FromFile(path);
            }
            finally { Lock.ExitGdiPlus(); }

#if true_
            float        vres  = image.VerticalResolution;
            float        hres  = image.HorizontalResolution;
            SizeF        size  = image.PhysicalDimension;
            int          flags = image.Flags;
            Size         sz    = image.Size;
            GraphicsUnit units = GraphicsUnit.Millimeter;
            RectangleF   rect  = image.GetBounds(ref units);
            int          width = image.Width;
#endif
            Initialize();
        }
Example #4
0
        /// <summary>
        /// Initializes a new instance of the XPdfForm class from the specified path to an external PDF document.
        /// Although PDFsharp internally caches XPdfForm objects it is recommended to reuse XPdfForm objects
        /// in your code and change the PageNumber property if more than one page is needed form the external
        /// document. Furthermore, because XPdfForm can occupy very much memory, it is recommended to
        /// dispose XPdfForm objects if not needed anymore.
        /// </summary>
        internal XPdfForm(string path)
        {
            int pageNumber;

            path = ExtractPageNumber(path, out pageNumber);

#if !NETFX_CORE && !PORTABLE
            path = Path.GetFullPath(path);
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(PSSR.FileNotFound(path));
            }
#endif

            if (PdfReader.TestPdfFile(path) == 0)
            {
                throw new ArgumentException("The specified file has no valid PDF file header.", "path");
            }

            _path = path;
            if (pageNumber != 0)
            {
                PageNumber = pageNumber;
            }
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        PdfTrailer ReadXRefTableAndTrailer(PdfReferenceTable xrefTable)
        {
            Debug.Assert(xrefTable != null);

            Symbol symbol = ScanNextToken();

            // Is it an xref stream?
            if (symbol == Symbol.Integer)
            {
                throw new PdfReaderException(PSSR.CannotHandleXRefStreams);
            }
            // TODO: It is very high on the todo list, but still undone
            Debug.Assert(symbol == Symbol.XRef);
            while (true)
            {
                symbol = ScanNextToken();
                if (symbol == Symbol.Integer)
                {
                    int start  = this.lexer.TokenToInteger;
                    int length = ReadInteger();
                    for (int id = start; id < start + length; id++)
                    {
                        int position   = ReadInteger();
                        int generation = ReadInteger();
                        ReadSymbol(Symbol.Keyword);
                        string token = lexer.Token;
                        // Skip start entry
                        if (id == 0)
                        {
                            continue;
                        }
                        // Skip unused entries.
                        if (token != "n")
                        {
                            continue;
                        }
                        // Even it is restricted, an object can exists in more than one subsection.
                        // (PDF Reference Implementation Notes 15).
                        PdfObjectID objectID = new PdfObjectID(id, generation);
                        // Ignore the latter one
                        if (xrefTable.Contains(objectID))
                        {
                            continue;
                        }
                        xrefTable.Add(new PdfReference(objectID, position));
                    }
                }
                else if (symbol == Symbol.Trailer)
                {
                    ReadSymbol(Symbol.BeginDictionary);
                    PdfTrailer trailer = new PdfTrailer(this.document);
                    this.ReadDictionary(trailer, false);
                    return(trailer);
                }
                else
                {
                    throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
                }
            }
        }
Example #6
0
 static void CheckByte(int val, string name)
 {
     if (val < 0 || val > 0xFF)
     {
         throw new ArgumentException(PSSR.InvalidValue(val, name, 0, 255));
     }
 }
Example #7
0
 /// <summary>
 /// Reads the next token that must be the specified one.
 /// </summary>
 Symbol ReadToken(string token)
 {
   Symbol current = this.lexer.ScanNextToken();
   if (token != this.lexer.Token)
     throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
   return current;
 }
Example #8
0
        /// <summary>
        /// Create the font image using WPF functionality.
        /// </summary>
        void CreateWpfFontData(XFont font, XPdfFontOptions options)
        {
            GlyphTypeface glyphTypeface;

            if (!font.typeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(font.Name));
            }

            Stream fontStream = null;

            try
            {
                fontStream = glyphTypeface.GetFontStream();
                int size = (int)fontStream.Length;
                Debug.Assert(size > 0);
                this.data = new byte[size];
                fontStream.Read(this.data, 0, size);
            }
            finally
            {
                if (fontStream != null)
                {
                    fontStream.Close();
                }
            }
        }
Example #9
0
 /// <summary>
 /// Reads a name from the PDF data stream. The preceding slash is part of the result string.
 /// </summary>
 string ReadName()
 {
   string name;
   Symbol symbol = ScanNextToken(out name);
   if (symbol != Symbol.Name)
     throw new PdfReaderException(PSSR.UnexpectedToken(name));
   return name;
 }
        /// <summary>
        /// Create a WPF GlyphTypeface and retrieve font data from it.
        /// </summary>
        internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions,
                                                     out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey)
        {
            if (string.IsNullOrEmpty(typefaceKey))
            {
                typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
            }
            XFontStyle style = fontResolvingOptions.FontStyle;

#if DEBUG
            if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0 &&
                (style & XFontStyle.BoldItalic) == XFontStyle.Italic)
            {
                familyName.GetType();
            }
#endif

            // Use WPF technique to create font data.
            wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily);
#if DEBUG__
            if (wpfTypeface != null)
            {
                WpfGlyphTypeface          glyphTypeface;
                ICollection <WpfTypeface> list = wpfFontFamily.GetTypefaces();
                foreach (WpfTypeface tf in list)
                {
                    if (!tf.TryGetGlyphTypeface(out glyphTypeface))
                    {
                        Debug - Break.Break();
                    }
                }

                //if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface))
                //    throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }
#endif
            if (wpfFontFamily == null)
            {
                wpfFontFamily = new WpfFontFamily(familyName);
            }

            if (wpfTypeface == null)
            {
                wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style);
            }

            // Let WPF choose the right glyph typeface.
            if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface))
            {
                throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }

            // Get or create the font source and cache it unter the specified typeface key.
            XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface);
            return(fontSource);
        }
Example #11
0
        /// <summary>
        /// Reads the next symbol that must be the specified one.
        /// </summary>
        Symbol ReadSymbol(Symbol symbol)
        {
            Symbol current = lexer.ScanNextToken();

            if (symbol != current)
            {
                throw new PdfReaderException(PSSR.UnexpectedToken(lexer.Token));
            }
            return(current);
        }
Example #12
0
        /// <summary>
        /// Reads the next symbol that must be the specified one.
        /// </summary>
        CSymbol ReadSymbol(CSymbol symbol)
        {
            CSymbol current = this.lexer.ScanNextToken();

            if (symbol != current)
            {
                throw new ContentReaderException(PSSR.UnexpectedToken(this.lexer.Token));
            }
            return(current);
        }
Example #13
0
        /// <summary>
        /// Reads the next token that must be the specified one.
        /// </summary>
        Symbol ReadToken(string token)
        {
            Symbol current = lexer.ScanNextToken();

            if (token != lexer.Token)
            {
                throw new PdfReaderException(PSSR.UnexpectedToken(lexer.Token));
            }
            return(current);
        }
Example #14
0
        /// <summary>
        /// Reads the next symbol that must be the specified one.
        /// </summary>
        CSymbol ReadSymbol(CSymbol symbol)
        {
            CSymbol current = _lexer.ScanNextToken();

            if (symbol != current)
            {
                ContentReaderDiagnostics.ThrowContentReaderException(PSSR.UnexpectedToken(_lexer.Token));
            }
            return(current);
        }
Example #15
0
        // Useful stuff here: http://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code
        XImage(string path)
        {
#if !NETFX_CORE && !UWP
            path = Path.GetFullPath(path);
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(PSSR.FileNotFound(path));
            }
            //throw new FileNotFoundException(PSSR.FileNotFound(path), path);
#endif
            _path = path;

            //FileStream file = new FileStream(filename, FileMode.Open);
            //BitsLength = (int)file.Length;
            //Bits = new byte[BitsLength];
            //file.Read(Bits, 0, BitsLength);
            //file.Close();
#if CORE_WITH_GDI || GDI
            try
            {
                Lock.EnterGdiPlus();
                _gdiImage = Image.FromFile(path);
            }
            finally { Lock.ExitGdiPlus(); }
#endif
#if WPF && !SILVERLIGHT
            //BitmapSource.Create()
            // BUG: BitmapImage locks the file
            //_wpfImage = new BitmapImage(new Uri(path));  // AGHACK
            // Suggested change from forum to prevent locking.
            _wpfImage = BitmapFromUri(new Uri(path));
#endif
#if WPF && SILVERLIGHT
            //BitmapSource.Create()
            // BUG: BitmapImage locks the file
            //_wpfImage = new BitmapImage(new Uri(path));  // AGHACK
            //Debug-Break.Break();
#endif

#if true_
            float        vres  = image.VerticalResolution;
            float        hres  = image.HorizontalResolution;
            SizeF        size  = image.PhysicalDimension;
            int          flags = image.Flags;
            Size         sz    = image.Size;
            GraphicsUnit units = GraphicsUnit.Millimeter;
            RectangleF   rect  = image.GetBounds(ref units);
            int          width = image.Width;
#endif
            Initialize();
        }
Example #16
0
    /// <summary>
    /// Initializes a new instance of the XPdfForm class from the specified path to an external PDF document.
    /// Although PDFsharp internally caches XPdfForm objects it is recommended to reuse XPdfForm objects
    /// in your code and change the PageNumber property if more than one page is needed form the external
    /// document. Furthermore, because XPdfForm can occupy very much memory, it is recommended to
    /// dispose XPdfForm objects if not needed anymore.
    /// </summary>
    internal XPdfForm(string path)
    {
      int pageNumber;
      path = ExtractPageNumber(path, out pageNumber);

      path = Path.GetFullPath(path);
      if (!File.Exists(path))
        throw new FileNotFoundException(PSSR.FileNotFound(path), path);

      if (PdfReader.TestPdfFile(path) == 0)
        throw new ArgumentException("The specified file has no valid PDF file header.", "path");

      this.path = path;
      if (pageNumber != 0)
        PageNumber = pageNumber;
    }
Example #17
0
    /*
        /// <summary>
        /// Reads a string immediately or (optionally) indirectly from the PDF data stream.
        /// </summary>
        protected string ReadString(bool canBeIndirect)
        {
          Symbol symbol = Symbol.None; //this.lexer.ScanNextToken(canBeIndirect);
          if (symbol == Symbol.String || symbol == Symbol.HexString)
            return this.lexer.Token;
          else if (symbol == Symbol.R)
          {
            int position = this.lexer.Position;
            MoveToObject(this.lexer.Token);
            ReadObjectID(null);
            string s = ReadString();
            ReadSymbol(Symbol.EndObj);
            this.lexer.Position = position;
            return s;
          }
          throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
        }

        protected string ReadString()
        {
          return ReadString(false);
        }

        /// <summary>
        /// Reads a string immediately or (optionally) indirectly from the PDF data stream.
        /// </summary>
        protected bool ReadBoolean(bool canBeIndirect)
        {
          Symbol symbol = this.lexer.ScanNextToken(canBeIndirect);
          if (symbol == Symbol.Boolean)
            return this.lexer.TokenToBoolean;
          else if (symbol == Symbol.R)
          {
            int position = this.lexer.Position;
            MoveToObject(this.lexer.Token);
            ReadObjectID(null);
            bool b = ReadBoolean();
            ReadSymbol(Symbol.EndObj);
            this.lexer.Position = position;
            return b;
          }
          throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
        }

        protected bool ReadBoolean()
        {
          return ReadBoolean(false);
        }
    */
    /// <summary>
    /// Reads an integer value directly from the PDF data stream.
    /// </summary>
    int ReadInteger(bool canBeIndirect)
    {
      Symbol symbol = this.lexer.ScanNextToken();
      if (symbol == Symbol.Integer)
        return this.lexer.TokenToInteger;
      else if (symbol == Symbol.R)
      {
        int position = this.lexer.Position;
        //        MoveToObject(this.lexer.Token);
        ReadObjectID(null);
        int n = ReadInteger();
        ReadSymbol(Symbol.EndObj);
        this.lexer.Position = position;
        return n;
      }
      throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
    }
Example #18
0
        XImage(string path)
        {
            path = Path.GetFullPath(path);
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(PSSR.FileNotFound(path), path);
            }

            this.path = path;

            //FileStream file = new FileStream(filename, FileMode.Open);
            //BitsLength = (int)file.Length;
            //Bits = new byte[BitsLength];
            //file.Read(Bits, 0, BitsLength);
            //file.Close();
#if GDI
            this.gdiImage = Image.FromFile(path);
#endif
#if WPF && !SILVERLIGHT
            //BitmapSource.Create()
            // BUG: BitmapImage locks the file
            this.wpfImage = new BitmapImage(new Uri(path)); // AGHACK
#endif

#if __IOS__
            this.iosImage = UIImage.FromFile(path);
#endif

#if false
            float        vres  = this.image.VerticalResolution;
            float        hres  = this.image.HorizontalResolution;
            SizeF        size  = this.image.PhysicalDimension;
            int          flags = this.image.Flags;
            Size         sz    = this.image.Size;
            GraphicsUnit units = GraphicsUnit.Millimeter;
            RectangleF   rect  = this.image.GetBounds(ref units);
            int          width = this.image.Width;
#endif
            Initialize();
        }
Example #19
0
        /// <summary>
        /// Initializes a new instance of the XPdfForm class from the specified path to an external PDF document.
        /// Although PDFsharp internally caches XPdfForm objects it is recommended to reuse XPdfForm objects
        /// in your code and change the PageNumber property if more than one page is needed form the external
        /// document. Furthermore, because XPdfForm can occupy very much memory, it is recommended to
        /// dispose XPdfForm objects if not needed anymore.
        /// </summary>
        internal XPdfForm(string path, PdfReadAccuracy accuracy)
        {
            int pageNumber;

            path = ExtractPageNumber(path, out pageNumber);

            path = Path.GetFullPath(path);
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(PSSR.FileNotFound(path));
            }

            if (PdfReader.TestPdfFile(path) == 0)
            {
                throw new ArgumentException("The specified file has no valid PDF file header.", "path");
            }

            _path             = path;
            _pathReadAccuracy = accuracy;
            if (pageNumber != 0)
            {
                PageNumber = pageNumber;
            }
        }
Example #20
0
 static PdfDocument()
 {
     PSSR.TestResourceMessages();
     //string test = PSSR.ResMngr.GetString("SampleMessage1");
     //test.GetType();
 }
Example #21
0
        internal PdfFormXObject(PdfDocument thisDocument, PdfImportedObjectTable importedObjectTable, XPdfForm form)
            : base(thisDocument)
        {
            Debug.Assert(ReferenceEquals(thisDocument, importedObjectTable.Owner));
            Elements.SetName(Keys.Type, "/XObject");
            Elements.SetName(Keys.Subtype, "/Form");

            if (form.IsTemplate)
            {
                Debug.Assert(importedObjectTable == null);
                // TODO more initialization here???
                return;
            }
            Debug.Assert(importedObjectTable != null);

            XPdfForm pdfForm = form;
            // Get import page
            PdfPages importPages = importedObjectTable.ExternalDocument.Pages;

            if (pdfForm.PageNumber < 1 || pdfForm.PageNumber > importPages.Count)
            {
                PSSR.ImportPageNumberOutOfRange(pdfForm.PageNumber, importPages.Count, form._path);
            }
            PdfPage importPage = importPages[pdfForm.PageNumber - 1];

            // Import resources
            PdfItem res = importPage.Elements["/Resources"];

            if (res != null) // unlikely but possible
            {
#if true
                // Get root object
                PdfObject root;
                if (res is PdfReference)
                {
                    root = ((PdfReference)res).Value;
                }
                else
                {
                    root = (PdfDictionary)res;
                }

                root = ImportClosure(importedObjectTable, thisDocument, root);
                // If the root was a direct object, make it indirect.
                if (root.Reference == null)
                {
                    thisDocument._irefTable.Add(root);
                }

                Debug.Assert(root.Reference != null);
                Elements["/Resources"] = root.Reference;
#else
                // Get transitive closure
                PdfObject[] resources = importPage.Owner.Internals.GetClosure(resourcesRoot);
                int         count     = resources.Length;
#if DEBUG_
                for (int idx = 0; idx < count; idx++)
                {
                    Debug.Assert(resources[idx].XRef != null);
                    Debug.Assert(resources[idx].XRef.Document != null);
                    Debug.Assert(resources[idx].Document != null);
                    if (resources[idx].ObjectID.ObjectNumber == 12)
                    {
                        GetType();
                    }
                }
#endif
                // 1st step. Already imported objects are reused and new ones are cloned.
                for (int idx = 0; idx < count; idx++)
                {
                    PdfObject obj = resources[idx];
                    if (importedObjectTable.Contains(obj.ObjectID))
                    {
                        // external object was already imported
                        PdfReference iref = importedObjectTable[obj.ObjectID];
                        Debug.Assert(iref != null);
                        Debug.Assert(iref.Value != null);
                        Debug.Assert(iref.Document == Owner);
                        // replace external object by the already clone counterpart
                        resources[idx] = iref.Value;
                    }
                    else
                    {
                        // External object was not imported ealier and must be cloned
                        PdfObject clone = obj.Clone();
                        Debug.Assert(clone.Reference == null);
                        clone.Document = Owner;
                        if (obj.Reference != null)
                        {
                            // add it to this (the importer) document
                            Owner.irefTable.Add(clone);
                            Debug.Assert(clone.Reference != null);
                            // save old object identifier
                            importedObjectTable.Add(obj.ObjectID, clone.Reference);
                            //Debug.WriteLine("Cloned: " + obj.ObjectID.ToString());
                        }
                        else
                        {
                            // The root object (the /Resources value) is not an indirect object
                            Debug.Assert(idx == 0);
                            // add it to this (the importer) document
                            Owner.irefTable.Add(clone);
                            Debug.Assert(clone.Reference != null);
                        }
                        // replace external object by its clone
                        resources[idx] = clone;
                    }
                }
#if DEBUG_
                for (int idx = 0; idx < count; idx++)
                {
                    Debug.Assert(resources[idx].XRef != null);
                    Debug.Assert(resources[idx].XRef.Document != null);
                    Debug.Assert(resources[idx].Document != null);
                    if (resources[idx].ObjectID.ObjectNumber == 12)
                    {
                        GetType();
                    }
                }
#endif

                // 2nd step. Fix up indirect references that still refers to the import document.
                for (int idx = 0; idx < count; idx++)
                {
                    PdfObject obj = resources[idx];
                    Debug.Assert(obj.Owner != null);
                    FixUpObject(importedObjectTable, importedObjectTable.Owner, obj);
                }

                // Set resources key to the root of the clones
                Elements["/Resources"] = resources[0].Reference;
#endif
            }

            // Take /Rotate into account
            PdfRectangle rect   = importPage.Elements.GetRectangle(PdfPage.Keys.MediaBox);
            int          rotate = importPage.Elements.GetInteger(PdfPage.Keys.Rotate);
            //rotate = 0;
            if (rotate == 0)
            {
                // Set bounding box to media box
                Elements["/BBox"] = rect;
            }
            else
            {
                // TODO: Have to adjust bounding box? (I think not, but I'm not sure -> wait for problem)
                Elements["/BBox"] = rect;

                // Rotate the image such that it is upright
                XMatrix matrix = new XMatrix();
                double  width  = rect.Width;
                double  height = rect.Height;
                matrix.RotateAtPrepend(-rotate, new XPoint(width / 2, height / 2));

                if (rotate != 180)
                {
                    // Translate the image such that its center lies on the center of the rotated bounding box
                    double offset = (height - width) / 2;
                    if (height > width)
                    {
                        matrix.TranslatePrepend(offset, offset);
                    }
                    else
                    {
                        matrix.TranslatePrepend(-offset, -offset);
                    }
                }

                //string item = "[" + PdfEncoders.ToString(matrix) + "]";
                //Elements[Keys.Matrix] = new PdfLiteral(item);
                Elements.SetMatrix(Keys.Matrix, matrix);
            }

            // Preserve filter because the content keeps unmodified
            PdfContent content = importPage.Contents.CreateSingleContent();
#if !DEBUG
            content.Compressed = true;
#endif
            PdfItem filter = content.Elements["/Filter"];
            if (filter != null)
            {
                Elements["/Filter"] = filter.Clone();
            }

            // (no cloning needed because the bytes keep untouched)
            Stream = content.Stream; // new PdfStream(bytes, this);
            Elements.SetInteger("/Length", content.Stream.Value.Length);
        }
Example #22
0
        /// <summary>
        /// Reads PDF object from input stream.
        /// </summary>
        /// <param name="pdfObject">Either the instance of a derived type or null. If it is null
        /// an appropriate object is created.</param>
        /// <param name="objectID">The address of the object.</param>
        /// <param name="includeReferences">If true, specifies that all indirect objects
        /// are included recursively.</param>
        public PdfObject ReadObject(PdfObject pdfObject, PdfObjectID objectID, bool includeReferences)
        {
            MoveToObject(objectID);
            int objectNumber     = ReadInteger();
            int generationNumber = ReadInteger();

#if DEBUG
            // The following assertion sometime failed (see below)
            //Debug.Assert(objectID == new PdfObjectID(objectNumber, generationNumber));
            if (objectID != new PdfObjectID(objectNumber, generationNumber))
            {
                // A special kind of bug? Or is this an undocumented PDF feature?
                // PDF4NET 2.6 provides a sample called 'Unicode', which produces a file 'unicode.pdf'
                // The iref table of this file contains the following entries:
                //    iref
                //    0 148
                //    0000000000 65535 f
                //    0000000015 00000 n
                //    0000000346 00000 n
                //    ....
                //    0000083236 00000 n
                //    0000083045 00000 n
                //    0000083045 00000 n
                //    0000083045 00000 n
                //    0000083045 00000 n
                //    0000080334 00000 n
                //    ....
                // Object 84, 85, 86, and 87 maps to the same dictionary, but all PDF readers I tested
                // ignores this mismatch! The following assertion failed about 50 times with this file.
#if true_
                string message = String.Format("xref entry {0} {1} maps to object {2} {3}.",
                                               objectID.ObjectNumber, objectID.GenerationNumber, objectNumber, generationNumber);
                Debug.Assert(false, message);
#endif
            }
#endif
            // Always use object ID from iref table (see above)
            objectNumber     = objectID.ObjectNumber;
            generationNumber = objectID.GenerationNumber;
#if true_
            Debug.WriteLine(String.Format("obj: {0} {1}", objectNumber, generationNumber));
#endif
            ReadSymbol(Symbol.Obj);

            bool   checkForStream = false;
            Symbol symbol         = ScanNextToken();
            switch (symbol)
            {
            case Symbol.BeginArray:
                PdfArray array;
                if (pdfObject == null)
                {
                    array = new PdfArray(this.document);
                }
                else
                {
                    array = (PdfArray)pdfObject;
                }
                //PdfObject.RegisterObject(array, objectID, generation);
                pdfObject = ReadArray(array, includeReferences);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                break;

            case Symbol.BeginDictionary:
                PdfDictionary dict;
                if (pdfObject == null)
                {
                    dict = new PdfDictionary(this.document);
                }
                else
                {
                    dict = (PdfDictionary)pdfObject;
                }
                //PdfObject.RegisterObject(dict, objectID, generation);
                checkForStream = true;
                pdfObject      = ReadDictionary(dict, includeReferences);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                break;

            // Acrobat 6 Professional proudly presents: The Null object!
            // Even with a one-digit object number an indirect reference �x 0 R� to this object is
            // one character larger than the direct use of �null�. Probable this is the reason why
            // it is true that Acrobat Web Capture 6.0 creates this object, but obviously never
            // creates a reference to it!
            case Symbol.Null:
                pdfObject = new PdfNullObject(this.document);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.Boolean:
                pdfObject = new PdfBooleanObject(this.document, string.Compare(this.lexer.Token, Boolean.TrueString, true) == 0); //!!!mod THHO 19.11.09
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.Integer:
                pdfObject = new PdfIntegerObject(this.document, this.lexer.TokenToInteger);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.UInteger:
                pdfObject = new PdfUIntegerObject(this.document, this.lexer.TokenToUInteger);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.Real:
                pdfObject = new PdfRealObject(this.document, this.lexer.TokenToReal);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.String:
                pdfObject = new PdfStringObject(this.document, this.lexer.Token);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.Name:
                pdfObject = new PdfNameObject(this.document, this.lexer.Token);
                pdfObject.SetObjectID(objectNumber, generationNumber);
                ReadSymbol(Symbol.EndObj);
                return(pdfObject);

            case Symbol.Keyword:
                // Should not come here anymore
                throw new NotImplementedException("Keyword");

            default:
                // Should not come here anymore
                throw new NotImplementedException("unknown token \"" + symbol + "\"");
            }
            symbol = ScanNextToken();
            if (symbol == Symbol.BeginStream)
            {
                PdfDictionary dict = (PdfDictionary)pdfObject;
                Debug.Assert(checkForStream, "Unexpected stream...");
                int    length = GetStreamLength(dict);
                byte[] bytes  = this.lexer.ReadStream(length);
#if true_
                if (dict.Elements.GetString("/Filter") == "/FlateDecode")
                {
                    if (dict.Elements["/Subtype"] == null)
                    {
                        try
                        {
                            byte[] decoded = Filtering.FlateDecode.Decode(bytes);
                            if (decoded.Length == 0)
                            {
                                goto End;
                            }
                            string pageContent = Filtering.FlateDecode.DecodeToString(bytes);
                            if (pageContent.Length > 100)
                            {
                                pageContent = pageContent.Substring(pageContent.Length - 100);
                            }
                            pageContent.GetType();
                            bytes = decoded;
                            dict.Elements.Remove("/Filter");
                            dict.Elements.SetInteger("/Length", bytes.Length);
                        }
                        catch
                        {
                        }
                    }
                    End :;
                }
#endif
                PdfDictionary.PdfStream stream = new PdfDictionary.PdfStream(bytes, dict);
                dict.Stream = stream;
                ReadSymbol(Symbol.EndStream);
                symbol = ScanNextToken();
            }
            if (symbol != Symbol.EndObj)
            {
                throw new PdfReaderException(PSSR.UnexpectedToken(this.lexer.Token));
            }
            return(pdfObject);
        }
Example #23
0
        /// <summary>
        /// Connects the specifications of a font from XFont to a real glyph type face.
        /// </summary>
        void Initialize()
        {
            XFontMetrics fm = null;

#if DEBUG___
            FontData[] fontDataArray = FontDataStock.Global.GetFontDataList();
            if (fontDataArray.Length > 0)
            {
                ////        GetType();
                ////#if GDI
                ////        var x = XPrivateFontCollection.global.GlobalPrivateFontCollection;
                ////        families = x.Families;

                ////        bool fff = families[0].IsStyleAvailable(System.Drawing.FontStyle.Regular);
                ////        fff.GetType();
                ////        this.font = new Font(families[0].Name, 12, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);

                ////        this.font = new Font("Oblivious", 12, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);

                ////        this.font = new Font(families[0], 12, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);

                ////        System.Drawing.FontFamily f = new System.Drawing.FontFamily(families[0].Name);
                ////        f.GetType();
                ////#endif
            }
#endif
#if GDI
            if (this.font == null)
            {
                if (this.gdifamily != null)
                {
                    this.font       = new Font(this.gdifamily, (float)this.emSize, (System.Drawing.FontStyle) this.style, GraphicsUnit.World);
                    this.familyName = this.gdifamily.Name; // Do we need this???
                }
                else
                {
                    // First check private fonts
                    this.font = XPrivateFontCollection.TryFindPrivateFont(this.familyName, this.emSize, (System.Drawing.FontStyle) this.style) ??
                                new Font(this.familyName, (float)this.emSize, (System.Drawing.FontStyle) this.style, GraphicsUnit.World);
                }
#if DEBUG
                // new Font returns MSSansSerif if the requested font was not found ...
                //Debug.Assert(this.familyName == this.font.FontFamily.Name);
#endif
            }

            fm = Metrics;
            System.Drawing.FontFamily fontFamily = this.font.FontFamily;
            this.unitsPerEm = fm.UnitsPerEm;

            System.Drawing.FontFamily fontFamily2 = this.font.FontFamily;
            this.cellSpace = fontFamily2.GetLineSpacing(font.Style);
            //Debug.Assert(this.cellSpace == fm.Ascent + Math.Abs(fm.Descent) + fm.Leading, "Value differs from information retrieved from font image.");

            this.cellAscent = fontFamily.GetCellAscent(font.Style);
#pragma warning disable 1030
#warning delTHHO
            //!!!delTHHO 14.08.2008 Debug.Assert(this.cellAscent == fm.Ascent, "Value differs from information retrieved from font image.");
            //Debug.Assert(this.cellAscent == fm.Ascent, "Value differs from information retrieved from font image.");

            this.cellDescent = fontFamily.GetCellDescent(font.Style);
#if DEBUG
            int desc = Math.Abs(fm.Descent);
            if (this.cellDescent != desc)
            {
                Debug.Assert(false, "Value differs from information retrieved from font image.");
            }
#endif
#endif
#if WPF
#if !SILVERLIGHT
            if (this.family == null)
            {
                Debug.Assert(this.typeface == null);
                this.typeface = XPrivateFontCollection.TryFindTypeface(Name, this.style, out this.family);
#if true
                if (this.typeface != null)
                {
                    GlyphTypeface glyphTypeface;

                    ICollection <Typeface> list = this.family.GetTypefaces();
                    foreach (Typeface tf in list)
                    {
                        if (!tf.TryGetGlyphTypeface(out glyphTypeface))
                        {
                            Debugger.Break();
                        }
                    }

                    if (!this.typeface.TryGetGlyphTypeface(out glyphTypeface))
                    {
                        throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(Name));
                    }
                }
#endif
            }

            if (this.family == null)
            {
                this.family = new System.Windows.Media.FontFamily(Name);
            }

            if (typeface == null)
            {
                this.typeface = FontHelper.CreateTypeface(this.family, style);
            }

            fm = Metrics;
            Debug.Assert(this.unitsPerEm == 0 || this.unitsPerEm == fm.UnitsPerEm);
            this.unitsPerEm = fm.UnitsPerEm;

            //Debug.Assert(this.cellSpace == 0 || this.cellSpace == fm.Ascent + Math.Abs(fm.Descent) + fm.Leading);
            this.cellSpace = fm.Ascent + Math.Abs(fm.Descent) + fm.Leading;

            Debug.Assert(this.cellAscent == 0 || this.cellAscent == fm.Ascent);
            this.cellAscent = fm.Ascent;

            Debug.Assert(this.cellDescent == 0 || this.cellDescent == Math.Abs(fm.Descent));
            this.cellDescent = Math.Abs(fm.Descent);
#else
            if (fm != null)
            {
                fm.GetType();
            }
#endif
#endif
        }