示例#1
0
        virtual public void FileSpecCheckTest2()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            MemoryStream txt  = new MemoryStream();
            StreamWriter outp = new StreamWriter(txt);

            outp.Write("<foo><foo2>Hello world</foo2></foo>");
            outp.Close();

            PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, null, "foo.xml", txt.ToArray());

            fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Unspecified);

            writer.AddFileAttachment(fs);

            document.Close();
        }
示例#2
0
        /* ----------------------------------------------------------------- */
        ///
        /// Set
        ///
        /// <summary>
        /// Sets attachments to the specified writer.
        /// </summary>
        ///
        /// <param name="src">PdfCopy object.</param>
        /// <param name="data">Collection of attachments.</param>
        ///
        /* ----------------------------------------------------------------- */
        public static void Set(this PdfCopy src, IEnumerable <Attachment> data)
        {
            var done = new List <Attachment>();

            foreach (var item in data)
            {
                var dup = done.Any(e =>
                                   e.Name.ToLower() == item.Name.ToLower() &&
                                   e.Length == item.Length &&
                                   e.Checksum.SequenceEqual(item.Checksum)
                                   );

                if (dup)
                {
                    continue;
                }

                var fs = item is EmbeddedAttachment?
                         PdfFileSpecification.FileEmbedded(src, null, item.Name, item.Data) :
                             PdfFileSpecification.FileEmbedded(src, item.Source, item.Name, null);

                fs.SetUnicodeFileName(item.Name, true);
                src.AddFileAttachment(fs);
                done.Add(item);
            }
        }
示例#3
0
        virtual public void FileSpecCheckTest6()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create),
                                                         PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open,
                                                        FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfDictionary _params = new PdfDictionary();

            _params.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(
                writer, RESOURCES + "foo.xml", "foo.xml", null, false, "text/xml", _params);

            fileSpec.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Data);

            writer.AddFileAttachment(fileSpec);

            document.Close();
        }
示例#4
0
        public virtual void FileSpecCheckTest7()
        {
            FileStream   inPdf = new FileStream(RESOURCES + "fileSpec.pdf", FileMode.Open);
            MemoryStream xml   = new MemoryStream();
            StreamWriter sr    = new StreamWriter(xml);

            sr.Write("<foo><foo2>Hello world</foo2></foo>");
            sr.Close();

            MemoryStream output  = new MemoryStream();
            PdfReader    reader  = new PdfReader(inPdf);
            PdfAStamper  stamper = new PdfAStamper(reader, output, PdfAConformanceLevel.PDF_A_3B);

            stamper.CreateXmpMetadata();

            PdfDictionary embeddedFileParams = new PdfDictionary();

            embeddedFileParams.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(stamper.Writer, "foo", "foo",
                                                                        xml.ToArray(), "text/xml", embeddedFileParams, 0);

            fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Source);
            stamper.AddFileAttachment("description", fs);

            stamper.Close();
            reader.Close();
        }
示例#5
0
    public void Write(Stream stream)
    {
        using (Document document = new Document()) {
            PdfWriter writer = PdfWriter.GetInstance(document, stream);

            document.Open();
            document.Add(new Paragraph("This document contains a collection of PDFs"));

            PdfIndirectReference parentFolderObjectReference = writer.PdfIndirectReference;
            PdfIndirectReference childFolder1ObjectReference = writer.PdfIndirectReference;
            PdfIndirectReference childFolder2ObjectReference = writer.PdfIndirectReference;

            PdfDictionary parentFolderObject = GetFolderDictionary(0);
            parentFolderObject.Put(new PdfName("Child"), childFolder1ObjectReference);
            parentFolderObject.Put(PdfName.NAME, new PdfString());

            PdfDictionary childFolder1Object = GetFolderDictionary(1);
            childFolder1Object.Put(PdfName.NAME, new PdfString("Folder 1"));
            childFolder1Object.Put(PdfName.PARENT, parentFolderObjectReference);
            childFolder1Object.Put(PdfName.NEXT, childFolder2ObjectReference);

            PdfDictionary childFolder2Object = GetFolderDictionary(2);
            childFolder2Object.Put(PdfName.NAME, new PdfString("Folder 2"));
            childFolder2Object.Put(PdfName.PARENT, parentFolderObjectReference);

            PdfCollection       collection = new PdfCollection(PdfCollection.DETAILS);
            PdfCollectionSchema schema     = CollectionSchema();
            collection.Schema = schema;
            collection.Sort   = new PdfCollectionSort(keys);
            collection.Put(new PdfName("Folders"), parentFolderObjectReference);
            writer.Collection = collection;

            PdfFileSpecification fs;
            PdfCollectionItem    item;

            fs   = PdfFileSpecification.FileEmbedded(writer, file1Path, File1, null);
            item = new PdfCollectionItem(schema);
            item.AddItem("Type", "pdf");
            fs.AddCollectionItem(item);
            // the description is apparently used to place the
            // file in a particular folder.  The number between the < and >
            // is used to put the file in the folder that has the matching id
            fs.AddDescription(GetDescription(1, File1), false);
            writer.AddFileAttachment(fs);

            fs   = PdfFileSpecification.FileEmbedded(writer, file2Path, File2, null);
            item = new PdfCollectionItem(schema);
            item.AddItem("Type", "pdf");
            fs.AddCollectionItem(item);
            fs.AddDescription(GetDescription(2, File2), false);
            writer.AddFileAttachment(fs);

            writer.AddToBody(parentFolderObject, parentFolderObjectReference);
            writer.AddToBody(childFolder1Object, childFolder1ObjectReference);
            writer.AddToBody(childFolder2Object, childFolder2ObjectReference);

            document.Close();
        }
    }
示例#6
0
        private void addAttachment(AttachmentFile file)
        {
            var pdfDictionary = new PdfDictionary();

            pdfDictionary.Put(PdfName.MODDATE, new PdfDate(DateTime.Now));
            var fs = PdfFileSpecification.FileEmbedded(_writer, string.Empty, file.FileName, file.Content, true, null, pdfDictionary);

            _writer.AddFileAttachment(fs);
        }
示例#7
0
        private static void SetPdfAConformance(PdfReader reader, Document doc, MemoryStream ms)
        {
            // Create PdfAWriter with PdfAConformanceLevel.PDF_A_3B option if you
            // want to get a PDF/A-3b compliant document.
            PdfAWriter writer = PdfAWriter.GetInstance(doc, ms, _pdfaConformanceLevel);

            // Create XMP metadata. It's a PDF/A requirement.
            writer.CreateXmpMetadata();

            doc.Open();

            // Set output intent. PDF/A requirement.
            ICC_Profile icc = ICC_Profile
                              .GetInstance(new FileStream(@"resources/sRGB Color Space Profile.icm", FileMode.Open));

            writer.SetOutputIntents("Custom", "", "http://www.color.org",
                                    "sRGB IEC61966-2.1", icc);

            // Creating PDF/A-3 compliant attachment.
            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(
                writer, _inputFilePath,
                "test.pdf", null, "application/pdf", parameters, 0);

            fileSpec.Put(new PdfName("AFRelationship"), new PdfName("Data"));
            writer.AddFileAttachment("test.pdf", fileSpec);
            PdfArray array = new PdfArray {
                fileSpec.Reference
            };

            writer.ExtraCatalog.Put(new PdfName("AF"), array);

            doc.AddDocListener(writer);
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                doc.SetPageSize(reader.GetPageSize(i));
                doc.NewPage();
                PdfContentByte  cb       = writer.DirectContent;
                PdfImportedPage page     = writer.GetImportedPage(reader, i);
                int             rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
                }
            }
        }
        private static PdfFileSpecification EmbeddedAttachment(string filePath, string fileName, string mimeType,
                                                               PdfName afRelationship, PdfAWriter writer, string description)
        {
            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.MODDATE, new PdfDate(File.GetLastWriteTime(filePath)));
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(writer, filePath, fileName, null, mimeType,
                                                                              parameters, 0);

            fileSpec.Put(new PdfName("AFRelationship"), afRelationship);
            writer.AddFileAttachment(description, fileSpec);
            return(fileSpec);
        }
示例#9
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                writer.AddDeveloperExtension(
                    PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3
                    );
                // step 3
                document.Open();
                // step 4
                // we prepare a RichMediaAnnotation
                RichMediaAnnotation richMedia = new RichMediaAnnotation(
                    writer, new Rectangle(36, 400, 559, 806)
                    );
                // we embed the swf file
                PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                    writer, RESOURCE, "FestivalCalendar1.swf", null
                    );
                // we declare the swf file as an asset
                PdfIndirectReference asset = richMedia.AddAsset(
                    "FestivalCalendar1.swf", fs
                    );
                // we create a configuration
                RichMediaConfiguration configuration = new RichMediaConfiguration(
                    PdfName.FLASH
                    );
                RichMediaInstance instance  = new RichMediaInstance(PdfName.FLASH);
                RichMediaParams   flashVars = new RichMediaParams();
                String            vars      = "&day=2011-10-13";
                flashVars.FlashVars = vars;
                instance.Params     = flashVars;
                instance.Asset      = asset;
                configuration.AddInstance(instance);
                // we add the configuration to the annotation
                PdfIndirectReference configurationRef = richMedia.AddConfiguration(
                    configuration
                    );
                // activation of the rich media
                RichMediaActivation activation = new RichMediaActivation();
                activation.Configuration = configurationRef;
                richMedia.Activation     = activation;
                // we add the annotation
                PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation();
                richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT;
                writer.AddAnnotation(richMediaAnnotation);
            }
        }
 /// <summary>
 /// Adds all of the file attachments.
 /// </summary>
 public void AddFileAttachments()
 {
     if (PageSetup.FileAttachments == null || !PageSetup.FileAttachments.Any())
     {
         return;
     }
     foreach (var file in PageSetup.FileAttachments)
     {
         var fileInfo      = new FileInfo(file.FilePath);
         var pdfDictionary = new PdfDictionary();
         pdfDictionary.Put(PdfName.Moddate, new PdfDate(fileInfo.LastWriteTime));
         var fs = PdfFileSpecification.FileEmbedded(PdfWriter, file.FilePath, fileInfo.Name, null, true, null, pdfDictionary);
         PdfWriter.AddFileAttachment(file.Description, fs);
     }
 }
