public CSSStyleEnumerator(StringEnumerator str, CSSStyleParser owner, PDFContextBase context)
 {
     this._str     = str;
     this._owner   = owner;
     this._context = context;
     this._log     = context == null ? new DoNothingTraceLog(TraceRecordLevel.Off) : context.TraceLog;
 }
        //
        // 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);
        }
예제 #3
0
        /// <summary>
        /// Creates a new PDFReader for the specified stream (which must be seekable)
        /// </summary>
        /// <param name="seekableStream"></param>
        /// <returns></returns>
        public static PDFReader Create(System.IO.Stream seekableStream, PDFTraceLog log)
        {
            if (seekableStream.CanSeek == false)
            {
                throw new ArgumentException("Cannot read a PDF File from a non-seekable stream");
            }

            seekableStream.Position = 0;
            Version vers = ReadHeaderVersion(seekableStream);

            seekableStream.Position = 0;
            PDFReader reader;

            if (vers < new Version(1, 5))
            {
                reader = new PDFReader14(seekableStream, false, log);
            }
            else if (vers < new Version(1, 8))
            {
                reader = new PDFReader17(seekableStream, false, log);
            }
            else
            {
                log.Add(Scryber.TraceLevel.Warning, "PDFReader", "Source PDF File version is greater than the supported version 1.7. Parsing of the file will continue, but may not succeed.");
                reader = new PDFReader17(seekableStream, false, log);
            }
            reader.InitData(log);

            return(reader);
        }
예제 #4
0
        /// <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");
                }
            }
        }
예제 #5
0
 public CSSStyleParser(string content, PDFContextBase context)
 {
     this.Context = context;
     this.Content = content;
     this._err    = new List <CSSParsingError>();
     this._log    = context == null ? new DoNothingTraceLog(TraceRecordLevel.Off) : context.TraceLog;
 }
        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;
        }
예제 #7
0
 /// <summary>
 /// Creates a new PDFSecureWriter14 that will write to the provded stream and encrypt output using the PDFEncrypter (cannot be null).
 /// </summary>
 /// <param name="stream">The stream to ultimately write the data to.</param>
 /// <param name="generation">The current generation of the PDF docucment.</param>
 /// <param name="log">The log to write messages to.</param>
 /// <param name="security">The PDFEncrypter to use.</param>
 internal PDFSecureWriter14(Stream stream, int generation, PDFTraceLog log, Version vers, PDFEncryter security)
     : base(stream, generation, log, vers)
 {
     if (null == security)
     {
         throw new ArgumentNullException("security");
     }
     _security   = security;
     _encrypters = new Stack <PDFObjectEncryptionStream>();
 }
        //
        // .ctor
        //

        #region internal PDFSecureWriter14(Stream stream, PDFTraceLog log, PDFEncryter security)

        /// <summary>
        /// Creates a new PDFSecureWriter14 that will write to the provded stream and encrypt output using the PDFEncrypter (cannot be null).
        /// </summary>
        /// <param name="stream">The stream to ultimately write the data to.</param>
        /// <param name="log">The log to write messages to.</param>
        /// <param name="security">The PDFEncrypter to use.</param>
        internal PDFSecureWriter14(Stream stream, PDFTraceLog log, PDFPerformanceMonitor monitor, PDFEncryter security)
            : base(stream, log)
        {
            if (null == security)
            {
                throw new ArgumentNullException("security");
            }
            _security   = security;
            _monitor    = monitor;
            _encrypters = new Stack <PDFObjectEncryptionStream>();
        }
예제 #9
0
        //
        // .ctor
        //

        #region private PDFReader14(System.IO.Stream stream, bool ownStream)

        /// <summary>
        /// Constructs an new PDFReader14
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="ownStream"></param>
        internal PDFReader14(System.IO.Stream stream, bool ownStream, PDFTraceLog log)
        {
            this._innerStream = stream;
            this._ownsstream  = ownStream;
            if (stream.CanSeek == false)
            {
                throw new ArgumentException("Cannot read a PDF File from a non-seekable stream");
            }

            this._searcher = new PDFTextSearcher(stream);
        }
