Beispiel #1
0
        protected void ParseSecurityType(string content, Secure.DocumentPermissions permissions, PDFTraceLog log)
        {
            if (!string.IsNullOrEmpty(content))
            {
                content = content.ToLower();
                switch (content)
                {
                case ("40bit"):
                    if (log.ShouldLog(TraceLevel.Message))
                    {
                        log.Add(TraceLevel.Message, "meta", "Set the document encryption to 40 bit standard (v1.2)");
                    }
                    permissions.Type = Secure.SecurityType.Standard40Bit;
                    break;

                case ("128bit"):
                    if (log.ShouldLog(TraceLevel.Message))
                    {
                        log.Add(TraceLevel.Message, "meta", "Set the document encryption to 128 bit standard (v2.3)");
                    }
                    permissions.Type = Secure.SecurityType.Standard128Bit;
                    break;

                default:
                    if (log.ShouldLog(TraceLevel.Warning))
                    {
                        log.Add(TraceLevel.Warning, "meta", "The document encryption " + content + " was not a recognised value, use 40bit or 128bit");
                    }

                    break;
                }
            }
        }
        private const int MinLoggingStringLength = 1000; //minimum length of the string before we start logging how long it took to parse the string.

        /// <summary>
        /// Initializes the XMLFragmentReader with a string
        /// </summary>
        /// <param name="text"></param>
        private void InitWithText(string text, bool preserveWhitespace, PDFTraceLog log)
        {
            System.Diagnostics.Stopwatch  sw  = null;
            List <Scryber.Text.PDFTextOp> all = null;

            //TODO: IMPORTANT. Change this to an actual reader implementation that does not create an array of all the lines
            try
            {
                if (text.Length > MinLoggingStringLength)
                {
                    sw = System.Diagnostics.Stopwatch.StartNew();
                }

                PDFXMLFragmentParser parser = new PDFXMLFragmentParser();
                all = parser.Parse(text, preserveWhitespace);

                if (null != sw)
                {
                    sw.Stop();
                    if (null != log && log.ShouldLog(TraceLevel.Debug))
                    {
                        log.Add(TraceLevel.Debug, "XML Fragment Parser", "Splitting out entries in a string of " + text.Length + " characters took " + sw.Elapsed);
                    }
                }
            }
            catch (Exception ex)
            {
                _error = ex;
                throw new PDFXmlFormatException("Could not parse the XML text in the provided string", ex);
            }

            //set the instance variable in pre-read state
            _all   = all;
            _index = -1;
        }
        /// <summary>
        /// Removes all the styles that cannot be applied to a row explicitly
        /// </summary>
        /// <param name="applied"></param>
        private void RemoveInapplicableStyles(Style applied)
        {
            int count = applied.ValueCount;

            applied.RemoveItemStyleValues(StyleKeys.MarginsItemKey);
            applied.RemoveItemStyleValues(StyleKeys.PaddingItemKey);

            //Remove the position mode if it is not set to invisible
            StyleValue <PositionMode> pos;

            if (applied.IsValueDefined(StyleKeys.PositionModeKey) && applied.TryGetValue(StyleKeys.PositionModeKey, out pos) && pos.Value(applied) != PositionMode.Invisible)
            {
                applied.RemoveValue(StyleKeys.PositionModeKey);
            }

            applied.RemoveValue(StyleKeys.SizeHeightKey);
            applied.RemoveValue(StyleKeys.PositionXKey);
            applied.RemoveValue(StyleKeys.PositionYKey);

            bool modified = count != applied.ValueCount;



            if (modified)
            {
                PDFTraceLog log = this.Document.TraceLog;
                if (log.ShouldLog(TraceLevel.Message))
                {
                    log.Add(TraceLevel.Verbose, "PDFTableRow", "Removed all unsupported Margins, Padding and Postion style items that are not supported on a table row");
                }
            }
        }
        //
        // public methods
        //

        #region public PDFLayoutPage BeginNewContinuationPage()

        /// <summary>
        /// Begins a new page based on the current page's size and content rect. This will then be the current page
        /// </summary>
        /// <returns></returns>
        public PDFLayoutPage BeginNewContinuationPage()
        {
            if (CurrentPageIndex < 0)
            {
                throw new ArgumentOutOfRangeException("Cannot begin a new page based on previous page if there are no previous pages");
            }
            PDFLayoutPage pg = this.CurrentPage;

            PDFTraceLog log = this.DocumentComponent.TraceLog;

            if (log.ShouldLog(TraceLevel.Verbose))
            {
                log.Add(TraceLevel.Verbose, "LAYOUT", "Beginning a new continuation page for '" + pg + "'");
            }

            if (!pg.IsClosed)
            {
                pg.Close();
            }

            PDFSize        size     = pg.Size;
            Style          style    = pg.FullStyle;
            Page           owner    = pg.Owner as Page;
            OverflowAction overflow = pg.OverflowAction;

            PDFLayoutPage newpg = this.BeginNewPage(owner, this.Engine, style, overflow);

            return(newpg);
        }
        //
        // factory methods
        //

        #region public static PDFFile Load(string path, PDFTraceLog log)

        /// <summary>
        /// Loads a new PDFFile with the data from the specified path - Must be disposed after use.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public static PDFFile Load(string path, PDFTraceLog log)
        {
            if (log.ShouldLog(TraceLevel.Message))
            {
                log.Begin(TraceLevel.Message, PDFFileLogCategory, "Creating a new PDFFile to read the existing data from a file at path '" + path + "'");
            }

            PDFFile file = new PDFFile();

            file._log         = log;
            file._innerStream = GetFileStreamForPath(path);
            file._reader      = PDFReader.Create(file._innerStream, log);
            file._canAppend   = true;
            file._origpath    = path;
            file.Init();

            if (log.ShouldLog(TraceLevel.Message))
            {
                log.End(TraceLevel.Message, PDFFileLogCategory, "A new PDFFile was read from the existing data from the file");
            }

            return(file);
        }
        /// <summary>
        /// Loads a PDFFile from the specified stream recoding process in the log. The stream position
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public static PDFFile Load(System.IO.Stream stream, PDFTraceLog log)
        {
            if (log.ShouldLog(TraceLevel.Message))
            {
                log.Begin(TraceLevel.Message, PDFFileLogCategory, "Creating a new PDFFile to read the existing data from a stream");
            }

            PDFFile file = new PDFFile();

            file._log         = log;
            file._innerStream = stream;
            file._reader      = PDFReader.Create(stream, log);
            file._canAppend   = stream.CanWrite;
            file._origpath    = string.Empty;

            file.Init();

            if (log.ShouldLog(TraceLevel.Message))
            {
                log.End(TraceLevel.Message, PDFFileLogCategory, "A new PDFFile was read from the existing data from a stream");
            }

            return(file);
        }