示例#11
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                document.Add(new Paragraph(
                                 "This document contains a collection of PDFs,"
                                 + " one per Stanley Kubrick movie."
                                 ));

                PdfCollection       collection = new PdfCollection(PdfCollection.DETAILS);
                PdfCollectionSchema schema     = _collectionSchema();
                collection.Schema = schema;
                PdfCollectionSort sort = new PdfCollectionSort("YEAR");
                sort.SetSortOrder(false);
                collection.Sort            = sort;
                collection.InitialDocument = "Eyes Wide Shut";
                writer.Collection          = collection;

                PdfCollectionItem   item;
                IEnumerable <Movie> movies = PojoFactory.GetMovies(1);
                foreach (Movie movie in movies)
                {
                    PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                        writer, null,
                        String.Format("kubrick_{0}.pdf", movie.Imdb),
                        CreateMoviePage(movie)
                        );
                    fs.AddDescription(movie.Title, false);

                    item = new PdfCollectionItem(schema);
                    item.AddItem("TITLE", movie.GetMovieTitle(false));
                    if (movie.GetMovieTitle(true) != null)
                    {
                        item.SetPrefix("TITLE", movie.GetMovieTitle(true));
                    }
                    item.AddItem("DURATION", movie.Duration.ToString());
                    item.AddItem("YEAR", movie.Year.ToString());
                    fs.AddCollectionItem(item);
                    writer.AddFileAttachment(fs);
                }
            }
        }
示例#12
0
        virtual public void FileSpecCheckTest5()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest5.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            MemoryStream txt  = new MemoryStream();
            StreamWriter outp = new StreamWriter(txt);

            outp.Write("<foo><foo2>Hello world</foo2></foo>");
            outp.Close();

            bool exceptionThrown = false;

            try {
                PdfFileSpecification fs
                    = PdfFileSpecification.FileEmbedded(writer,
                                                        null, "foo.xml", txt.ToArray());
                writer.AddFileAttachment(fs);
            }
            catch (PdfAConformanceException e) {
                if (e.GetObject() != null && e.Message.Equals("The file specification dictionary for an embedded file shall contain correct AFRelationship key."))
                {
                    exceptionThrown = true;
                }
            }
            if (!exceptionThrown)
            {
                Assert.Fail("PdfAConformanceException with correct message should be thrown.");
            }
        }
示例#13
0
        public void CreatePDFFile_old(string strPDFPath, string attachment, string password)
        {
            try
            {
                string fileName = Path.GetFileName(attachment);

                using (Document document = new Document(cPageSize.GetDocumentWithBackroundColor(cPageSize.A4, new BaseColor(245, 245, 245)), 0f, 0f, 0f, 17f))
                {
                    using (FileStream pdf = new FileStream(strPDFPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdf))
                        {
                            document.Open();
                            var fs = PdfFileSpecification.FileEmbedded(pdfWriter, attachment, fileName, null);

                            fs.AddDescription(fileName, false);
                            PdfAnnotation annotation = new PdfAnnotation(pdfWriter, new Rectangle(1550f, 50f, 150f, 500f));
                            annotation.Put(PdfName.SUBTYPE, PdfName.FILEATTACHMENT);
                            annotation.Put(PdfName.CONTENTS, new PdfString(fileName));
                            annotation.Put(PdfName.FS, fs.Reference);

                            document.Add(new Paragraph("Attached files:"));

                            Chunk linkChunk = new Chunk("this is what we need to achive using pdfanotation");
                            linkChunk.SetAnnotation(annotation);
                            Phrase phrase = new Phrase();
                            phrase.Add(linkChunk);
                            document.Add(phrase);
                            document.Close();
                            pdfWriter.Close();
                            pdfWriter.Dispose();
                        }
                        pdf.Close();
                        pdf.Dispose();
                    }
                    document.Dispose();
                }
            }
            catch (Exception ex)
            {
            }

            PasswordProtectPDF(strPDFPath, password);
        }
示例#14
0
        public void CreatePdf(String dest)
        {
            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create));

            document.Open();
            document.Add(new Paragraph("Portable collection"));
            PdfCollection collection = new PdfCollection(PdfCollection.TILE);

            writer.Collection = collection;
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(writer, DATA, "united_states.csv", null);

            writer.AddFileAttachment("united_states.csv", fileSpec);
            fileSpec = PdfFileSpecification.FileEmbedded(writer, HELLO, "hello.pdf", null);
            writer.AddFileAttachment("hello.pdf", fileSpec);
            fileSpec = PdfFileSpecification.FileEmbedded(writer, IMG, "berlin2013.jpg", null);
            writer.AddFileAttachment("berlin2013.jpg", fileSpec);
            document.Close();
        }
示例#15
0
        internal void ExtractAttachments(string file_name, string folderName, PdfWriter write)
        {
            PdfDictionary documentNames = null;
            PdfDictionary embeddedFiles = null;
            PdfDictionary fileArray     = null;
            PdfDictionary file          = null;
            PRStream      stream        = null;

            PdfReader     reader  = new PdfReader(file_name);
            PdfDictionary catalog = reader.Catalog;

            documentNames = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.NAMES));

            if (documentNames != null)
            {
                embeddedFiles = (PdfDictionary)PdfReader.GetPdfObject(documentNames.Get(PdfName.EMBEDDEDFILES));
                if (embeddedFiles != null)
                {
                    PdfArray filespecs = embeddedFiles.GetAsArray(PdfName.NAMES);

                    for (int i = 0; i < filespecs.Size; i++)
                    {
                        i++;
                        fileArray = filespecs.GetAsDict(i);
                        file      = fileArray.GetAsDict(PdfName.EF);

                        foreach (PdfName key in file.Keys)
                        {
                            stream = (PRStream)PdfReader.GetPdfObject(file.GetAsIndirectObject(key));
                            string attachedFileName  = folderName + fileArray.GetAsString(key).ToString();
                            byte[] attachedFileBytes = PdfReader.GetStreamBytes(stream);
                            //graba el anexo extraido
                            System.IO.File.WriteAllBytes(attachedFileName, attachedFileBytes);
                            //adjunta los anexos
                            PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(write, attachedFileName, fileArray.GetAsString(key).ToString(), null);
                            write.AddFileAttachment(pfs);
                            //borramos los archivos extraidos
                            System.IO.File.Delete(attachedFileName);
                        }
                    }
                }
            }
        }
示例#16
0
        public static PdfAnnotation ConvertAnnotation(PdfWriter writer, Annotation annot, Rectangle defaultRect)
        {
            switch (annot.AnnotationType)
            {
            case Annotation.URL_NET:
                return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((Uri)annot.Attributes[Annotation.URL])));

            case Annotation.URL_AS_STRING:
                return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.FILE])));

            case Annotation.FILE_DEST:
                return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.FILE], (String)annot.Attributes[Annotation.DESTINATION])));

            case Annotation.SCREEN:
                bool[] sparams  = (bool[])annot.Attributes[Annotation.PARAMETERS];
                String fname    = (String)annot.Attributes[Annotation.FILE];
                String mimetype = (String)annot.Attributes[Annotation.MIMETYPE];
                PdfFileSpecification fs;
                if (sparams[0])
                {
                    fs = PdfFileSpecification.FileEmbedded(writer, fname, fname, null);
                }
                else
                {
                    fs = PdfFileSpecification.FileExtern(writer, fname);
                }
                PdfAnnotation ann = PdfAnnotation.CreateScreen(writer, new Rectangle(annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry()),
                                                               fname, fs, mimetype, sparams[1]);
                return(ann);

            case Annotation.FILE_PAGE:
                return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.FILE], (int)annot.Attributes[Annotation.PAGE])));

            case Annotation.NAMED_DEST:
                return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((int)annot.Attributes[Annotation.NAMED])));

            case Annotation.LAUNCH:
                return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.APPLICATION], (String)annot.Attributes[Annotation.PARAMETERS], (String)annot.Attributes[Annotation.OPERATION], (String)annot.Attributes[Annotation.DEFAULTDIR])));

            default:
                return(new PdfAnnotation(writer, defaultRect.Left, defaultRect.Bottom, defaultRect.Right, defaultRect.Top, new PdfString(annot.Title, PdfObject.TEXT_UNICODE), new PdfString(annot.Content, PdfObject.TEXT_UNICODE)));
            }
        }
        private void addAsAttachment(IDataExporter exporter, byte[] data)
        {
            if (string.IsNullOrEmpty(exporter.FileName))
            {
                throw new InvalidOperationException("Please fill the exporter.FileName.");
            }

            if (string.IsNullOrEmpty(exporter.Description))
            {
                exporter.Description = "Exported data";
            }

            var pdfDictionary = new PdfDictionary();

            pdfDictionary.Put(PdfName.Moddate, new PdfDate(DateTime.Now));
            var fs = PdfFileSpecification.FileEmbedded(_sharedData.PdfWriter, null, exporter.FileName, data, true, null, pdfDictionary);

            _sharedData.PdfWriter.AddFileAttachment(exporter.Description, fs);
        }
示例#18
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                    writer, RESOURCE, "foxdog.mpg", null
                    );
                writer.AddAnnotation(PdfAnnotation.CreateScreen(
                                         writer,
                                         new Rectangle(200f, 700f, 400f, 800f),
                                         "Fox and Dog", fs,
                                         "video/mpeg", true
                                         ));
            }
        }
