Beispiel #1
0
 /// <summary>
 /// Creates an image from the specified file.
 /// For non-pdf files, this requires that an instance of an implementation of <see cref="T:MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource"/> be set on the `ImageSource.ImageSourceImpl` property.
 /// For .NetCore apps, if this property is null at this point, then <see cref="T:PdfSharpCore.Utils.ImageSharpImageSource"/> with <see cref="T:SixLabors.ImageSharp.PixelFormats.Rgba32"/> Pixel Type is used
 /// </summary>
 /// <param name="path">The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.</param>
 /// <param name="accuracy">Moderate allows for broken references when using a PDF file.</param>
 public static XImage FromFile(string path, PdfReadAccuracy accuracy)
 {
     if (PdfReader.TestPdfFile(path) > 0)
     {
         return(new XPdfForm(path, accuracy));
     }
     return(new XImage(path));
 }
Beispiel #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XPdfForm"/> class from a stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="accuracy">Moderate allows for broken references.</param>
        internal XPdfForm(Stream stream, PdfReadAccuracy accuracy)
        {
            // Create a dummy unique path
            _path = "*" + Guid.NewGuid().ToString("B");

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

            _externalDocument = PdfReader.Open(stream, accuracy);
        }
Beispiel #3
0
        public PdfDocument GetDocument(string path, PdfReadAccuracy accuracy)
        {
            Debug.Assert(path.StartsWith("*") || Path.IsPathRooted(path), "Path must be full qualified.");

            PdfDocument document = null;

            PdfDocument.DocumentHandle handle;
            if (_importedDocuments.TryGetValue(path, out handle))
            {
                document = handle.Target;
                if (document == null)
                {
                    RemoveDocument(path);
                }
            }
            if (document == null)
            {
                document = PdfReader.Open(path, PdfDocumentOpenMode.Import, accuracy);
                _importedDocuments.Add(path, document.Handle);
            }
            return(document);
        }
Beispiel #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, 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;
            }
        }
Beispiel #5
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(Stream stream, string password, PdfDocumentOpenMode openmode, PdfReadAccuracy accuracy)
 {
     return(Open(stream, password, openmode, null, accuracy));
 }
Beispiel #6
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(Stream stream, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider, PdfReadAccuracy accuracy)
 {
     return(Open(stream, null, openmode, passwordProvider, accuracy));
 }
Beispiel #7
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(Stream stream, PdfDocumentOpenMode openmode, PdfReadAccuracy accuracy)
 {
     return(Open(stream, null, openmode, accuracy));
 }
Beispiel #8
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(string path, string password, PdfReadAccuracy accuracy)
 {
     return(Open(path, password, PdfDocumentOpenMode.Modify, null, accuracy));
 }
Beispiel #9
0
        /// <summary>
        /// Opens an existing PDF document.
        /// </summary>
        public static PdfDocument Open(string path, string password, PdfDocumentOpenMode openmode, PdfPasswordProvider provider, PdfReadAccuracy accuracy)
        {
#if NETCOREAPP1_1 || (!NETFX_CORE && !PORTABLE)
            PdfDocument document;
            Stream      stream = null;
            try
            {
                stream   = new FileStream(path, FileMode.Open, FileAccess.Read);
                document = Open(stream, password, openmode, provider, accuracy);
                if (document != null)
                {
                    document._fullPath = Path.GetFullPath(path);
                }
            }
            finally
            {
                if (stream != null)
#if NETCOREAPP1_1 || UWP
                { stream.Dispose(); }
#else
                { stream.Close(); }
#endif
            }
            return(document);
#else
            return(null);
#endif
        }
Beispiel #10
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(string path, PdfDocumentOpenMode openmode, PdfPasswordProvider provider, PdfReadAccuracy accuracy)
 {
     return(Open(path, null, openmode, provider, accuracy));
 }
