コード例 #1
0
        private PdfEmbeddedFile
        (
            PdfDocument Document,
            string FileName,
            string PdfFileName
        ) : 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
            var FI = new FileInfo(FileName);

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

            var FileLength = (int)FI.Length;

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

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

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

            // file data content byte array
            EmbeddedFile.ObjectValueArray = 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(EmbeddedFile.ObjectValueArray, 0, FileLength) != FileLength)
                {
                    throw new Exception();
                }
            }

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

            // close the file
            DataStream.Close();

            // debug
            if (Document.Debug)
            {
                EmbeddedFile.ObjectValueArray = Document.TextToByteArray("*** MEDIA FILE PLACE HOLDER ***");
            }

            // write stream
            EmbeddedFile.WriteObjectToPdfFile();

            // 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);
        }