示例#19
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                Image img = Image.GetInstance(IMG_BOX);
                document.Add(img);
                List           list = new List(List.UNORDERED, 20);
                PdfDestination dest = new PdfDestination(PdfDestination.FIT);
                dest.AddFirst(new PdfNumber(1));
                IEnumerable <Movie> box = PojoFactory.GetMovies(1)
                                          .Concat(PojoFactory.GetMovies(4))
                ;
                foreach (Movie movie in box)
                {
                    if (movie.Year > 1960)
                    {
                        PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                            writer, null,
                            String.Format("kubrick_{0}.pdf", movie.Imdb),
                            CreateMoviePage(movie)
                            );
                        fs.AddDescription(movie.Title, false);
                        writer.AddFileAttachment(fs);
                        ListItem            item   = new ListItem(movie.MovieTitle);
                        PdfTargetDictionary target = new PdfTargetDictionary(true);
                        target.EmbeddedFileName = movie.Title;
                        PdfAction action = PdfAction.GotoEmbedded(null, target, dest, true);
                        Chunk     chunk  = new Chunk(" (see info)");
                        chunk.SetAction(action);
                        item.Add(chunk);
                        list.Add(item);
                    }
                }
                document.Add(list);
            }
        }
示例#20
0
// ---------------------------------------------------------------------------

        /**
         * Creates the PDF.
         * @return the bytes of a PDF file.
         */
        public byte[] CreatePdf()
        {
            IEnumerable <Movie> movies = PojoFactory.GetMovies(1);

            using (MemoryStream ms = new MemoryStream()) {
                using (Document document = new Document()) {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();
                    document.Add(new Paragraph(
                                     "'Stanley Kubrick: A Life in Pictures'"
                                     + " is a documentary about Stanley Kubrick and his films:"
                                     ));
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("<movies>");
                    List list = new List(List.UNORDERED, 20);
                    foreach (Movie movie in movies)
                    {
                        sb.AppendLine("<movie>");
                        sb.AppendLine(String.Format(
                                          "<title>{0}</title>",
                                          XMLUtil.EscapeXML(movie.MovieTitle, true)
                                          ));
                        sb.AppendLine(String.Format("<year>{0}</year>", movie.Year));
                        sb.AppendLine(String.Format(
                                          "<duration>{0}</duration>", movie.Duration
                                          ));
                        sb.AppendLine("</movie>");
                        ListItem item = new ListItem(movie.MovieTitle);
                        list.Add(item);
                    }
                    document.Add(list);
                    sb.Append("</movies>");
                    PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                        writer, null, "kubrick.xml", Encoding.UTF8.GetBytes(sb.ToString())
                        //txt.toByteArray()
                        );
                    writer.AddFileAttachment(fs);
                }
                return(ms.ToArray());
            }
        }
示例#21
0
        public static void EmbedEdiconData(string srcPdfFileName, string ediconXmlData, string dstPdfFileName)
        {
            //
            PdfReader  reader  = null;
            PdfStamper stamper = null;
            FileStream destPdfFileFileStream = null;

            //
            try
            {
                reader = new PdfReader(srcPdfFileName);
                destPdfFileFileStream = new FileStream(dstPdfFileName, FileMode.OpenOrCreate);
                stamper = new PdfStamper(reader, destPdfFileFileStream);
                PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(stamper.Writer, null /*srcDataFileName*/, EDICON_EMBED_FILENAME, Encoding.UTF8.GetBytes(ediconXmlData));
                stamper.AddFileAttachment(EDICON_EMBED_FILENAME, pfs);
            }
            catch (Exception ex)
            {
                Console.WriteLine("EmbedEdiconData error: " + ex.Message);
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                //
                if (stamper != null)
                {
                    stamper.Close();
                }
                //
                if (destPdfFileFileStream != null)
                {
                    destPdfFileFileStream.Close();
                }
            }
        }
示例#22
0
        public void Write(Stream stream, string[] pfade)
        {
            using (Document document = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(document, stream);

                document.Open();
                document.Add(new Paragraph(" "));

                PdfIndirectReference parentFolderObjectReference = writer.PdfIndirectReference;

                PdfCollection       collection = new PdfCollection(PdfCollection.DETAILS);
                PdfCollectionSchema schema     = CollectionSchema();
                collection.Schema = schema;
                collection.Sort   = new PdfCollectionSort(keys);
                collection.Put(new PdfName("Vorlagen BA"), parentFolderObjectReference);
                writer.Collection = collection;

                PdfFileSpecification fs;
                PdfCollectionItem    item;

                int nummer = 1;

                foreach (string pfad in pfade)
                {
                    String Filename = Path.GetFileName(pfad);
                    fs   = PdfFileSpecification.FileEmbedded(writer, pfad, string.Format("{0} - {1}", nummer, Filename), null);
                    item = new PdfCollectionItem(schema);
                    item.AddItem("Type", "pdf");
                    fs.AddCollectionItem(item);
                    fs.AddDescription(GetDescription(Filename), false);
                    writer.AddFileAttachment(fs);

                    nummer++;
                }

                document.Close();
            }
        }
示例#23
0
        public void ZugferdInvoiceTest()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "zugferdInvoiceTest.pdf", FileMode.Create),
                                                         PdfAConformanceLevel.ZUGFeRD);

            writer.CreateXmpMetadata();
            writer.XmpWriter.SetProperty(PdfAXmpWriter.zugferdSchemaNS, PdfAXmpWriter.zugferdDocumentFileName, "invoice.xml");
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));
            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open,
                                                        FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(
                writer, RESOURCES + "invoice.xml",
                "invoice.xml", null, "application/xml", parameters, 0);

            fileSpec.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Alternative);
            writer.AddFileAttachment("invoice.xml", fileSpec);
            PdfArray array = new PdfArray();

            array.Add(fileSpec.Reference);
            writer.ExtraCatalog.Put(new PdfName("AF"), array);

            document.Close();
        }
示例#24
0
        public void CreatePDFFile(string strPDFPath, string[] selectedFiles, string password)
        {
            try
            {
                using (Document document = new Document(cPageSize.GetDocumentWithBackroundColor(cPageSize.A4, new BaseColor(245, 245, 245)), 0f, 0f, 0f, 17f))
                {
                    using (FileStream pdf = new FileStream(strPDFPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdf))
                        {
                            document.Open();

                            Font titleFont = FontFactory.GetFont("Verdana", 12f, Font.BOLD);
                            Font listFont  = FontFactory.GetFont("Verdana", 9f, Font.NORMAL);

                            Paragraph pMain      = new Paragraph();
                            Chunk     chunkTitle = new Chunk("Attached files:", titleFont);
                            chunkTitle.SetUnderline(0.5f, -1.5f);
                            pMain.Add(chunkTitle);

                            for (int i = 0; i < selectedFiles.Length; i++)
                            {
                                string fileName = Path.GetFileName(selectedFiles[i]);

                                var fs = PdfFileSpecification.FileEmbedded(pdfWriter, selectedFiles[i], fileName, null);

                                //fs.AddDescription(fileName, false);

                                //var rect = new Rectangle(10000f,10000f);
                                Rectangle rect = new Rectangle(100, 400, 500, 800);
                                rect.Border      = Rectangle.BOX;
                                rect.BorderWidth = 0.5f;
                                rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);

                                PdfAnnotation annotation = new PdfAnnotation(pdfWriter, rect);
                                annotation.Put(PdfName.NAME, PdfName.ANNOT);
                                annotation.Put(PdfName.SUBTYPE, PdfName.FILEATTACHMENT);
                                annotation.Put(PdfName.CONTENTS, new PdfString(fileName));
                                annotation.Put(PdfName.FS, fs.Reference);

                                //PdfTemplate tmp = PdfTemplate.CreateTemplate(pdfWriter, document.PageSize.Width, 100);
                                PdfAppearance ap = pdfWriter.DirectContent.CreateAppearance(rect.Width, rect.Height);
                                annotation.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);

                                Chunk linkChunk = new Chunk("(" + (i + 1).ToString() + ") " + fileName, listFont);
                                linkChunk.SetAnnotation(annotation);
                                Phrase phrase = new Phrase();
                                phrase.Add(new Chunk("\n"));
                                phrase.Add(linkChunk);
                                //document.Add(phrase);
                                //document.Add(new Chunk("\n"));

                                //document.Close();
                                //pdfWriter.Close();
                                //pdfWriter.Dispose();
                                pMain.Add(phrase);
                            }
                            pMain.IndentationLeft = 10f;
                            document.Add(pMain);
                            //pdf.Close();
                            //pdf.Dispose();
                        }
                        //document.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
            }

            PasswordProtectPDF(strPDFPath, password);
        }