Beispiel #7
0
        public bool SetStyleValue(PDFTraceLog log, Style style, CSSStyleItemReader reader)
        {
            IParserStyleFactory found;

            if (string.IsNullOrEmpty(reader.CurrentAttribute) && reader.ReadNextAttributeName() == false)
            {
                return(false);
            }

            if (_knownStyles.TryGetValue(reader.CurrentAttribute, out found))
            {
                return(found.SetStyleValue(log, style, reader));
            }
            else
            {
                if (null != log && log.ShouldLog(TraceLevel.Warning))
                {
                    log.Add(TraceLevel.Warning, "CSS", "Could not set the style value on attribute '" + reader.CurrentAttribute + "' as it is not a known style attribute.");
                }

                return(false);
            }
        }
Beispiel #8
0
        protected void ParseRestrictions(string content, Secure.DocumentPermissions permissions, PDFTraceLog log)
        {
            if (string.IsNullOrEmpty(content))
            {
                return;
            }
            content = content.Trim().ToLower();

            bool logVerbose = log.ShouldLog(TraceLevel.Verbose);

            if (content == "none")
            {
                if (logVerbose)
                {
                    log.Add(TraceLevel.Verbose, "meta", "Cleared all restrictions from the document");
                }
                return;
            }

            permissions.AllowAccessiblity        = false;
            permissions.AllowAnnotations         = false;
            permissions.AllowCopying             = false;
            permissions.AllowDocumentAssembly    = false;
            permissions.AllowFormFilling         = false;
            permissions.AllowHighQualityPrinting = false;
            permissions.AllowModification        = false;
            permissions.AllowPrinting            = false;

            if (content == "all")
            {
                if (logVerbose)
                {
                    log.Add(TraceLevel.Verbose, "meta", "Set restrictions to ALL for the document");
                }

                return;
            }

            string[] parts = content.Split(_splits, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

            foreach (var part in parts)
            {
                switch (part)
                {
                case ("allow-printing"):
                case ("printing"):
                    permissions.AllowHighQualityPrinting = true;
                    permissions.AllowPrinting            = true;
                    if (logVerbose)
                    {
                        log.Add(TraceLevel.Verbose, "meta", "Allowed printing for the document");
                    }
                    break;

                case ("allow-accessibility"):
                case ("accessibility"):
                    permissions.AllowAccessiblity = true;
                    if (logVerbose)
                    {
                        log.Add(TraceLevel.Verbose, "meta", "Allowed accessibility for the document");
                    }
                    break;

                case ("allow-annotations"):
                case ("annotations"):
                    permissions.AllowAnnotations = true;
                    if (logVerbose)
                    {
                        log.Add(TraceLevel.Verbose, "meta", "Allowed annotations for the document");
                    }
                    break;

                case ("allow-copying"):
                case ("copying"):
                    permissions.AllowCopying = true;
                    if (logVerbose)
                    {
                        log.Add(TraceLevel.Verbose, "meta", "Allowed copying for the document");
                    }
                    break;

                case ("allow-modifications"):
                case ("modifications"):
                    permissions.AllowModification     = true;
                    permissions.AllowDocumentAssembly = true;
                    if (logVerbose)
                    {
                        log.Add(TraceLevel.Verbose, "meta", "Allowed modifications for the document");
                    }
                    break;

                case ("allow-forms"):
                case ("forms"):
                    permissions.AllowFormFilling = true;
                    if (logVerbose)
                    {
                        log.Add(TraceLevel.Verbose, "meta", "Allowed form filling for the document");
                    }
                    break;

                default:
                    if (log.ShouldLog(TraceLevel.Warning))
                    {
                        log.Add(TraceLevel.Warning, "meta", "The restrictions part " + part + " was not recognised as a valid restriction");
                    }
                    break;
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Initializes the known PDF file data such as trailers, xref tables and catalogs
        /// </summary>
        protected override void InitData(PDFTraceLog log)
        {
            try
            {
                if (log.ShouldLog(TraceLevel.Debug))
                {
                    log.Add(TraceLevel.Debug, "PDFReader", "Finding end of file, startxref and trailer positions");
                }

                this.Searcher.Position = this.Searcher.Length;
                PDFFileRange eofPos       = AssertFoundRange(Searcher.MatchBackwardString(EndOfFileMarker), EndOfFileMarker);
                PDFFileRange startxrefPos = AssertFoundRange(Searcher.MatchBackwardString(StartXRefMarker), StartXRefMarker);

                PDFFileRange trailerPos = AssertFoundRange(Searcher.MatchBackwardString(TrailerMarker), TrailerMarker);

                if (log.ShouldLog(TraceLevel.Debug))
                {
                    log.Add(TraceLevel.Debug, "PDFReader", "Markers found, loading the trailer dictionary");
                }

                PDFDictionary trailer = GetTrailerDictionary(trailerPos, startxrefPos);
                this._trailer = trailer;

                if (log.ShouldLog(TraceLevel.Debug))
                {
                    log.Add(TraceLevel.Debug, "PDFReader", "Markers found, loading the XRef table");
                }

                PDFObjectRef catalogRef = AssertGetObjectRef(trailer, CatalogObjName, "The '" + CatalogObjName + "' entry couldnot be found in the documents trailer dictionary");
                PDFObjectRef infoRef    = AssertGetObjectRef(trailer, InfoObjName, "The '" + InfoObjName + "' entry couldnot be found in the documents trailer dictionary");
                IFileObject  prevXRefObj;
                trailer.TryGetValue(PrevXRefName, out prevXRefObj);
                long prevOffset = -1;
                if (prevXRefObj is PDFNumber)
                {
                    prevOffset = ((PDFNumber)prevXRefObj).Value;
                }
                else if (prevXRefObj is PDFReal)
                {
                    prevOffset = (long)((PDFNumber)prevXRefObj).Value;
                }

                PDFXRefTable xref = GetXRefTable(startxrefPos, eofPos, prevOffset);


                if (log.ShouldLog(TraceLevel.Debug))
                {
                    log.Add(TraceLevel.Debug, "PDFReader", "References for the catalog and document info found");
                }

                this._xreftable = xref;
                this._info      = (PDFFileIndirectObject)this.GetObject(infoRef);

                if (log.ShouldLog(TraceLevel.Debug))
                {
                    log.Add(TraceLevel.Debug, "PDFReader", "Loaded the document Info indirect object");
                }

                this._catalog = (PDFFileIndirectObject)this.GetObject(catalogRef);

                if (log.ShouldLog(TraceLevel.Debug))
                {
                    log.Add(TraceLevel.Debug, "PDFReader", "Loaded the document Catalog indirect object");
                }

                //TODO: Look for more updates and read those in too
            }
            catch (Exception ex)
            {
                throw new PDFNativeParserException(CommonErrors.CouldNotInitializeThePDFReader, ex);
            }
        }