Esempio n. 1
0
        /// <summary>
        /// PDF embedded file class constructor
        /// </summary>
        /// <param name="Document">Current document</param>
        /// <param name="FileName">File name</param>
        /// <param name="PdfFileName">PDF file name (see remarks)</param>
        /// <remarks>
        /// <para>
        /// FileName is the name of the source file on the disk.
        /// PDFFileName is the name of the as saved within the PDF document file.
        /// If PDFFileName is not given or it is set to null, the class takes
        /// the disk's file name without the path.
        /// </para>
        /// </remarks>
        public PdfEmbeddedFile
        (
            PdfDocument Document,
            String FileName,
            String PdfFileName = null
        ) : base(Document, ObjectType.Dictionary, "/Filespec")
        {
            // save file name
            this.FileName = FileName;

            // test exitance
            if (!File.Exists(FileName))
            {
                throw new ApplicationException("Embedded file " + FileName + " does not exist");
            }

            // get file length
            FileInfo FI = new FileInfo(FileName);

            if (FI.Length > Int32.MaxValue - 4095)
            {
                throw new ApplicationException("Embedded file " + FileName + " too long");
            }
            Int32 FileLength = (Int32)FI.Length;

            // translate file extension to mime type string
            MimeType = ExtToMime.TranslateExtToMime(FI.Extension);

            // create embedded file object
            PdfObject EmbeddedFile = new PdfObject(Document, ObjectType.Stream, "/EmbeddedFile");

            // save uncompressed file length
            EmbeddedFile.Dictionary.AddFormat("/Params", "<</Size {0}>>", FileLength);

            // file data content byte array
            Byte[] FileData = new Byte[FileLength];

            // load all the file's data
            FileStream DataStream = null;

            try
            {
                // open the file
                DataStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);

                // read all the file
                if (DataStream.Read(FileData, 0, FileLength) != FileLength)
                {
                    throw new Exception();
                }
            }

            // loading file failed
            catch (Exception)
            {
                throw new ApplicationException("Invalid media file: " + FileName);
            }

            // close the file
            DataStream.Close();

            // compress the data
            Byte[] FileDataComp = CompressStream(FileData);
            if (FileDataComp != null)
            {
                FileData = FileDataComp;
                EmbeddedFile.Dictionary.Add("/Filter", "/FlateDecode");
            }

            // encryption
            if (Document.Encryption != null)
            {
                FileData = Document.Encryption.EncryptByteArray(EmbeddedFile.ObjectNumber, FileData);
            }

            // add compressed file length
            EmbeddedFile.Dictionary.AddInteger("/Length", FileData.Length);

            // shortcut
            PdfBinaryWriter PdfFile = Document.PdfFile;

            // save file position for this object
            EmbeddedFile.FilePosition = PdfFile.BaseStream.Position;

            // write object header
            PdfFile.WriteFormat("{0} 0 obj\n", EmbeddedFile.ObjectNumber);

            // write dictionary
            EmbeddedFile.Dictionary.WriteToPdfFile();

            // output stream
            PdfFile.WriteString("stream\n");

            // debug
            if (Document.Debug)
            {
                PdfFile.WriteString("*** MEDIAFILE PLACE HOLDER ***");
            }

            // output embedded font
            else
            {
                PdfFile.Write(FileData);
            }

            // output stream
            PdfFile.WriteString("\nendstream\n");

            // output object trailer
            PdfFile.WriteString("endobj\n");

            // file spec object type
            Dictionary.Add("/Type", "/Filespec");

            // PDF file name
            if (String.IsNullOrWhiteSpace(PdfFileName))
            {
                PdfFileName = FI.Name;
            }
            Dictionary.AddPdfString("/F", PdfFileName);
            Dictionary.AddPdfString("/UF", PdfFileName);

            // add reference
            Dictionary.AddFormat("/EF", "<</F {0} 0 R /UF {0} 0 R>>", EmbeddedFile.ObjectNumber);
            return;
        }
Esempio n. 2
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Create PDF document file
        /// </summary>
        /// <remarks>
        /// The last step of document creation after all pages were constructed.
        /// FileName is the path and name of the output file.
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public void CreateFile()
        {
            // create page array
            StringBuilder Kids = new StringBuilder("[");

            for (Int32 Index = 0; Index < PageArray.Count; Index++)
            {
                Kids.AppendFormat("{0} 0 R ", PageArray[Index].ObjectNumber);
            }
            if (Kids.Length > 1)
            {
                Kids.Length--;
            }
            Kids.Append("]");
            PagesObject.Dictionary.Add("/Kids", Kids.ToString());

            // page count
            PagesObject.Dictionary.AddInteger("/Count", PageArray.Count);

            // objects
            for (Int32 Index = 0; Index < ObjectArray.Count; Index++)
            {
                ObjectArray[Index].WriteObjectHeaderToPdfFile();
            }

            // save cross reference table position
            Int32 XRefPos = (Int32)PdfFile.BaseStream.Position;

            // cross reference
            PdfFile.WriteFormat("xref\n0 {0}\n0000000000 65535 f \n", ObjectArray.Count + 1);
            foreach (PdfObject PO in ObjectArray)
            {
                PdfFile.WriteFormat("{0:0000000000} 00000 n \n", PO.FilePosition);
            }

            // trailer
            PdfFile.WriteFormat("trailer\n<</Size {0}/Root 1 0 R/ID [{1}{1}]{2}>>\nstartxref\n{3}\n",
                                ObjectArray.Count + 1, ByteArrayToPdfHexString(DocumentID),
                                Encryption == null ? String.Empty : String.Format("/Encrypt {0} 0 R", Encryption.ObjectNumber), XRefPos);

            // write PDF end of file marker
            PdfFile.WriteString("%%EOF\n");

            // close file
            PdfFile.Close();

            // dispose all FontApi resources
            foreach (PdfObject Obj in ObjectArray)
            {
                if (Obj.GetType() == typeof(PdfFont))
                {
                    ((PdfFont)Obj).FontInfo.Dispose();
                }
            }

            // dispose encryption resources
            if (Encryption != null)
            {
                Encryption.Dispose();
                Encryption = null;
            }

            // successful exit
            return;
        }