示例#25
0
        static void Main(string[] args)
        {
            int
                MaxCell;

            string
                CurrentDirectory = System.IO.Directory.GetCurrentDirectory();

            CurrentDirectory = CurrentDirectory.Substring(0, CurrentDirectory.LastIndexOf("bin", CurrentDirectory.Length - 1));

            string
                OutputFileName = CurrentDirectory + "wdpt.pdf",
                ImageName      = CurrentDirectory + "TestImage.jpg";

            Document
                pdfDocument = new Document(PageSize.A4);

            PdfWriter
                writer = PdfWriter.GetInstance(pdfDocument, new FileStream(OutputFileName, FileMode.Create));

            pdfDocument.Open();

            Phrase
                phrase = new Phrase(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT", new Font(Font.FontFamily.COURIER, 8));

            Rectangle
                page = pdfDocument.PageSize;

            PdfPTable
                head = new PdfPTable(1);

            head.TotalWidth = page.Width;

            PdfPCell
                cell = new PdfPCell(phrase);

            cell.Border              = Rectangle.NO_BORDER;
            cell.VerticalAlignment   = Element.ALIGN_TOP;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            head.AddCell(cell);
            head.WriteSelectedRows(
                // first/last row; -1 writes all rows
                0, -1,
                // left offset
                0,
                // ** bottom** yPos of the table
                page.Height - pdfDocument.TopMargin + head.TotalHeight + 20,
                writer.DirectContent
                );

            pdfDocument.Add(new Paragraph("Here is a test of creating a PDF"));

            Paragraph
                p = new Paragraph();

            Font
                font = FontFactory.GetFont("Times New Roman", 16, Font.NORMAL);

            p.Font = font;
            p.Add("Times New Roman");
            pdfDocument.Add(p);

            Chunk
                c = new Chunk("Times New Roman", FontFactory.GetFont("Times New Roman", 16));

            c.SetCharacterSpacing(10);
            p = new Paragraph(c);
            pdfDocument.Add(p);

            BaseFont
                bfComic = BaseFont.CreateFont("c:\\windows\\fonts\\comic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            font = new Font(bfComic, 12);
            pdfDocument.Add(new Paragraph("Some cyrillic characters: \u0418\u044f", font));

            c = new Chunk("Some text in Verdana \n", FontFactory.GetFont("Verdana", 12));

            Chunk
                c2 = new Chunk("More text in Tahoma", FontFactory.GetFont("Tahoma", 14));

            p = new Paragraph();
            p.Add(c);
            p.Add(c2);
            pdfDocument.Add(p);

            Image
                image = Image.GetInstance(ImageName);

            c = new Chunk("Check out this wicked graphic: \n", FontFactory.GetFont("Verdana", 12));
            p = new Paragraph();
            p.Add(c);
            p.Add(image);
            pdfDocument.Add(p);

            PdfPTable
                table = new PdfPTable(3);

            cell                     = new PdfPCell(new Phrase("Header spanning 3 columns"));
            cell.Colspan             = 3;
            cell.HorizontalAlignment = 1;             //0=Left, 1=Centre, 2=Right
            table.AddCell(cell);
            table.AddCell("Col 1 Row 1");
            table.AddCell("Col 2 Row 1");
            table.AddCell("Col 3 Row 1");
            table.AddCell("Col 1 Row 2");
            table.AddCell("Col 2 Row 2");
            table.AddCell("Col 3 Row 2");
            pdfDocument.Add(table);

            table = new PdfPTable(2);
            //actual width of table in points
            table.TotalWidth = 216f;
            //fix the absolute width of the table
            table.LockedWidth = true;

            //relative col widths in proportions - 1/3 and 2/3
            float[] widths = new float[] { 1f, 2f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;
            //leave a gap before and after the table
            table.SpacingBefore = 20f;
            table.SpacingAfter  = 30f;

            cell                     = new PdfPCell(new Phrase("Products"));
            cell.Colspan             = 2;
            cell.Border              = 0;
            cell.HorizontalAlignment = 1;
            table.AddCell(cell);

            string
            //connect = "Server=NOZHENKO-PC\\SQLEXPRESS;database=testdb;Integrated Security=SSPI";
                connect = "Server=nozhenko-s8k;Database=testdb;Trusted_Connection=True;";

            using (SqlConnection conn = new SqlConnection(connect))
            {
                string
                    query = "SELECT ID, Name FROM Staff";

                SqlCommand
                    cmd = new SqlCommand(query, conn);

                try
                {
                    conn.Open();
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        BaseFont
                            baseFont = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                        font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

                        while (rdr.Read())
                        {
                            table.AddCell(rdr[0].ToString());
                            table.AddCell(new Paragraph(rdr[1].ToString(), font));
                        }
                    }
                }
                catch (Exception eException)
                {
                    Console.WriteLine(eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace);
                }

                pdfDocument.Add(table);
            }

            table = new PdfPTable(3);

            cell        = new PdfPCell();
            cell.Phrase = new Phrase("Cell 1");
            cell.Image  = Image.GetInstance(CurrentDirectory + "pdf.gif");
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("Cell 2", new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL, BaseColor.YELLOW)));
            cell.BackgroundColor   = new BaseColor(0, 150, 0);
            cell.BorderColor       = new BaseColor(255, 242, 0);
            cell.Border            = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
            cell.BorderWidthBottom = 3f;
            cell.BorderWidthTop    = 3f;
            cell.PaddingBottom     = 10f;
            cell.PaddingLeft       = 20f;
            cell.PaddingTop        = 4f;
            table.AddCell(cell);
            table.AddCell("Cell 3");
            pdfDocument.Add(table);

            table             = new PdfPTable(4);
            table.TotalWidth  = 400f;
            table.LockedWidth = true;

            PdfPCell
                header = new PdfPCell(new Phrase("Header"));

            header.Colspan = 4;
            table.AddCell(header);
            table.AddCell("Cell 1");
            table.AddCell("Cell 2");
            table.AddCell("Cell 3");
            table.AddCell("Cell 4");

            PdfPTable
                nested = new PdfPTable(1);

            nested.AddCell("Nested Row 1");
            nested.AddCell("Nested Row 2");
            nested.AddCell("Nested Row 3");

            PdfPCell
                nesthousing = new PdfPCell(nested);

            nesthousing.Padding = 0f;
            table.AddCell(nesthousing);

            PdfPCell
                bottom = new PdfPCell(new Phrase("bottom"));

            bottom.Colspan = 3;
            table.AddCell(bottom);
            pdfDocument.Add(table);

            table                     = new PdfPTable(3);
            table.TotalWidth          = 144f;
            table.LockedWidth         = true;
            table.HorizontalAlignment = 0;

            PdfPCell
                left = new PdfPCell(new Paragraph("Rotated"));

            left.Rotation = 90;
            table.AddCell(left);

            PdfPCell
                middle = new PdfPCell(new Paragraph("Rotated"));

            middle.Rotation = -90;
            table.AddCell(middle);
            table.AddCell("Not Rotated");
            pdfDocument.Add(table);

            string
                text = "This is a paragraph. It is represted" +
                       " by a Paragraph object in the iTextSharp " +
                       "library. Here, we're creating paragraphs with " +
                       "various styles in order to test out iTextSharp." +
                       " This paragraph will take up multiple lines " +
                       "and allow for a more complete example.";

            // Add a basic paragraph
            pdfDocument.Add(new Paragraph(text));


            // Add a paragraph that's underlined and indented
            Paragraph
                p2 = new Paragraph(text);

            p2.IndentationLeft = 36;
            p2.Font.SetStyle(Font.UNDERLINE);
            pdfDocument.Add(p2);

            // Add a paragraph that's underlined and in bold
            pdfDocument.Add(new Paragraph(text, FontFactory.GetFont("Courier", Font.DEFAULTSIZE, Font.UNDERLINE | Font.BOLD)));

            // Add a really big paragraph
            pdfDocument.Add(new Paragraph(text, new Font(Font.FontFamily.HELVETICA, 36)));

            // Add a green, centered paragraph
            Paragraph
                p5 = new Paragraph(text, new Font(Font.FontFamily.TIMES_ROMAN, Font.DEFAULTSIZE, Font.NORMAL, BaseColor.GREEN));

            p5.Alignment = Element.ALIGN_CENTER;
            pdfDocument.Add(p5);

            // Add a double-spaced paragraph with
            // an indented first line
            Paragraph
                p6 = new Paragraph(text);

            p6.FirstLineIndent   = 36;
            p6.MultipliedLeading = 2;
            pdfDocument.Add(p6);

            // Add a paragraph with multiple styles
            // Each word gets bigger
            Paragraph
                ascending = new Paragraph();

            ascending.SpacingBefore = 72;
            for (int i = 1; i <= 5; i++)
            {
                ascending.Add(new Chunk("Hello", new Font(Font.FontFamily.HELVETICA, i * 5)));
            }
            pdfDocument.Add(ascending);

            Paragraph
                hello = new Paragraph("Hello. This is a paragraph.");

            hello.Font.SetStyle(Font.ITALIC);
            pdfDocument.Add(hello);

            Paragraph
                fancy = new Paragraph();

            Chunk
                bold = new Chunk("This ");

            bold.Font.SetStyle(Font.BOLD);
            fancy.Add(bold);

            Chunk
                italics = new Chunk("is a");

            italics.Font.SetStyle(Font.ITALIC);
            fancy.Add(italics);

            Chunk
                big = new Chunk("fancy");

            big.Font.Size = 20;
            big.Font.SetStyle(Font.BOLD);
            fancy.Add(big);

            Chunk
                struck = new Chunk("paragraph.");

            struck.Font.SetStyle(Font.STRIKETHRU);
            fancy.Add(struck);
            pdfDocument.Add(fancy);

            Paragraph
                spaced = new Paragraph("This has a lot of space around it.");

            spaced.SpacingBefore    = 72;
            spaced.SpacingAfter     = 72;
            spaced.IndentationLeft  = 72;
            spaced.IndentationRight = 72;
            pdfDocument.Add(spaced);

            p = new Paragraph("p.FirstLineIndent = 36");
            p.FirstLineIndent = 36;
            pdfDocument.Add(p);

            p           = new Paragraph("p.Alignment = Element.ALIGN_JUSTIFIED;");
            p.Alignment = Element.ALIGN_LEFT;
            p.Alignment = Element.ALIGN_CENTER;
            p.Alignment = Element.ALIGN_RIGHT;
            p.Alignment = Element.ALIGN_JUSTIFIED;
            pdfDocument.Add(p);

            Paragraph
                spacy = new Paragraph();

            spacy.Leading = 72;
            pdfDocument.Add(spacy);

            Paragraph
                spacy2 = new Paragraph(72);

            Paragraph
                spacy3 = new Paragraph(72, "The leading is an inch.");

            pdfDocument.Add(spacy2);
            pdfDocument.Add(spacy3);

            Paragraph
                doubleSpaced = new Paragraph("doubleSpaced.MultipliedLeading = 2");

            doubleSpaced.MultipliedLeading = 2;
            pdfDocument.Add(doubleSpaced);

            Chunk
                boo = new Chunk("Boo!");

            boo.Font.SetStyle(Font.BOLD);
            boo.Font.Size = 72;
            boo.Font.SetStyle("bold");

            Font
                small = new Font(Font.FontFamily.TIMES_ROMAN, 5);

            Chunk
                smallText = new Chunk("This is small.", small);

            Font
                redItalic = new Font(Font.FontFamily.HELVETICA, Font.DEFAULTSIZE, Font.ITALIC, BaseColor.RED);

            Chunk
                hey = new Chunk("Hey.", FontFactory.GetFont("Courier", 12, Font.ITALIC));

            table = new PdfPTable(3);
            table.AddCell(new PdfPCell(new Phrase("Cell# 1")));
            table.AddCell(new PdfPCell(new Phrase("Cell# 2")));
            table.AddCell(new PdfPCell(new Phrase("Cell# 3")));
            pdfDocument.Add(table);

            #if TEST_ATTACHMENTS
            PdfFileSpecification
                pdfFileSpecification = PdfFileSpecification.FileEmbedded(writer, ImageName, Path.GetFileName(ImageName), null);

            writer.AddFileAttachment("Description", pdfFileSpecification);

            FileStream
                fs = File.OpenRead(ImageName);

            byte[]
            img = new byte[fs.Length];

            fs.Read(img, 0, img.Length);
            pdfFileSpecification = PdfFileSpecification.FileEmbedded(writer, ImageName, Path.GetFileName(ImageName), img);
            writer.AddFileAttachment("DescriptionDescription", pdfFileSpecification);
            #endif

            PdfContentByte
                pdfContentByte;

            float
                x,
                y;

            #if TEST_DIRECT_CONTENT
            pdfDocument.NewPage();

            pdfContentByte = writer.DirectContent;

            pdfContentByte.MoveTo(x = 400f, 0f);
            pdfContentByte.LineTo(x, page.Height);
            pdfContentByte.MoveTo(x = 300f, 0f);
            pdfContentByte.LineTo(x, page.Height);
            pdfContentByte.MoveTo(0f, y = 10f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 50f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 90f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 130f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 170f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 600f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 700f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.Stroke();

            pdfContentByte.BeginText();
            pdfContentByte.SetFontAndSize(BaseFont.CreateFont(/*BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED*/), iTextSharp.text.Font.DEFAULTSIZE);
            pdfContentByte.ShowText("pdfContentByte.ShowText()");
            pdfContentByte.SetTextMatrix(x, 170f);
            pdfContentByte.ShowText("pdfContentByte.ShowText()");
            pdfContentByte.ShowText(string.Format("Width: {0}, Height: {1}", page.Width, page.Height));
            pdfContentByte.ShowTextAlignedKerned(PdfContentByte.ALIGN_RIGHT, "pdfContentByte.ShowTextAlignedKerned(RIGHT)", x, 130f, 0f);
            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "pdfContentByte.ShowTextAligned(RIGHT)", x, 90f, 0f);
            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "pdfContentByte.ShowTextAligned(CENTER)", x, 50f, 0f);
            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "pdfContentByte.ShowTextAligned(LEFT)", x, 10f, 0f);

            pdfContentByte.SetTextMatrix(0, 1, -1, 0, 300, 600);
            pdfContentByte.ShowText("Position 300,600, rotated 90 degrees.");

            for (int i = 0; i < 360; i += 30)
            {
                pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Rotated Text", 400f, 700f, i);
            }

            pdfContentByte.EndText();
            #endif

            #if TEST_NESTED_TABLES
            pdfDocument.NewPage();

            table = new PdfPTable(3);
            for (int i = 0; i < 3; ++i)
            {
                nested           = new PdfPTable(1);
                cell             = new PdfPCell(new Phrase(i.ToString()));
                cell.BorderColor = BaseColor.RED;
                nested.AddCell(cell);
                nesthousing             = new PdfPCell(nested);
                nesthousing.BorderColor = BaseColor.BLUE;
                nesthousing.Padding     = 10;
                table.AddCell(nesthousing);
            }
            pdfDocument.Add(table);
            #endif

            #if TEST_LEADING
            pdfDocument.NewPage();

            table = new PdfPTable(10);
            cell  = new PdfPCell(new Paragraph("Quick brown fox jumps over the lazy dog.\nQuick brown fox jumps over the lazy dog."));
            table.AddCell("default leading / spacing");
            table.AddCell(cell);
            table.AddCell("absolute leading: 20");
            cell.SetLeading(20f, 0f);
            table.AddCell(cell);
            table.AddCell("absolute leading: 3; relative leading: 1.2");
            cell.SetLeading(3f, 1.2f);
            table.AddCell(cell);
            table.AddCell("absolute leading: 0; relative leading: 1.2");
            cell.SetLeading(0f, 1.2f);
            table.AddCell(cell);
            table.AddCell("no leading at all");
            cell.SetLeading(0f, 0f);
            table.AddCell(cell);
            pdfDocument.Add(table);
            #endif

            #if TEST_DIRECT_TEXT_IN_CELL
            pdfDocument.NewPage();

            table = new PdfPTable(MaxCell = 3);
            for (int i = 0; i < MaxCell; ++i)
            {
                cell = new PdfPCell(new Paragraph(i.ToString()));
                table.AddCell(cell);
            }
            pdfDocument.Add(table);

            pdfContentByte = writer.DirectContent;
            pdfContentByte.BeginText();
            pdfContentByte.SetFontAndSize(BaseFont.CreateFont(), iTextSharp.text.Font.DEFAULTSIZE);
            pdfContentByte.SetTextMatrix(230, 792);
            pdfContentByte.ShowText(string.Format("Width: {0}, Height: {1} - blah-blah-blah", page.Width, page.Height));
            pdfContentByte.EndText();
            #endif

            #if TEST_TABLE_WITH_ABSOLUTE_WIDTH_OF_CELL
            pdfDocument.NewPage();

            widths = new float[] { (PageSize.A4.Width * 50) / 210f, (PageSize.A4.Width * 25) / 210f, (PageSize.A4.Width * 25) / 210f };
            table  = new PdfPTable(MaxCell = 3);
            table.SetTotalWidth(widths);
            table.LockedWidth = true;
            for (int i = 0; i < MaxCell; ++i)
            {
                cell = new PdfPCell(new Paragraph(i.ToString()));
                table.AddCell(cell);
            }
            pdfDocument.Add(table);
            #endif

            ColumnText
                columnText;

            #if TEST_COLUMN_TEXT
            pdfDocument.NewPage();

            pdfContentByte = writer.DirectContent;

            pdfContentByte.MoveTo(x = 80f, 0f);
            pdfContentByte.LineTo(x, page.Height);
            pdfContentByte.MoveTo(0f, y = 80f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.Stroke();

            columnText = new ColumnText(pdfContentByte);
            phrase     = new Phrase("blah-blah-blah1\nblah-blah-blah2 blah-blah-blah3 blah-blah-blah4 blah-blah-blah5");
            columnText.AddText(phrase);
            //columnText.AddElement(phrase);
            columnText.SetSimpleColumn(0, 0, x, y);
            columnText.Go();
            #endif

            pdfDocument.Close();
        }