Beispiel #11
0
 /// <summary>
 /// Creates an XPdfForm from a stream.
 /// </summary>
 public static XPdfForm FromStream(Stream stream, PdfReadAccuracy accuracy)
 {
     return(new XPdfForm(stream, accuracy));
 }
        /// <summary>
        /// Opens an existing PDF document.
        /// </summary>
        public static PdfDocument Open(string path, string password, PdfDocumentOpenMode openmode, PdfPasswordProvider provider, PdfReadAccuracy accuracy)
        {
            PdfDocument document;
            Stream      stream = null;

            try
            {
                stream   = new FileStream(path, FileMode.Open, FileAccess.Read);
                document = Open(stream, password, openmode, provider, accuracy);
                if (document != null)
                {
                    document._fullPath = Path.GetFullPath(path);
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
            return(document);
        }
Beispiel #13
0
 /// <summary>
 /// Creates an XPdfForm from a stream and a password.
 /// </summary>
 public static XPdfForm FromStream(Stream stream, string password, PdfReadAccuracy accuracy)
 {
     return(new XPdfForm(stream, password, accuracy));
 }
Beispiel #14
0
        /// <summary>
        /// Opens an existing PDF document.
        /// </summary>
        public static PdfDocument Open(Stream stream, string password, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider, PdfReadAccuracy accuracy)
        {
            PdfDocument document;

            try
            {
                Lexer lexer = new Lexer(stream);
                document           = new PdfDocument(lexer);
                document._state   |= DocumentState.Imported;
                document._openMode = openmode;
                document._fileSize = stream.Length;

                // Get file version.
                byte[] header = new byte[1024];
                stream.Position = 0;
                stream.Read(header, 0, 1024);
                document._version = GetPdfFileVersion(header);
                if (document._version == 0)
                {
                    throw new InvalidOperationException(PSSR.InvalidPdf);
                }

                document._irefTable.IsUnderConstruction = true;
                Parser parser = new Parser(document);

                // Read all trailers or cross-reference streams, but no objects.
                document._trailer = parser.ReadTrailer(accuracy);

                if (document._trailer == null)
                {
                    ParserDiagnostics.ThrowParserException("Invalid PDF file: no trailer found.");
                }

                Debug.Assert(document._irefTable.IsUnderConstruction);
                document._irefTable.IsUnderConstruction = false;

                // Is document encrypted?
                PdfReference xrefEncrypt = document._trailer.Elements[PdfTrailer.Keys.Encrypt] as PdfReference;
                if (xrefEncrypt != null)
                {
                    //xrefEncrypt.Value = parser.ReadObject(null, xrefEncrypt.ObjectID, false);
                    PdfObject encrypt = parser.ReadObject(null, xrefEncrypt.ObjectID, false, false);

                    encrypt.Reference = xrefEncrypt;
                    xrefEncrypt.Value = encrypt;
                    PdfStandardSecurityHandler securityHandler = document.SecurityHandler;
TryAgain:
                    PasswordValidity validity = securityHandler.ValidatePassword(password);
                    if (validity == PasswordValidity.Invalid)
                    {
                        if (passwordProvider != null)
                        {
                            PdfPasswordProviderArgs args = new PdfPasswordProviderArgs();
                            passwordProvider(args);
                            if (args.Abort)
                            {
                                return(null);
                            }
                            password = args.Password;
                            goto TryAgain;
                        }
                        else
                        {
                            if (password == null)
                            {
                                throw new PdfReaderException(PSSR.PasswordRequired);
                            }
                            else
                            {
                                throw new PdfReaderException(PSSR.InvalidPassword);
                            }
                        }
                    }
                    else if (validity == PasswordValidity.UserPassword && openmode == PdfDocumentOpenMode.Modify)
                    {
                        if (passwordProvider != null)
                        {
                            PdfPasswordProviderArgs args = new PdfPasswordProviderArgs();
                            passwordProvider(args);
                            if (args.Abort)
                            {
                                return(null);
                            }
                            password = args.Password;
                            goto TryAgain;
                        }
                        else
                        {
                            throw new PdfReaderException(PSSR.OwnerPasswordRequired);
                        }
                    }
                }
                else
                {
                    if (password != null)
                    {
                        // Password specified but document is not encrypted.
                        // ignore
                    }
                }

                PdfReference[] irefs2 = document._irefTable.AllReferences;
                int            count2 = irefs2.Length;

                // 3rd: Create iRefs for all compressed objects.
                Dictionary <int, object> objectStreams = new Dictionary <int, object>();
                for (int idx = 0; idx < count2; idx++)
                {
                    PdfReference            iref       = irefs2[idx];
                    PdfCrossReferenceStream xrefStream = iref.Value as PdfCrossReferenceStream;
                    if (xrefStream != null)
                    {
                        for (int idx2 = 0; idx2 < xrefStream.Entries.Count; idx2++)
                        {
                            PdfCrossReferenceStream.CrossReferenceStreamEntry item = xrefStream.Entries[idx2];
                            // Is type xref to compressed object?
                            if (item.Type == 2)
                            {
                                //PdfReference irefNew = parser.ReadCompressedObject(new PdfObjectID((int)item.Field2), (int)item.Field3);
                                //document._irefTable.Add(irefNew);
                                int objectNumber = (int)item.Field2;
                                if (!objectStreams.ContainsKey(objectNumber))
                                {
                                    objectStreams.Add(objectNumber, null);
                                    PdfObjectID objectID = new PdfObjectID((int)item.Field2);
                                    parser.ReadIRefsFromCompressedObject(objectID);
                                }
                            }
                        }
                    }
                }

                // 4th: Read compressed objects.
                for (int idx = 0; idx < count2; idx++)
                {
                    PdfReference            iref       = irefs2[idx];
                    PdfCrossReferenceStream xrefStream = iref.Value as PdfCrossReferenceStream;
                    if (xrefStream != null)
                    {
                        for (int idx2 = 0; idx2 < xrefStream.Entries.Count; idx2++)
                        {
                            PdfCrossReferenceStream.CrossReferenceStreamEntry item = xrefStream.Entries[idx2];
                            // Is type xref to compressed object?
                            if (item.Type == 2)
                            {
                                PdfReference irefNew = parser.ReadCompressedObject(new PdfObjectID((int)item.Field2),
                                                                                   (int)item.Field3);
                                Debug.Assert(document._irefTable.Contains(iref.ObjectID));
                                //document._irefTable.Add(irefNew);
                            }
                        }
                    }
                }


                PdfReference[] irefs = document._irefTable.AllReferences;
                int            count = irefs.Length;

                // Read all indirect objects.
                for (int idx = 0; idx < count; idx++)
                {
                    PdfReference iref = irefs[idx];
                    if (iref.Value == null)
                    {
#if DEBUG_
                        if (iref.ObjectNumber == 1074)
                        {
                            iref.GetType();
                        }
#endif
                        try
                        {
                            Debug.Assert(document._irefTable.Contains(iref.ObjectID));
                            PdfObject pdfObject = parser.ReadObject(null, iref.ObjectID, false, false);
                            Debug.Assert(pdfObject.Reference == iref);
                            pdfObject.Reference = iref;
                            Debug.Assert(pdfObject.Reference.Value != null, "Something went wrong.");
                        }
                        catch (PositionNotFoundException ex)
                        {
                            Debug.WriteLine(ex.Message);

                            if (accuracy == PdfReadAccuracy.Strict)
                            {
                                throw;
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                            // 4STLA rethrow exception to notify caller.
                            throw;
                        }
                    }
                    else
                    {
                        Debug.Assert(document._irefTable.Contains(iref.ObjectID));
                        //iref.GetType();
                    }
                    // Set maximum object number.
                    document._irefTable._maxObjectNumber = Math.Max(document._irefTable._maxObjectNumber,
                                                                    iref.ObjectNumber);
                }

                // Encrypt all objects.
                if (xrefEncrypt != null)
                {
                    document.SecurityHandler.EncryptDocument();
                }

                // Fix references of trailer values and then objects and irefs are consistent.
                document._trailer.Finish();

#if DEBUG_
                // Some tests...
                PdfReference[] reachables = document.xrefTable.TransitiveClosure(document.trailer);
                reachables.GetType();
                reachables = document.xrefTable.AllXRefs;
                document.xrefTable.CheckConsistence();
#endif

                if (openmode == PdfDocumentOpenMode.Modify)
                {
                    // Create new or change existing document IDs.
                    if (document.Internals.SecondDocumentID == "")
                    {
                        document._trailer.CreateNewDocumentIDs();
                    }
                    else
                    {
                        byte[] agTemp = Guid.NewGuid().ToByteArray();
                        document.Internals.SecondDocumentID = PdfEncoders.RawEncoding.GetString(agTemp, 0, agTemp.Length);
                    }

                    // Change modification date
                    document.Info.ModificationDate = DateTime.Now;

                    // Remove all unreachable objects
                    int removed = document._irefTable.Compact();
                    if (removed != 0)
                    {
                        Debug.WriteLine("Number of deleted unreachable objects: " + removed);
                    }

                    // Force flattening of page tree
                    PdfPages pages = document.Pages;
                    Debug.Assert(pages != null);

                    //bool b = document.irefTable.Contains(new PdfObjectID(1108));
                    //b.GetType();

                    document._irefTable.CheckConsistence();
                    document._irefTable.Renumber();
                    document._irefTable.CheckConsistence();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
            return(document);
        }
Beispiel #15
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(string path, PdfDocumentOpenMode openmode, PdfReadAccuracy accuracy)
 {
     return(Open(path, null, openmode, null, accuracy));
 }
Beispiel #16
0
 /// <summary>
 /// Opens an existing PDF document.
 /// </summary>
 public static PdfDocument Open(Stream stream, PdfReadAccuracy accuracy)
 {
     return(Open(stream, PdfDocumentOpenMode.Modify, accuracy));
 }
Beispiel #17
0
 /// <summary>
 /// Creates an XPdfForm from a file.
 /// </summary>
 public static new XPdfForm FromFile(string path, PdfReadAccuracy accuracy)
 {
     // TODO: Same file should return same object (that's why the function is static).
     return(new XPdfForm(path, accuracy));
 }