Esempio n. 3
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        ///     Create PDF document file
        /// </summary>
        /// <remarks>
        ///     <para>The last step of document creation after all pages were constructed.</para>
        ///     <para>
        ///         If PdfDocument was constructed with a file name,
        ///         the CreateFile method will close the file after the file is
        ///         written to. If the PdfDocument was constructed with a stream,
        ///         the CreateFile does not close the stream. It is the user application
        ///         that should close the stream after the stream was used.
        ///     </para>
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public void CreateFile()
        {
            // add destinations to link annotation
            AddDestToLinkAnnot();

            // create named destinations
            CreateNamedDestinations();

            // create page array
            var Kids = new StringBuilder("[");

            for (var Index = 0; Index < PageArray.Count; Index++)
            {
                Kids.AppendFormat("{0} 0 R ", PageArray[Index].ObjectNumber);
            }

            if (Kids.Length > 1)
            {
                Kids.Length--;
            }

            Kids.Append("]");
            PagesObject.Dictionary.Add("/Kids", Kids.ToString());

            // page count
            PagesObject.Dictionary.AddInteger("/Count", PageArray.Count);

            // objects
            for (var Index = 0; Index < ObjectArray.Count; Index++)
            {
                if (ObjectArray[Index].FilePosition == 0)
                {
                    ObjectArray[Index].WriteObjectToPdfFile();
                }
            }

            // save cross reference table position
            var XRefPos = (int)PdfFile.BaseStream.Position;

            // cross reference
            PdfFile.WriteFormat("xref\n0 {0}\n0000000000 65535 f \n", ObjectArray.Count + 1);
            foreach (var PO in ObjectArray)
            {
                if (PO.FilePosition != 0)
                {
                    PdfFile.WriteFormat("{0:0000000000} 00000 n \n", PO.FilePosition);
                }
                else
                {
                    PdfFile.WriteString("0000000000 00000 f \n");
                }
            }

            // finalize trailer dictionary
            TrailerDict.AddInteger("/Size", ObjectArray.Count + 1);

            // trailer
            PdfFile.WriteString("trailer\n");
            TrailerDict.WriteToPdfFile();
            PdfFile.WriteFormat("startxref\n{0}\n", XRefPos);

            // write PDF end of file marker
            PdfFile.WriteString("%%EOF\n");

            // close file and dispose all open resources
            Dispose();

            // successful exit
        }
Esempio n. 4
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Create PDF document file
        /// </summary>
        /// <remarks>
        /// <para>The last step of document creation after all pages were constructed.</para>
        /// <para>If PdfDocument was constructed with a file name,
        /// the CreateFile method will close the file after the file is
        /// written to. If the PdfDocument was constructed with a stream,
        /// the CreateFile does not close the stream. It is the user application
        /// that should close the stream after the stream was used.</para>
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public void CreateFile()
        {
            // add destinations to link annotation
            AddDestToLinkAnnot();

            // create named destinations
            CreateNamedDestinations();

            // Optional content properties dictionary
            if (Layers != null && Layers.LayerList.Count > 0)
            {
                // create optional content dictionary
                Layers.CreateDictionary();

                // add to catalog object
                CatalogObject.Dictionary.AddIndirectReference("/OCProperties", Layers);
            }

            // create page array
            StringBuilder Kids = new StringBuilder("[");

            for (int Index = 0; Index < PageArray.Count; Index++)
            {
                Kids.AppendFormat("{0} 0 R ", PageArray[Index].ObjectNumber);
            }
            if (Kids.Length > 1)
            {
                Kids.Length--;
            }
            Kids.Append("]");
            PagesObject.Dictionary.Add("/Kids", Kids.ToString());

            // page count
            PagesObject.Dictionary.AddInteger("/Count", PageArray.Count);

            // page mode
            if (InitialDocDisplay != InitialDocDisplay.UseNone)
            {
                CatalogObject.Dictionary.Add("/PageMode", InitDocDispText[(int)InitialDocDisplay]);
            }

            // objects
            for (int Index = 0; Index < ObjectArray.Count; Index++)
            {
                if (ObjectArray[Index].FilePosition == 0)
                {
                    ObjectArray[Index].WriteObjectToPdfFile();
                }
            }

            // save cross reference table position
            int XRefPos = (int)PdfFile.BaseStream.Position;

            // cross reference
            PdfFile.WriteFormat("xref\n0 {0}\n0000000000 65535 f \n", ObjectArray.Count + 1);
            foreach (PdfObject PO in ObjectArray)
            {
                if (PO.FilePosition != 0)
                {
                    PdfFile.WriteFormat("{0:0000000000} 00000 n \n", PO.FilePosition);
                }
                else
                {
                    PdfFile.WriteString("0000000000 00000 f \n");
                }
            }

            // finalize trailer dictionary
            TrailerDict.AddInteger("/Size", ObjectArray.Count + 1);

            // trailer
            PdfFile.WriteString("trailer\n");
            TrailerDict.WriteToPdfFile();
            PdfFile.WriteFormat("startxref\n{0}\n", XRefPos);

            // write PDF end of file marker
            PdfFile.WriteString("%%EOF\n");

            // close file and dispose all open resources
            Dispose();

            // successful exit
            return;
        }