示例#26
0
        // metodo principal para el procesamiento de pdfs (firma digital adjuntos metadatos)
        public string SignPdf(
            SignRenderingMode signRenderingMode,
            Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto jsonToProcess,
            string path)
        {
            try
            {
                //var json = File.ReadAllText(path);

                //var jsonToProcess = JsonConvert
                //.DeserializeObject<Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto>(json.Replace("<EOF>", ""));

                _target = jsonToProcess.outPath;
                _fs     = GetPdfStreamFormUrlOrBase64(jsonToProcess.dataUriBase64PdfToSign);

                // conversor de certificados
                var objCP   = new BcX509.X509CertificateParser();
                var crlList = new List <ICrlClient>();

                // buscar el certificado por numero serial
                var certificate = SearchCertificate(jsonToProcess.certificateSerialNumber);
                if (certificate == null)
                {
                    return("No se encontraron certificados para el serial: " + jsonToProcess.certificateSerialNumber);
                }

                // definicion del certificado operable
                var objChain = new BcX509.X509Certificate[] { objCP.ReadCertificate(certificate.RawData) };
                crlList.Add(new CrlClientOnline(objChain));

                //TODO: habilitar la estampa cronologica (Error) (verificar tsa Timestamping Authority)
                // agregamos la estampa cronologica
                #region estampa cronologica
                ITSAClient  tsaClient  = null;
                IOcspClient ocspClient = null;
                if (jsonToProcess.addTimeStamp)
                {
                    ocspClient = new OcspClientBouncyCastle();
                    //CertificateUtil.getTSAURL(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate));
                    tsaClient = new TSAClientBouncyCastle(jsonToProcess.urlTSA);
                }
                #endregion estampa cronologica

                // cargue del pdf al lector de itextsharp
                var _pdfReader = new PdfReader(_fs);

                // cargue an memoria del pdf
                using (var _wfs = new MemoryStream())
                {
                    // creacion de la firma a partir del lector itextsharp y el pdf en memoria
                    using (var objStamper = PdfStamper.CreateSignature(_pdfReader, _wfs, '\0', null, true))
                    {
                        // Procesar adjuntos
                        var attachmentIndex = 1;
                        (jsonToProcess.dataUriBase64ListOfPdfToAttach as List <FileToAttachDto>).ForEach(
                            (item) =>
                        {
                            //TODO: verificar si no se va a necesitar
                            if (!item.pathOrDataUriBase64.StartsWith("data:"))
                            {
                                var pfs = PdfFileSpecification.FileEmbedded(objStamper.Writer, item.fileDescription, attachmentIndex + "_" + item.fileDescription + ".pdf", null, true);
                                objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs);
                            }
                            else
                            {
                                try
                                {
                                    var x   = StreamToByteArray(GetPdfStreamFormUrlOrBase64(item.pathOrDataUriBase64));
                                    var pfs = PdfFileSpecification.FileEmbedded(
                                        objStamper.Writer,
                                        item.fileDescription + ".pdf",
                                        item.fileDescription + ".pdf",
                                        x,
                                        true,
                                        item.mimeType,
                                        null
                                        );
                                    objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs);
                                    //.AddFileAttachment("adjunto número: " + attachmentIndex, x, "adjunto_" + attachmentIndex + ".pdf", "adjunto " + attachmentIndex);
                                }
                                catch (Exception exce)
                                {
                                    Console.WriteLine(exce.StackTrace);
                                }
                            }
                            attachmentIndex++;
                        });

                        // definicion de la apariencia de la firma
                        var signatureAppearance = objStamper.SignatureAppearance;
                        // definicion del enum itextsharp a partir del enum parametro local
                        var mode = Enum.Parse(typeof(RenderingMode), signRenderingMode.ToString());
                        signatureAppearance.SignatureRenderingMode = (RenderingMode)mode;
                        signatureAppearance.Reason   = jsonToProcess.reasonToSign;
                        signatureAppearance.Location = jsonToProcess.locationDescription;

                        // agregar marca visual de firma digital
                        #region agregar marca visual firma digital
                        if (jsonToProcess.addVisibleSignMark)
                        {
                            // definicion de imagen desde ruta o base64
                            signatureAppearance.SignatureGraphic = GetImageFormUrlOrBase64(jsonToProcess.dataUriBase64SignImage);
                            // definicion de la firma digital visible
                            signatureAppearance.SetVisibleSignature(
                                new Rectangle(jsonToProcess.visibleSignMarkWidth, jsonToProcess.visibleSignMarkHeight, jsonToProcess.xVisibleSignMarkPosition, jsonToProcess.yVisibleSignMarkPosition),
                                _pdfReader.NumberOfPages,
                                jsonToProcess.visibleSignText);
                        }
                        #endregion agregar marca visual firma digital

                        // Agregar propiedades extendidas
                        objStamper.MoreInfo = (jsonToProcess.metadata as List <MetadataDto>).ToDictionary(x => x.key, x => x.value);

                        //TODO: verificar si no es necesario la utilizacion de XMP manual (actualmente funciona)
                        #region xmp implementacion manual

                        /* objStamper.Writer.CreateXmpMetadata();
                         * var xmp = objStamper.Writer.XmpMetadata;
                         *
                         *
                         * //XMP metadatos
                         * IXmpMeta xmp;
                         * using (var stream = File.OpenRead(@"C:\Users\danie\OneDrive\Escritorio\xmpMetadata.xml"))
                         *  xmp = XmpMetaFactory.Parse(stream);
                         *
                         * foreach (var property in xmp.Properties)
                         * {
                         *  Console.WriteLine($"Path={property.Path} Namespace={property.Namespace} Value={property.Value}");
                         * }
                         *
                         * var serializeOptions = new SerializeOptions();
                         * serializeOptions.UsePlainXmp = true;
                         * var newMetadata = XmpMetaFactory.SerializeToBuffer(xmp, serializeOptions);
                         * objStamper.XmpMetadata = newMetadata;*/
                        #endregion xmp implementacion manual

                        // Firmar digitalmente
                        var externalSignature = new X509Certificate2Signature(certificate, jsonToProcess.certificateHashAlgorithm);
                        MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
                    }
                    var pdfFileTocreate = jsonToProcess.outPath.Replace("json", "pdf");
                    System.IO.File.WriteAllBytes(pdfFileTocreate, _wfs.ToArray());
                    Process.Start(pdfFileTocreate);
                    return(Convert.ToBase64String(_wfs.ToArray()));
                }
            }
            catch (Exception exce)
            {
                WriteToFile(exce.StackTrace);
                WriteToFile(exce.Message);
                return(exce.Message);
            }
        }