예제 #10
0
        private void InitAndLoadRoot(Component built, PDFContextBase context)
        {
            if (context.TraceLog.ShouldLog(TraceLevel.Debug))
            {
                context.TraceLog.Add(TraceLevel.Debug, "DataGrid", "Initializing and loading root component before binding");
            }

            PDFTraceLog    log  = context.TraceLog;
            PDFInitContext init = new PDFInitContext(context.Items, log, context.PerformanceMonitor, this.Document);
            PDFLoadContext load = new PDFLoadContext(context.Items, log, context.PerformanceMonitor, this.Document);

            built.Init(init);
            built.Load(load);
        }
예제 #11
0
 public CSSStyleParser(string content, PDFContextBase context)
 {
     this.Content = content;
     this._err    = new List <CSSParsingError>();
     this.Context = context;
     if (null == context)
     {
         this.Log = new Logging.DoNothingTraceLog(TraceRecordLevel.Off);
     }
     else
     {
         this.Log = context.TraceLog;
     }
 }
예제 #12
0
        public override PDFTraceLog GetLogWithName(string name)
        {
            PDFTraceLog log = base.GetLogWithName(name);

            if (null == log)
            {
                foreach (PDFTraceLog inner in this._inner)
                {
                    log = inner.GetLogWithName(name);
                    if (null != log)
                    {
                        break;
                    }
                }
            }
            return(log);
        }
예제 #13
0
        public PDFGeneratorSettings(Type literaltype, Type templategenerator, Type templateinstance,
                                    PDFReferenceResolver resolver, ParserConformanceMode conformance, ParserLoadType loadtype,
                                    PDFTraceLog log, PDFPerformanceMonitor perfmon, object controllerInstance)
        {
            this._textLiteralType      = literaltype;
            this._tempateGenType       = templategenerator;
            this._templateinstanceType = templateinstance;
            this._resolver             = resolver;
            this._conformance          = conformance;
            this._loadtype             = loadtype;
            this._log                = log;
            this._perfmon            = perfmon;
            this._controllerInstance = controllerInstance;
            this._controllerType     = (null == controllerInstance) ? null : controllerInstance.GetType();

            //Get the default culture from the config - can be overridden in the processing instructions, or at generation time in code
            var config        = ServiceProvider.GetService <IScryberConfigurationService>();
            var parserOptions = config.ParsingOptions;

            this.MissingReferenceAction = parserOptions.MissingReferenceAction;
            this.SpecificCulture        = parserOptions.GetDefaultCulture();
        }
예제 #14
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);
            }
        }
예제 #15
0
        protected override void InitData(PDFTraceLog log)
        {
            this.Searcher.Position = this.Searcher.Length;
            PDFFileRange eofPos       = AssertFoundRange(Searcher.MatchBackwardString(EndOfFileMarker), EndOfFileMarker);
            PDFFileRange startxrefPos = AssertFoundRange(Searcher.MatchBackwardString(StartXRefMarker), StartXRefMarker);

            //Look for a object number as the xref object as per v1.5 onwards.

            this.Searcher.Position = startxrefPos.EndOffset;
            string offset = this.Searcher.GetInnerText(startxrefPos, eofPos).Trim();

            long pos;

            if (long.TryParse(offset, out pos))
            {
                this.Searcher.Position = pos;
                PDFFileRange num  = this.Searcher.MatchForwardString(" ");
                PDFFileRange vers = this.Searcher.MatchForwardString(" ");
            }


            base.InitData(log);
        }
예제 #16
0
        //
        // 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);
        }
        private bool ValidateSecureDocumentLicense()
        {
            Type             licensedType = typeof(PDFSecureDocument);
            string           msg;
            IPDFLicense      lic    = Licensing.GetLicense(licensedType);
            PDFLicenseAction action = lic.Validate(out msg);

            if (action == PDFLicenseAction.None)
            {
                return(false);
            }
            else
            {
                if ((action & PDFLicenseAction.ExcludeFromOutput) > 0)
                {
                    throw new InvalidOperationException("Excluding from output is not appropriate for a document component");
                }

                if ((action & PDFLicenseAction.LogMessage) > 0)
                {
                    PDFTraceLog log = this.Context.TraceLog;
                    log.Add(TraceLevel.Message, "Licensing", "No valid license for component " + licensedType.Name + " was found. " + msg);
                }
                if ((action & PDFLicenseAction.RaiseException) > 0)
                {
                    throw new PDFLicenceException(licensedType, msg);
                }

                if ((action & PDFLicenseAction.ShowBadge) > 0)
                {
                    return(true);
                }

                //No action defined
                return(false);
            }
        }