示例#27
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                writer.AddDeveloperExtension(
                    PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3
                    );
                // step 3
                document.Open();
                // step 4
                writer.AddJavaScript(File.ReadAllText(JS));

                // we prepare a RichMediaAnnotation
                RichMediaAnnotation richMedia = new RichMediaAnnotation(
                    writer, new Rectangle(36, 560, 561, 760)
                    );
                // we embed the swf file
                PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                    writer, RESOURCE, "FestivalCalendar2.swf", null
                    );
                // we declare the swf file as an asset
                PdfIndirectReference asset = richMedia.AddAsset(
                    "FestivalCalendar2.swf", fs
                    );
                // we create a configuration
                RichMediaConfiguration configuration = new RichMediaConfiguration(
                    PdfName.FLASH
                    );
                RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
                instance.Asset = asset;
                configuration.AddInstance(instance);
                // we add the configuration to the annotation
                PdfIndirectReference configurationRef = richMedia.AddConfiguration(
                    configuration
                    );
                // activation of the rich media
                RichMediaActivation activation = new RichMediaActivation();
                activation.Configuration = configurationRef;
                richMedia.Activation     = activation;
                // we add the annotation
                PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation();
                richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT;
                writer.AddAnnotation(richMediaAnnotation);

                String[] days = new String[] {
                    "2011-10-12", "2011-10-13", "2011-10-14", "2011-10-15",
                    "2011-10-16", "2011-10-17", "2011-10-18", "2011-10-19"
                };
                for (int i = 0; i < days.Length; i++)
                {
                    Rectangle       rect   = new Rectangle(36 + (65 * i), 765, 100 + (65 * i), 780);
                    PushbuttonField button = new PushbuttonField(writer, rect, "button" + i);
                    button.BackgroundColor          = new GrayColor(0.75f);
                    button.BorderStyle              = PdfBorderDictionary.STYLE_BEVELED;
                    button.TextColor                = GrayColor.GRAYBLACK;
                    button.FontSize                 = 12;
                    button.Text                     = days[i];
                    button.Layout                   = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
                    button.ScaleIcon                = PushbuttonField.SCALE_ICON_ALWAYS;
                    button.ProportionalIcon         = true;
                    button.IconHorizontalAdjustment = 0;
                    PdfFormField     field   = button.Field;
                    RichMediaCommand command = new RichMediaCommand(
                        new PdfString("getDateInfo")
                        );
                    command.Arguments = new PdfString(days[i]);
                    RichMediaExecuteAction action = new RichMediaExecuteAction(
                        richMediaAnnotation.IndirectReference, command
                        );
                    field.Action = action;
                    writer.AddAnnotation(field);
                }
                TextField text = new TextField(
                    writer, new Rectangle(36, 785, 559, 806), "date"
                    );
                text.Options = TextField.READ_ONLY;
                writer.AddAnnotation(text.GetTextField());
            }
        }
示例#28
0
        public override void Generate()
        {
            var font        = FontFactory.GetFont("Times New Roman", 10);
            var sectionFont = FontFactory.GetFont("Times New Roman", 16, Font.BOLD);

            base.Generate();

            var table = new AttachmentTable();

            foreach (var attachment in Settings.Attachments)
            {
                string attachmentName = null;
                if (attachment.IsSection)
                {
                    if (table.Rows.Any() && table.Complete)
                    {
                        FormatTableCells(table, 20);
                        Document.Add(table);
                        Document.NewPage();
                        table = new AttachmentTable();
                    }
                    var sectionHeader = MakeCell(attachment.SectionHeader, sectionFont);
                    sectionHeader.Colspan = 2;
                    table.AddCell(sectionHeader);
                }
                if (attachment.HasAttachment)
                {
                    attachmentName = Path.GetFileName(attachment.AttachmentPath);
                    var fileSpec = PdfFileSpecification.FileEmbedded(Writer, attachment.AttachmentPath,
                                                                     attachmentName, null);
                    fileSpec.AddDescription(attachmentName, false);
                    Writer.AddFileAttachment(fileSpec);
                }
                if (attachment.HasThumbnail)
                {
                    var image = Image.GetInstance(attachment.ThumbnailPath, true);
                    var cell  = new PdfPCell(image)
                    {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment   = Element.ALIGN_MIDDLE
                    };
                    if (attachment.HasAttachment)
                    {
                        cell.CellEvent = new ThumbnailLayoutHandler(attachmentName, Writer);
                    }
                    if (!attachment.HasDescriptiveText)
                    {
                        cell.Colspan = 2;
                    }
                    table.AddCell(cell);
                }

                if (!attachment.HasDescriptiveText)
                {
                    continue;
                }

                var description = MakeCell(attachment.DescriptiveText, font);
                description.VerticalAlignment = Element.ALIGN_MIDDLE;
                if (!attachment.HasThumbnail)
                {
                    description.Colspan = 2;
                }

                table.AddCell(description);
            }

            FormatTableCells(table, 20);
            Document.Add(table);
        }
示例#29
0
        public void GerarPdf()
        {
            var       doc1     = new Document(PageSize.A4, 40.0f, 20.0f, 30.0f, 30.0f);//Margens - Margem direita precisa ser 20 para poder caber valores acima de R$ 100.000,00 nas contratações
            string    filename = null;
            PdfWriter writer   = null;

            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog
                {
                    InitialDirectory = PdfFolder,
                    Filter           = "Arquivo PDF|*.pdf",
                    Title            = "Salvar como",
                    FileName         = Cota.Cliente + ".pdf"
                };
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileDialog1.FileName != "")
                    {
                        filename = saveFileDialog1.FileName;
                        writer   = PdfWriter.GetInstance(doc1, new FileStream(saveFileDialog1.FileName, FileMode.Create));
                        Relatório.SalvaUtilizacao(Cota);
                    }
                }
                else
                {
                    return;
                }

                Home.preferencias.PastaPDF = saveFileDialog1.FileName.Substring(0, saveFileDialog1.FileName.LastIndexOf('\\') + 1);
                WebFile.Prefs = Home.preferencias;
            }
            catch (IOException)
            {
                Relatório.AdicionarAoRelatorio("Há um arquivo de mesmo nome aberto");
                MessageBox.Show("Não foi possível criar o arquivo PDF,\r\nverifique se há um arquivo de mesmo nome aberto.\r\nFeche-o e tente novamente.",
                                "Carta de Cotação",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            doc1.Open();
            iTextSharp.text.Font normal = FontFactory.GetFont("Helvetica", 11);

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(ConverteImageParaByteArray(Properties.Resources.Bragaseg));
            jpg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
            jpg.ScaleToFit(250f, 250f);
            //jpg.SetAbsolutePosition(500f, 750f);

            //Como colocar marca d'água:
            //jpg.SetAbsolutePosition(doc1.PageSize.Width - 500f, 750f);
            //jpg.Rotation = (float)Math.PI / 2;
            //jpg.RotationDegrees = 90f;

            doc1.Add(jpg);

            doc1.Add(new Paragraph("\r\n", normal));
            Paragraph pfcity = new Paragraph("Passo Fundo, " + DataPorExtenso(Cota.Data) + ".", normal);

            //pfcity.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
            //pfcity.IndentationLeft = 230;
            doc1.Add(pfcity);
            doc1.Add(new Paragraph("\r\n", normal));
            if (Home.excedeuLinhas)
            {
                doc1.Add(new Paragraph("A " + Cota.Cliente, normal));
            }
            else
            {
                doc1.Add(new Paragraph("A", normal));
                doc1.Add(new Paragraph(Cota.Cliente, normal));
            }
            doc1.Add(new Paragraph("\r\n", normal));
            doc1.Add(new Paragraph("Estamos encaminhando a cotação do veículo abaixo:", normal));
            doc1.Add(new Paragraph(Cota.Marca + " - " + Cota.Modelo, normal));
            doc1.Add(new Paragraph("Ano de fabricação: " + Cota.AnoFabricacao + "      Ano modelo: " + Cota.AnoModelo, normal));
            doc1.Add(new Paragraph("\r\n", normal));

            //Início das contratações:
            decimal        valorfipecont = Cota.ValorFipe * Cota.PorContratada / 100m;
            List <string>  contrat       = new List <string>();
            List <decimal> listvalores   = new List <decimal>();

            if (Cota.Rcf != true)
            {
                if (Cota.Vd != true)
                {
                    contrat.Add("Casco - " + Cota.PorContratada + "% da Fipe:");
                }
                else
                {
                    contrat.Add("Valor Determinado:");
                }
                listvalores.Add(valorfipecont);
            }
            else
            {
                contrat.Add("Sem casco contratado");
                listvalores.Add(-1.0m);
            }

            contrat.Add("Danos Materiais:");
            listvalores.Add(Cota.DanosMateriais);

            contrat.Add("Danos Corporais:");
            listvalores.Add(Cota.DanosCorporais);

            contrat.Add("Danos Morais:");
            listvalores.Add(Cota.DanosMorais);

            if (Cota.Seguradora != "Itaú")
            {
                contrat.Add("APP Morte:");
            }
            else
            {
                contrat.Add("APP:");
            }
            listvalores.Add(Cota.APPMorte);

            //AQUI: ESSE NÃO APARECE SE FOR ITAÚ
            contrat.Add("APP Invalidez:");
            listvalores.Add(Cota.APPInvalidez);

            if (Cota.Tipo == FipeType.Caminhão)
            {
                contrat.Add("Equipamento:");
                listvalores.Add(Cota.Equipamento);

                contrat.Add("Carroceria:");
                listvalores.Add(Cota.Carroceria);
            }

            bool semdecimais = listvalores.Exists(d => d > 999999);

            PdfPTable valores = new PdfPTable(5);

            valores.HorizontalAlignment = 0;
            float[] widthvalores = { 45f, 30f, 9f, 40f, 30f };
            valores.SetWidths(widthvalores);
            valores.DefaultCell.BorderColor = iTextSharp.text.BaseColor.WHITE;

            int c    = 0;  //contador de valores não zero na listvalores
            int n    = 0;  //num linhas
            int MODO = 0;  //<--MODO 0 divide os itens entre as colunas 1 e 2

            if (MODO == 0) //MODO 1 sempre preenche a coluna 1 inteira (3 itens ou 4 se caminhão) e depois preenche a coluna 2
            {
                foreach (decimal d in listvalores)
                {
                    if (d != 0.0m)
                    {
                        c++;
                        if (c % 2 != 0)
                        {
                            n++;
                        }
                    }
                }
            }
            else
            {
                n = 3;//num linhas se não caminhão
                if (Cota.Tipo == FipeType.Caminhão)
                {
                    n = 4;//num linhas se caminhão
                }
            }

            int[] col1 = new int[] { -1, -1, -1, -1 }; //posições na coluna 1, inicializa com -1 = não preenchido
            int[] col2 = new int[] { -1, -1, -1, -1 }; //posições na coluna 2, inicializa com -1 = não preenchido

            c = 0;                                     //reinicia contador
            int i = 0;                                 //contador de índice da listvalores

            foreach (decimal d in listvalores)
            {
                if (d != 0.0m)
                {
                    if (c < n)       //preenchimento da coluna 1
                    {
                        col1[c] = i; //guarda a posição de d na listvalores e contrat
                    }
                    else//preenchimento da coluna 2, após coluna 1 estar cheia
                    {
                        col2[c - n] = i;//guarda a posição de d na listvalores e contrat, c - n porque o índice deve iniciar no zero
                    }
                    c++;
                }
                i++;
            }

            for (i = 0; i < n; i++)
            {
                if (col1[i] != -1)                                         //testa se a posição na coluna 1 tem valor a ser preenchido
                {
                    valores.AddCell(new Phrase(contrat[col1[i]], normal)); //preenche com a string de contrat na posição guardada em col1

                    if (listvalores[col1[i]] != -1.0m)                     // testa se é o caso "sem casco"
                    {
                        if (!semdecimais)
                        {
                            valores.AddCell(new Phrase(listvalores[col1[i]].ToString("C2", CultureInfo.CurrentCulture)));//converte valor para string
                        }
                        else
                        {
                            valores.AddCell(new Phrase(listvalores[col1[i]].ToString("C0", CultureInfo.CurrentCulture)));//converte valor para string
                        }
                    }
                    else
                    {
                        valores.AddCell(new Phrase("", normal)); //se for "sem casco" preenche com vazio
                    }
                    valores.AddCell(new Phrase("", normal));     //preenche a coluna do meio com vazio
                }

                if (col2[i] != -1)                                         //testa se a posição na coluna 2 tem valor a ser preenchido
                {
                    valores.AddCell(new Phrase(contrat[col2[i]], normal)); //preenche com a string de contrat na posição guardada em col2
                    // como "sem casco" nunca vai cair na coluna 2, não precisa testar
                    if (!semdecimais)
                    {
                        valores.AddCell(new Phrase(listvalores[col2[i]].ToString("C2", CultureInfo.CurrentCulture)));//converte valor para string
                    }
                    else
                    {
                        valores.AddCell(new Phrase(listvalores[col2[i]].ToString("C0", CultureInfo.CurrentCulture)));//converte valor para string
                    }
                }
                else
                {
                    valores.AddCell(new Phrase("", normal)); //se a posição na coluna 2 não tem valor, preenche com vazio
                    valores.AddCell(new Phrase("", normal)); //idem acima para o valor
                }
            }
            doc1.Add(valores);
            //Fim das contratações

            int colunas = 3;
            if (Cota.Seguradora == "Bradesco" || Cota.Seguradora == "Generale" || (Cota.Seguradora == "Mapfre" && Cota.DebitoBB == true))
            {
                colunas = 2;
            }
            float[] width  = { 15f, 15f, 15f };
            float[] width2 = { 15f, 15f };

            //Tabela Franquia Básica
            if (Cota.FranquiaBasica + Cota.ValFranqBasicaAVista != 0)
            {
                PdfPTable table = new PdfPTable(colunas);

                if (colunas == 3)
                {
                    table.SetWidths(width);
                }
                else
                {
                    table.SetWidths(width2);
                }
                table.HorizontalAlignment = 0;
                PdfPCell cell = new PdfPCell(new Phrase(""));
                cell.Colspan             = 1;
                cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                table.AddCell(cell);
                doc1.Add(new Paragraph("\r\n", normal));
                if (Cota.Rcf != true)
                {
                    doc1.Add(new Paragraph("Franquia básica: " + Cota.FranquiaBasica.ToString("C2", CultureInfo.CurrentCulture), normal));
                    doc1.Add(new Paragraph("\r\n", normal));
                }

                if (Cota.Seguradora == "Mapfre" && Cota.DebitoBB)
                {
                    table.AddCell(new Phrase("Débito", normal));
                }
                else
                {
                    table.AddCell(new Phrase("Carnê", normal));
                }

                if (colunas != 2)
                {
                    if (Cota.Seguradora == "Sul América")
                    {
                        table.AddCell(new Phrase("Débito BB", normal));
                    }
                    else
                    {
                        table.AddCell(new Phrase("Débito", normal));
                    }
                }

                foreach (Parcelamento parc in Cota.TabelaParcelamento.FindAll(p => (p.TipoFranq == "Básica" && !(p.Seguradora == "Bradesco" && p.FormaPagto == "Débito")) && /* ADICIONADO */ !(p.Seguradora == "Generale" && p.FormaPagto == "Débito") && (p.TipoFranq == "Básica" && !(p.Seguradora == "Mapfre" && p.FormaPagto == "Carnê" && Cota.DebitoBB == true))))
                {
                    if (parc.FormaPagto == "Carnê" || (parc.FormaPagto == "Débito" && Cota.DebitoBB && parc.ValParcela != 0.0m))
                    {
                        table.AddCell(new Phrase(parc.Descricao.ToString(), normal));
                    }

                    if (parc.ValParcela == 0.0m)
                    {
                        table.AddCell(new Phrase("", normal));
                    }
                    else
                    {
                        table.AddCell(new Phrase(parc.ValParcela.ToString("C2", CultureInfo.CurrentCulture), normal));
                    }
                }
                doc1.Add(table);
            }
            //Tabela Franquia Reduzida
            if (Cota.FranquiaReduzida + Cota.ValFranqReduzidaAVista != 0.0m && Cota.Rcf != true)
            {
                PdfPTable table2 = new PdfPTable(colunas);
                if (colunas == 3)
                {
                    table2.SetWidths(width);
                }
                else
                {
                    table2.SetWidths(width2);
                }
                table2.HorizontalAlignment = 0;
                PdfPCell cell2 = new PdfPCell(new Phrase(""))
                {
                    Colspan             = 1,
                    HorizontalAlignment = 1
                };
                //0=Left, 1=Centre, 2=Right
                table2.AddCell(cell2);
                doc1.Add(new Paragraph("\r\n"));
                doc1.Add(new Paragraph("Franquia reduzida: " + Cota.FranquiaReduzida.ToString("C2", CultureInfo.CurrentCulture), normal));
                doc1.Add(new Paragraph("\r\n"));

                if (Cota.Seguradora == "Mapfre" && Cota.DebitoBB)
                {
                    table2.AddCell(new Phrase("Débito", normal));
                }
                else
                {
                    table2.AddCell(new Phrase("Carnê", normal));
                }

                if (colunas != 2)
                {
                    if (Cota.Seguradora == "Sul América")
                    {
                        table2.AddCell(new Phrase("Débito BB", normal));
                    }
                    else
                    {
                        table2.AddCell(new Phrase("Débito", normal));
                    }
                }

                foreach (Parcelamento parc in Cota.TabelaParcelamento.FindAll(p => (p.TipoFranq == "Reduzida" && !(p.Seguradora == "Bradesco" && p.FormaPagto == "Débito")) && /* ADICIONADO */ !(p.Seguradora == "Generale" && p.FormaPagto == "Débito") && (p.TipoFranq == "Reduzida" && !(p.Seguradora == "Mapfre" && p.FormaPagto == "Carnê" && Cota.DebitoBB == true))))
                {
                    if (parc.FormaPagto == "Carnê" || (parc.FormaPagto == "Débito" && Cota.DebitoBB && parc.ValParcela != 0.0m))
                    {
                        table2.AddCell(new Phrase(parc.Descricao.ToString(), normal));
                    }

                    if (parc.ValParcela == 0.0m)
                    {
                        table2.AddCell(new Phrase("", normal));
                    }
                    else
                    {
                        table2.AddCell(new Phrase(parc.ValParcela.ToString("C2", CultureInfo.CurrentCulture), normal));
                    }
                }
                doc1.Add(table2);
            }
            //Final Tabelas

            doc1.Add(new Paragraph("\r\n", normal));
            doc1.Add(new Paragraph(Cota.Observacoes, normal));

            if (Cota.MostrarValidade == true)
            {
                string textovalidade = "*Validade da cotação: " + Cota.Validade.ToShortDateString();
                doc1.Add(new Paragraph(textovalidade, normal));
            }

            doc1.Add(new Paragraph("\r\n", normal));
            iTextSharp.text.Font negrito = FontFactory.GetFont("Helvetica", 11, iTextSharp.text.Font.BOLD);

            //Testes das exibições

            /*if (Cota.NomeClaudio == true)
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * if (Cota.CelClaudio == true)
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * if (Cota.NomeFuncionario == true && Cota.Funcionario != "")
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * switch (exib)
             * {
             *  case "001":
             *      doc1.Add(new Paragraph(Cota.Funcionario, negrito));
             *      break;
             *  case "010":
             *      doc1.Add(new Paragraph("(54) 9981-4797", negrito));
             *      break;
             *  case "011":
             *      doc1.Add(new Paragraph("(54) 9981-4797 / " + Cota.Funcionario, negrito));
             *      break;
             *  case "100":
             *      doc1.Add(new Paragraph("Cláudio Zanchet", negrito));
             *      break;
             *  case "101":
             *      doc1.Add(new Paragraph("Cláudio Zanchet / " + Cota.Funcionario, negrito));
             *      break;
             *  case "110":
             *      doc1.Add(new Paragraph("Cláudio Zanchet" + " - (54) 9981-4797", negrito));
             *      break;
             *  case "111":
             *      doc1.Add(new Paragraph("Cláudio Zanchet" + " - (54) 9981-4797 / " + Cota.Funcionario, negrito));
             *      break;
             * }*/
            //Fim dos testes das exibições
            doc1.Add(new Paragraph(Cota.Funcionario, negrito));

            if (Cota.NomeFuncionario)
            {
                doc1.Add(new Paragraph("Bragaseg Corretora de Seguros", normal));
            }
            else
            {
                doc1.Add(new Paragraph("Bragaseg Corretora de Seguros", negrito));
            }
            doc1.Add(new Paragraph("Rua Uruguai, 1763 - Bairro Centro", normal));
            doc1.Add(new Paragraph("Passo Fundo - RS    CEP: 99010-112", normal));
            doc1.Add(new Paragraph("Telefone: (54) 3045-5300", normal));

            doc1.AddCreator("Carta de Cotação");
            File.Create(WebFile.AppData + "TempFill.bin").Close();
            WebFile.Serialize(Cota.Preenchimento, WebFile.AppData + "TempFill.bin");
            PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(writer, WebFile.AppData + "TempFill.bin", "TempFill.bin", null);
            writer.AddFileAttachment(pfs);
            doc1.Close();
            File.Delete(WebFile.AppData + "TempFill.bin");

            if (MessageBox.Show("Arquivo PDF gerado com sucesso!\r\nVocê deseja visualizá-lo agora?", "Carta de Cotação", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                Process.Start(filename);
            }
        }
示例#30
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();


                // step 4
                PdfCollection       collection = new PdfCollection(PdfCollection.HIDDEN);
                PdfCollectionSchema schema     = _collectionSchema();
                collection.Schema = schema;
                PdfCollectionSort sort = new PdfCollectionSort(KEYS);
                collection.Sort   = sort;
                writer.Collection = collection;

                PdfCollectionItem    collectionitem = new PdfCollectionItem(schema);
                PdfFileSpecification fs             = PdfFileSpecification.FileEmbedded(
                    writer, IMG_KUBRICK, "kubrick.jpg", null
                    );
                fs.AddDescription("Stanley Kubrick", false);
                collectionitem.AddItem(TYPE_FIELD, "JPEG");
                fs.AddCollectionItem(collectionitem);
                writer.AddFileAttachment(fs);

                Image img = Image.GetInstance(IMG_BOX);
                document.Add(img);
                List           list = new List(List.UNORDERED, 20);
                PdfDestination dest = new PdfDestination(PdfDestination.FIT);
                dest.AddFirst(new PdfNumber(1));
                PdfTargetDictionary intermediate;
                PdfTargetDictionary target;
                Chunk     chunk;
                ListItem  item;
                PdfAction action = null;

                IEnumerable <Movie> box = PojoFactory.GetMovies(1)
                                          .Concat(PojoFactory.GetMovies(4))
                ;
                StringBuilder sb = new StringBuilder();
                foreach (Movie movie in box)
                {
                    if (movie.Year > 1960)
                    {
                        sb.AppendLine(String.Format(
                                          "{0};{1};{2}", movie.MovieTitle, movie.Year, movie.Duration
                                          ));
                        item = new ListItem(movie.MovieTitle);
                        if (!"0278736".Equals(movie.Imdb))
                        {
                            target = new PdfTargetDictionary(true);
                            target.EmbeddedFileName          = movie.Title;
                            intermediate                     = new PdfTargetDictionary(true);
                            intermediate.FileAttachmentPage  = 1;
                            intermediate.FileAttachmentIndex = 1;
                            intermediate.AdditionalPath      = target;
                            action = PdfAction.GotoEmbedded(null, intermediate, dest, true);
                            chunk  = new Chunk(" (see info)");
                            chunk.SetAction(action);
                            item.Add(chunk);
                        }
                        list.Add(item);
                    }
                }
                document.Add(list);

                fs = PdfFileSpecification.FileEmbedded(
                    writer, null, "kubrick.txt",
                    Encoding.UTF8.GetBytes(sb.ToString())
                    );
                fs.AddDescription("Kubrick box: the movies", false);
                collectionitem.AddItem(TYPE_FIELD, "TXT");
                fs.AddCollectionItem(collectionitem);
                writer.AddFileAttachment(fs);

                PdfPTable table = new PdfPTable(1);
                table.SpacingAfter = 10;
                PdfPCell cell = new PdfPCell(new Phrase("All movies by Kubrick"));
                cell.Border = PdfPCell.NO_BORDER;
                fs          = PdfFileSpecification.FileEmbedded(
                    writer, null, KubrickMovies.FILENAME,
                    Utility.PdfBytes(new KubrickMovies())
                    //new KubrickMovies().createPdf()
                    );
                collectionitem.AddItem(TYPE_FIELD, "PDF");
                fs.AddCollectionItem(collectionitem);
                target = new PdfTargetDictionary(true);
                target.FileAttachmentPagename = "movies";
                target.FileAttachmentName     = "The movies of Stanley Kubrick";
                cell.CellEvent = new PdfActionEvent(
                    writer, PdfAction.GotoEmbedded(null, target, dest, true)
                    );
                cell.CellEvent = new FileAttachmentEvent(
                    writer, fs, "The movies of Stanley Kubrick"
                    );
                cell.CellEvent = new LocalDestinationEvent(writer, "movies");
                table.AddCell(cell);
                writer.AddFileAttachment(fs);

                cell        = new PdfPCell(new Phrase("Kubrick DVDs"));
                cell.Border = PdfPCell.NO_BORDER;
                fs          = PdfFileSpecification.FileEmbedded(
                    writer, null,
                    KubrickDvds.RESULT, new KubrickDvds().CreatePdf()
                    );
                collectionitem.AddItem(TYPE_FIELD, "PDF");
                fs.AddCollectionItem(collectionitem);
                cell.CellEvent = new FileAttachmentEvent(writer, fs, "Kubrick DVDs");
                table.AddCell(cell);
                writer.AddFileAttachment(fs);

                cell        = new PdfPCell(new Phrase("Kubrick documentary"));
                cell.Border = PdfPCell.NO_BORDER;
                fs          = PdfFileSpecification.FileEmbedded(
                    writer, null,
                    KubrickDocumentary.RESULT, new KubrickDocumentary().CreatePdf()
                    );
                collectionitem.AddItem(TYPE_FIELD, "PDF");
                fs.AddCollectionItem(collectionitem);
                cell.CellEvent = new FileAttachmentEvent(
                    writer, fs, "Kubrick Documentary"
                    );
                table.AddCell(cell);
                writer.AddFileAttachment(fs);

                document.NewPage();
                document.Add(table);
            }
        }