예제 #18
0
        /// <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);
        }
예제 #19
0
        public static PDFTextReader Create(string text, TextFormat format, bool preserveWhitespace, PDFTraceLog log)
        {
            switch (format)
            {
            case TextFormat.Plain:
                return(new PDFPlainTextReader(text, preserveWhitespace));

            case TextFormat.XML:
                return(new PDFXMLFragmentReader(text, preserveWhitespace, log));

            //case TextFormat.RTF:
            //    throw new NotSupportedException("RTF is not currently supported");

            default:
                throw new NotSupportedException("This format is not currently supported");
            }
        }
 public CSSStyleEnumerator(StringEnumerator str, CSSStyleParser owner, PDFTraceLog log)
 {
     this._str   = str;
     this._owner = owner;
     this._log   = log;
 }
예제 #21
0
 public PDFReader17(System.IO.Stream stream, bool ownsStream, PDFTraceLog log)
     : base(stream, ownsStream, log)
 {
 }
예제 #22
0
        protected virtual void AddAutoBindFields(object data, IPDFDataSource source, PDFDataContext context)
        {
            if (string.IsNullOrEmpty(this.DataSourceID))
            {
                throw new InvalidOperationException("Can only auto bind the schema when the With has an explicit DataSourceID and the referencing source supports Schema derriving");
            }

            IPDFDataSource found = base.FindDocumentComponentById(this.DataSourceID) as IPDFDataSource;

            if (null == found || found.SupportsDataSchema == false)
            {
                throw new InvalidOperationException("Can only auto bind the schema when the With has an explicit DataSourceID and the referencing source supports Schema derriving");
            }

            PDFDataSchema schema = found.GetDataSchema(this.SelectPath, context);

            if (null == schema || schema.Items == null || schema.Items.Count == 0)
            {
                context.TraceLog.Add(TraceLevel.Warning, "PDFWithFieldSet", string.Format("Cannot autobind the columns as no schema items were returned for the path '{0}'", this.SelectPath));
            }
            else
            {
                if (context.TraceLog.ShouldLog(TraceLevel.Debug))
                {
                    context.TraceLog.Add(TraceLevel.Debug, "DataGrid", "Initializing and loading root component before binding");
                }

                PDFTraceLog    log  = context.TraceLog;
                PDFInitContext init = new PDFInitContext(context.Items, log, context.PerformanceMonitor, this.Document);
                PDFLoadContext load = new PDFLoadContext(context.Items, log, context.PerformanceMonitor, this.Document);


                foreach (PDFDataItem item in schema.Items)
                {
                    if (ShouldIncludeAutoBoundItem(item))
                    {
                        WithBoundField field = GetFieldForType(item.DataType);
                        if (null != field)
                        {
                            field.StyleClass = this.FieldClass;

                            field.FieldLabel   = string.IsNullOrEmpty(item.Title) ? item.Name : item.Title;
                            field.LabelClass   = this.LabelClass;
                            field.ValueClass   = this.ValueClass;
                            field.LabelPostFix = this.LabelPostFix;
                            field.LayoutType   = this.AutoLayoutType;
                            field.DataType     = item.DataType;
                            field.HideIfEmpty  = this.HideEmptyFields;


                            field.SetDataSourceBindingItem(item, context);
                            if (context.TraceLog.ShouldLog(TraceLevel.Debug))
                            {
                                context.TraceLog.Add(TraceLevel.Debug, "PDFWithFieldSet", string.Format("The data field was automatically created for the schdema item '{0}' in set '{1}'", item, this));
                            }

                            this.Fields.Add(field);
                            field.Init(init);
                            field.Load(load);

                            this.BindingActions.Add(new BindingAction(data, source, field));
                        }
                    }
                }

                //added all the items
            }
        }
        /// <summary>
        /// Creates a new parser settings instance with cusomizable setting values.
        /// </summary>
        /// <param name="skipUnknown">Flag if unknown tags should be ignored</param>
        /// <param name="skipOverTags">Any known but unusable tags that should be skipped completely (including any of their inner content)</param>
        /// <param name="escapeEntites">All the escaped entities mapping HTML entities (e.g. &amp;) to the character equivalent (e.g. &)</param>
        private HTMLParserSettings(bool skipUnknown, bool skipCssClasses, bool skipStyles, bool skipProcessingInstructions, bool skipComments, bool skipDocType, bool skipCData, TraceLevel loglevel, PDFTraceLog log, IList <string> skipOverTags, IDictionary <string, char> escapeEntites)
        {
            if (null == escapeEntites)
            {
                throw new ArgumentNullException("escapeEntities");
            }
            if (null == skipOverTags)
            {
                throw new ArgumentNullException("skipOverTags");
            }

            this.SkipUnknownTags            = skipUnknown;
            this.SkipOverTags               = skipOverTags;
            this.SkipComments               = skipComments;
            this.SkipDocType                = skipDocType;
            this.SkipCData                  = skipCData;
            this.SkipCssClasses             = skipCssClasses;
            this.SkipStyles                 = skipStyles;
            this.SkipProcessingInstructions = skipProcessingInstructions;
            this.HTMLEntityMappings         = escapeEntites;
            this.LogLevel = loglevel;
            this.TraceLog = log;
        }
 /// <summary>
 /// Creates a new default instance of the parser settings
 /// </summary>
 public HTMLParserSettings(PDFTraceLog log)
     : this(DefaultSkipUnknown, DefaultSkipCssClasses, DefaultSkipStyles, DefaultSkipProcessingInstructions, DefaultSkipComments, DefaultSkipDocType, DefaultSkipCData, TraceLevel.Verbose, log, new ReadOnlyList <string>(DefaultSkipOverTags), new ReadOnlyDictionary <string, char>(DefaultEscapedHTMLEntities))
 {
 }
예제 #25
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;
                }
            }
        }
예제 #26
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;
                }
            }
        }
예제 #27
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);
            }
        }
        //implementation methods

        protected override PDFWriter DoGetInstance(Document forDoc, Stream stream, int generation, PDFDocumentRenderOptions options, PDFTraceLog log)
        {
            if (null == forDoc.DocumentID)
            {
                forDoc.DocumentID = PDFDocumentID.Create();
            }

            PDFEncrypterFactory factory = this.GetEncrypterFactory();

            IDocumentPasswordSettings settings;
            string          path = forDoc.LoadedSource;
            SecureString    owner;
            SecureString    user;
            PermissionFlags protection;

            if (Options.SecurityOptions.TryGetPasswordSettings(path, out settings))
            {
                owner      = settings.OwnerPassword;
                user       = settings.UserPassword;
                protection = settings.DefaultPermissions;

                if (settings.AllowDocumentOverrides)
                {
                    if (null != this.OwnerPassword)
                    {
                        owner = this.OwnerPassword;
                    }
                    if (null != this.UserPassword)
                    {
                        user = this.UserPassword;
                    }
                    protection |= this.GetRestrictions();
                }
            }
            else
            {
                protection = this.GetRestrictions();
                owner      = this.OwnerPassword;
                user       = this.UserPassword;
            }

            PDFEncryter       enc    = factory.InitEncrypter(owner, user, forDoc.DocumentID, protection);
            PDFSecureWriter14 writer = new PDFSecureWriter14(stream, log, enc);

            return(writer);
        }
 protected override PDFWriter DoGetInstance(Document forDoc, Stream stream, int generation, PDFDocumentRenderOptions options, PDFTraceLog log, PDFPerformanceMonitor monitor)
 {
     return(new PDFSecureWriter14(stream, log, monitor, this._enc));
 }
예제 #30
0
        //
        // abstract methods
        //

        /// <summary>
        /// Allows the instance to build any required data and perform and initialization.
        /// </summary>
        /// <param name="log"></param>
        protected abstract void InitData(PDFTraceLog log);