Exemplo n.º 1
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
                Rectangle rect = new Rectangle(100, 400, 500, 800);
                rect.Border      = Rectangle.BOX;
                rect.BorderWidth = 0.5f;
                rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);
                document.Add(rect);

                PdfIndirectObject streamObject = null;
                using (FileStream fs =
                           new FileStream(RESOURCE, FileMode.Open, FileAccess.Read))
                {
                    PdfStream stream3D = new PdfStream(fs, writer);

                    stream3D.Put(PdfName.TYPE, new PdfName("3D"));
                    stream3D.Put(PdfName.SUBTYPE, new PdfName("U3D"));
                    stream3D.FlateCompress();
                    streamObject = writer.AddToBody(stream3D);
                    stream3D.WriteLength();
                }

                PdfDictionary dict3D = new PdfDictionary();
                dict3D.Put(PdfName.TYPE, new PdfName("3DView"));
                dict3D.Put(new PdfName("XN"), new PdfString("Default"));
                dict3D.Put(new PdfName("IN"), new PdfString("Unnamed"));
                dict3D.Put(new PdfName("MS"), PdfName.M);
                dict3D.Put(
                    new PdfName("C2W"),
                    new PdfArray(
                        new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 }
                        )
                    );
                dict3D.Put(PdfName.CO, new PdfNumber(235));

                PdfIndirectObject dictObject = writer.AddToBody(dict3D);

                PdfAnnotation annot = new PdfAnnotation(writer, rect);
                annot.Put(PdfName.CONTENTS, new PdfString("3D Model"));
                annot.Put(PdfName.SUBTYPE, new PdfName("3D"));
                annot.Put(PdfName.TYPE, PdfName.ANNOT);
                annot.Put(new PdfName("3DD"), streamObject.IndirectReference);
                annot.Put(new PdfName("3DV"), dictObject.IndirectReference);
                PdfAppearance ap = writer.DirectContent.CreateAppearance(
                    rect.Width, rect.Height
                    );
                annot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
                annot.SetPage();

                writer.AddAnnotation(annot);
            }
        }
Exemplo n.º 2
0
 /**
  * Creates a RichMediaAnnotation using rich media content that has already
  * been added to the writer. Note that assets, configurations, views added
  * to a RichMediaAnnotation created like this will be ignored.
  * @param   writer  the PdfWriter to which the annotation will be added.
  * @param   rect    the rectangle where the annotation will be added.
  * @param   richMediaContentReference   reused rich media content.
  */
 public RichMediaAnnotation(PdfWriter writer, Rectangle rect, PdfIndirectReference richMediaContentReference)
 {
     this.richMediaContentReference = richMediaContentReference;
     richMediaContent = null;
     this.writer      = writer;
     annot            = new PdfAnnotation(writer, rect);
     annot.Put(PdfName.SUBTYPE, PdfName.RICHMEDIA);
 }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
 /**
  * Creates a RichMediaAnnotation.
  * @param   writer  the PdfWriter to which the annotation will be added.
  * @param   rect    the rectangle where the annotation will be added.
  */
 public RichMediaAnnotation(PdfWriter writer, Rectangle rect)
 {
     this.writer = writer;
     annot       = new PdfAnnotation(writer, rect);
     annot.Put(PdfName.SUBTYPE, PdfName.RICHMEDIA);
     richMediaContent = new PdfDictionary(PdfName.RICHMEDIACONTENT);
     assetsmap        = new Dictionary <string, PdfIndirectReference>();
     configurations   = new PdfArray();
     views            = new PdfArray();
 }
Exemplo n.º 5
0
            /**
             * @see com.itextpdf.text.pdf.PdfPageEventHelper#onGenericTag(
             *      com.itextpdf.text.pdf.PdfWriter,
             *      com.itextpdf.text.Document,
             *      com.itextpdf.text.Rectangle, java.lang.String)
             */
            public override void OnGenericTag(PdfWriter writer,
                                              Document document, Rectangle rect, string text)
            {
                PdfAnnotation annotation = new PdfAnnotation(writer,
                                                             new Rectangle(
                                                                 rect.Right + 10, rect.Bottom,
                                                                 rect.Right + 30, rect.Top
                                                                 )
                                                             );

                annotation.Title = "Text annotation";
                annotation.Put(PdfName.SUBTYPE, PdfName.TEXT);
                annotation.Put(PdfName.OPEN, PdfBoolean.PDFFALSE);
                annotation.Put(PdfName.CONTENTS,
                               new PdfString(string.Format("Icon: {0}", text))
                               );
                annotation.Put(PdfName.NAME, new PdfName(text));
                writer.AddAnnotation(annotation);
            }
Exemplo n.º 6
0
        public void StampAnnotation(PdfStamper stamper, int page, double scale)
        {
            PdfAnnotation annotation = null;

            if (Geometry == null)
            {
                throw new Exception(Properties.Resources.NoGeometry);
            }
            else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.Line))
            {
                var line = Geometry as Autodesk.DesignScript.Geometry.Line;
                annotation = line.ToPDFLine(Contents, stamper.Writer);
            }
            else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.Polygon))
            {
                var polygon = Geometry as Autodesk.DesignScript.Geometry.Polygon;
                annotation = polygon.ToPDFPolygon(Contents, stamper.Writer);
            }
            else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.PolyCurve))
            {
                var polycurve = Geometry as Autodesk.DesignScript.Geometry.PolyCurve;
                annotation = polycurve.ToPDFPolygon(Contents, stamper.Writer);
            }
            else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.Circle))
            {
                var circle = Geometry as Autodesk.DesignScript.Geometry.Circle;
                annotation = circle.ToPDFCircle(Contents, stamper.Writer);
            }
            else
            {
                throw new Exception(Properties.Resources.NotSupported);
            }

            annotation.Put(PdfName.T, new PdfString(Author));
            annotation.Put(PdfName.M, new PdfDate(DateTime.Now));
            annotation.Put(PdfName.CREATIONDATE, new PdfDate(DateTime.Now));
            annotation.Put(PdfName.CONTENTS, new PdfString(Contents));

            float[] floatdata = { Convert.ToSingle(Color.Red), Convert.ToSingle(Color.Green), Convert.ToSingle(Color.Blue) };
            annotation.Put(PdfName.C, new PdfArray(floatdata));

            stamper.AddAnnotation(annotation, page);
        }
Exemplo n.º 7
0
        // ---------------------------------------------------------------------------

        /**
         * Adds a popup.
         * @param stamper the PdfStamper to which the annotation needs to be added
         * @param rect the position of the annotation
         * @param title the annotation title
         * @param contents the annotation content
         * @param imdb the IMDB number of the movie used as name of the annotation
         */
        public void AddPopup(PdfStamper stamper, Rectangle rect,
                             String title, String contents, String imdb)
        {
            // Create the text annotation
            PdfAnnotation text = PdfAnnotation.CreateText(
                stamper.Writer,
                rect, title, contents, false, "Comment"
                );

            text.Name  = string.Format("IMDB{0}", imdb);
            text.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW;
            // Create the popup annotation
            PdfAnnotation popup = PdfAnnotation.CreatePopup(
                stamper.Writer,
                new Rectangle(
                    rect.Left + 10, rect.Bottom + 10,
                    rect.Left + 200, rect.Bottom + 100
                    ),
                null, false
                );

            // Add the text annotation to the popup
            popup.Put(PdfName.PARENT, text.IndirectReference);
            // Declare the popup annotation as popup for the text
            text.Put(PdfName.POPUP, popup.IndirectReference);
            // Add both annotations
            stamper.AddAnnotation(text, 1);
            stamper.AddAnnotation(popup, 1);
            // Create a button field
            PushbuttonField field = new PushbuttonField(
                stamper.Writer, rect,
                string.Format("b{0}", imdb)
                );
            PdfAnnotation widget = field.Field;
            // Show the popup onMouseEnter
            PdfAction enter = PdfAction.JavaScript(
                string.Format(JS1, imdb), stamper.Writer
                );

            widget.SetAdditionalActions(PdfName.E, enter);
            // Hide the popup onMouseExit
            PdfAction exit = PdfAction.JavaScript(
                string.Format(JS2, imdb), stamper.Writer
                );

            widget.SetAdditionalActions(PdfName.X, exit);
            // Add the button annotation
            stamper.AddAnnotation(widget, 1);
        }
Exemplo n.º 8
0
 /**
  * Creates the actual annotation and adds different elements to the
  * PdfWriter while doing so.
  * @return  a PdfAnnotation
  */
 virtual public PdfAnnotation CreateAnnotation()
 {
     if (richMediaContent != null)
     {
         if (assetsmap.Count > 0)
         {
             PdfDictionary assets = PdfNameTree.WriteTree(assetsmap, writer);
             richMediaContent.Put(PdfName.ASSETS, writer.AddToBody(assets).IndirectReference);
         }
         if (configurations.Size > 0)
         {
             richMediaContent.Put(PdfName.CONFIGURATION, writer.AddToBody(configurations).IndirectReference);
         }
         if (views.Size > 0)
         {
             richMediaContent.Put(PdfName.VIEWS, writer.AddToBody(views).IndirectReference);
         }
         richMediaContentReference = writer.AddToBody(richMediaContent).IndirectReference;
     }
     writer.AddDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
     annot.Put(PdfName.RICHMEDIACONTENT, richMediaContentReference);
     annot.Put(PdfName.RICHMEDIASETTINGS, writer.AddToBody(richMediaSettings).IndirectReference);
     return(annot);
 }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="writer"></param>
        /// <param name="pageNumber"></param>
        internal static void ExtractPdfComments(ref PdfReader reader, ref PdfWriter writer, int pageNumber)
        {
            if (reader == null || writer == null || pageNumber < 1)
            {
                return;
            }

            var annots = reader.GetPageN(pageNumber).GetAsArray(PdfName.ANNOTS);

            if (annots != null)
            {
                PdfDictionary             dict;
                iTextSharp.text.Rectangle bounds;
                PdfAnnotation             toAdd;
                System.Collections.Generic.IEnumerable <float> rect2;
                foreach (var item in annots)
                {
                    dict = PdfReader.GetPdfObject(item) as PdfDictionary;
                    //Evita di estrarre nuovamente gli allegati.
                    if (dict != null && !PdfName.FILEATTACHMENT.Equals(dict.GetAsName(PdfName.SUBTYPE)))
                    {
                        //Non copiare MAI l'annotazione "/Rect" !
                        if (dict.Keys != null && dict.Keys.Any(x => x.Equals(PdfName.RECT)))
                        {
                            rect2 = dict.GetAsArray(PdfName.RECT).ArrayList
                                    .OfType <PdfNumber>()
                                    .Select(x => x.FloatValue);

                            bounds = new iTextSharp.text.Rectangle(rect2.ElementAt(0), rect2.ElementAt(1), rect2.ElementAt(2), rect2.ElementAt(3));

                            toAdd = new PdfAnnotation(writer, bounds);

                            foreach (var chiave in dict.Keys.OfType <PdfName>())
                            {
                                //Non copiare MAI l'annotazione "/Rect" !
                                if (!chiave.Equals(PdfName.RECT))
                                {
                                    toAdd.Put(chiave, dict.Get(chiave));
                                }
                            }
                            //
                            writer.AddAnnotation(toAdd);
                        }
                    }
                }
            }
        }
        // Add annotation to PDF using iTextSharp
        private void addTextAnnotationToPDF(string filePath, string contents, int pageNum, int x, int y, int width, int height)
        {
            PdfReader  pdfReader = null;
            PdfStamper pdfStamp  = null;

            try
            {
                using (var inStream = new FileStream(filePath, FileMode.Open))
                {
                    pdfReader = new PdfReader(inStream);
                }

                using (var outStream = new FileStream(filePath, FileMode.Create))
                {
                    pdfStamp = new PdfStamper(pdfReader, outStream, (char)0, true);

                    var rect = new iTextSharp.text.Rectangle((float)x, (float)y, (float)x + width, (float)y + height);

                    // Generating the annotation's appearance using a TextField
                    TextField textField = new TextField(pdfStamp.Writer, rect, null);
                    textField.Text            = contents;
                    textField.FontSize        = 8;
                    textField.TextColor       = BaseColor.DARK_GRAY;
                    textField.BackgroundColor = new BaseColor(Color.LightGoldenrodYellow);
                    textField.BorderColor     = new BaseColor(Color.BurlyWood);
                    textField.Options         = TextField.MULTILINE;
                    textField.SetExtraMargin(2f, 2f);
                    textField.Alignment = Element.ALIGN_TOP | Element.ALIGN_LEFT;
                    PdfAppearance appearance = textField.GetAppearance();

                    // Create the annotation
                    PdfAnnotation annotation = PdfAnnotation.CreateFreeText(pdfStamp.Writer, rect, null, new PdfContentByte(null));
                    annotation.SetAppearance(PdfName.N, appearance);
                    annotation.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_LOCKED | PdfAnnotation.FLAGS_PRINT;
                    annotation.Put(PdfName.NM, new PdfString(Guid.NewGuid().ToString()));

                    // Add annotation to PDF
                    pdfStamp.AddAnnotation(annotation, pageNum);
                    pdfStamp.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not add signature image to PDF with error: " + ex.Message);
            }
        }
Exemplo n.º 11
0
        public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize)
        {
            PdfArray array       = new PdfArray();
            int      rotation    = pageSize.Rotation % 360;
            int      currentPage = writer.CurrentPageNumber;

            for (int k = 0; k < annotations.Count; ++k)
            {
                PdfAnnotation dic  = annotations[k];
                int           page = dic.PlaceInPage;
                if (page > currentPage)
                {
                    delayedAnnotations.Add(dic);
                    continue;
                }
                if (dic.IsForm())
                {
                    if (!dic.IsUsed())
                    {
                        Dictionary <PdfTemplate, object> templates = dic.Templates;
                        if (templates != null)
                        {
                            acroForm.AddFieldTemplates(templates);
                        }
                    }
                    PdfFormField field = (PdfFormField)dic;
                    if (field.Parent == null)
                    {
                        acroForm.AddDocumentField(field.IndirectReference);
                    }
                }
                if (dic.IsAnnotation())
                {
                    array.Add(dic.IndirectReference);
                    if (!dic.IsUsed())
                    {
                        PdfArray     tmp = dic.GetAsArray(PdfName.RECT);
                        PdfRectangle rect;
                        if (tmp.Size == 4)
                        {
                            rect = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue, tmp.GetAsNumber(2).FloatValue, tmp.GetAsNumber(3).FloatValue);
                        }
                        else
                        {
                            rect = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue);
                        }
                        if (rect != null)
                        {
                            switch (rotation)
                            {
                            case 90:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            pageSize.Top - rect.Bottom,
                                            rect.Left,
                                            pageSize.Top - rect.Top,
                                            rect.Right));
                                break;

                            case 180:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            pageSize.Right - rect.Left,
                                            pageSize.Top - rect.Bottom,
                                            pageSize.Right - rect.Right,
                                            pageSize.Top - rect.Top));
                                break;

                            case 270:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            rect.Bottom,
                                            pageSize.Right - rect.Left,
                                            rect.Top,
                                            pageSize.Right - rect.Right));
                                break;
                            }
                        }
                    }
                }
                if (!dic.IsUsed())
                {
                    dic.SetUsed();
                    writer.AddToBody(dic, dic.IndirectReference);
                }
            }
            return(array);
        }
Exemplo n.º 12
0
        public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize)
        {
            PdfArray array       = new PdfArray();
            int      rotation    = pageSize.Rotation % 360;
            int      currentPage = writer.CurrentPageNumber;

            for (int k = 0; k < Annotations.Count; ++k)
            {
                PdfAnnotation dic  = (PdfAnnotation)Annotations[k];
                int           page = dic.PlaceInPage;
                if (page > currentPage)
                {
                    DelayedAnnotations.Add(dic);
                    continue;
                }
                if (dic.IsForm())
                {
                    if (!dic.IsUsed())
                    {
                        Hashtable templates = dic.Templates;
                        if (templates != null)
                        {
                            acroForm.AddFieldTemplates(templates);
                        }
                    }
                    PdfFormField field = (PdfFormField)dic;
                    if (field.Parent == null)
                    {
                        acroForm.AddDocumentField(field.IndirectReference);
                    }
                }
                if (dic.IsAnnotation())
                {
                    array.Add(dic.IndirectReference);
                    if (!dic.IsUsed())
                    {
                        PdfRectangle rect = (PdfRectangle)dic.Get(PdfName.Rect);
                        if (rect != null)
                        {
                            switch (rotation)
                            {
                            case 90:
                                dic.Put(PdfName.Rect, new PdfRectangle(
                                            pageSize.Top - rect.Bottom,
                                            rect.Left,
                                            pageSize.Top - rect.Top,
                                            rect.Right));
                                break;

                            case 180:
                                dic.Put(PdfName.Rect, new PdfRectangle(
                                            pageSize.Right - rect.Left,
                                            pageSize.Top - rect.Bottom,
                                            pageSize.Right - rect.Right,
                                            pageSize.Top - rect.Top));
                                break;

                            case 270:
                                dic.Put(PdfName.Rect, new PdfRectangle(
                                            rect.Bottom,
                                            pageSize.Right - rect.Left,
                                            rect.Top,
                                            pageSize.Right - rect.Right));
                                break;
                            }
                        }
                    }
                }
                if (!dic.IsUsed())
                {
                    dic.SetUsed();
                    writer.AddToBody(dic, dic.IndirectReference);
                }
            }
            return(array);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Estrae i commenti "embedded" nel documento il cui contenuto è fornito in input sotto forma di array di bytes.
        /// </summary>
        /// <param name="inputDoc">B[L]OB : contenuto del PDF.</param>
        /// <returns>B[L]OB del documento fornito in input, manipolato.</returns>
        internal static byte[] ExtractPdfComments(byte[] inputDoc)
        {
            var pdfReader = new PdfReader(inputDoc);
            var retval    = new byte[0];

            //
            using (var document = new Document(PageSize.A4))
            {
                //Usare un memory stream evita di dover usare un file temporaneo su disco.
                using (var memStream = new MemoryStream())
                {
                    using (var pdfWriter = PdfWriter.GetInstance(document, memStream))
                    {
                        document.Open();
                        try
                        {
                            for (var idx = 1; idx < pdfReader.NumberOfPages + 1; idx++)
                            {
                                pdfWriter.DirectContent.AddTemplate(pdfWriter.GetImportedPage(pdfReader, idx), 0f, 0f);

                                var annots = pdfReader.GetPageN(idx)
                                             .GetAsArray(PdfName.ANNOTS);

                                if (annots != null)
                                {
                                    PdfDictionary             dict;
                                    iTextSharp.text.Rectangle bounds;
                                    PdfAnnotation             toAdd;
                                    System.Collections.Generic.IEnumerable <float> rect;
                                    foreach (var item in annots)
                                    {
                                        dict = PdfReader.GetPdfObject(item) as PdfDictionary;
                                        //Evita di estrarre nuovamente gli allegati.
                                        if (dict != null && !PdfName.FILEATTACHMENT.Equals(dict.GetAsName(PdfName.SUBTYPE)))
                                        {
                                            //Non copiare MAI l'annotazione "/Rect" !
                                            if (dict.Keys != null && dict.Keys.Any(x => x.Equals(PdfName.RECT)))
                                            {
                                                rect = dict.GetAsArray(PdfName.RECT).ArrayList
                                                       .OfType <PdfNumber>()
                                                       .Select(x => x.FloatValue);

                                                bounds = new iTextSharp.text.Rectangle(rect.ElementAt(0), rect.ElementAt(1), rect.ElementAt(2), rect.ElementAt(3));

                                                toAdd = new PdfAnnotation(pdfWriter, bounds);

                                                foreach (var chiave in dict.Keys.OfType <PdfName>())
                                                {
                                                    //Non copiare MAI l'annotazione "/Rect" !
                                                    if (!chiave.Equals(PdfName.RECT))
                                                    {
                                                        toAdd.Put(chiave, dict.Get(chiave));
                                                    }
                                                }
                                                //
                                                pdfWriter.AddAnnotation(toAdd);
                                            }
                                        }
                                    }
                                }
                                document.NewPage();
                            }
                        }
                        finally
                        {
                            try { pdfWriter.Close(); }
                            catch { }
                            try { pdfReader.Close(); }
                            catch { }
                        }
                    }
                    try { document.Close(); }
                    catch { }
                    retval = memStream.ToArray();
                }
            }
            return(retval);
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        public void CreatePDFFile111(string strPDFPath, string attachment)
        {
            try
            {
                if (!File.Exists(attachment))
                {
                    throw new FileNotFoundException("File Not Found", attachment);
                }


                string fileName           = Path.GetFileName(attachment);
                string fileNameWithOutExt = Path.GetFileNameWithoutExtension(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(fileNameWithOutExt, false);
                            //pdfWriter.AddFileAttachment(fs);
                            Rectangle rec = new Rectangle(150, 150);
                            //PdfAnnotation annotation = PdfAnnotation.CreateFileAttachment(pdfWriter, rec, fileName, fs);

                            //PdfAnnotation annotation = PdfAnnotation.CreateFileAttachment(pdfWriter, new iTextSharp.text.Rectangle(100, 200), "Link", fs);
                            //chapter1.Add(annotation);

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


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

                            Chunk linkChunk = new Chunk("Click Here to Download");
                            linkChunk.SetAnnotation(annotation);
                            Phrase phrase = new Phrase();
                            phrase.Add(linkChunk);

                            //PdfAction action = PdfAction.

                            //pdfWriter.AddFileAttachment(fileNameWithOutExt, StrToByteArray(attachment), fileName, fileNameWithOutExt);

                            //PdfAnnotation action = PdfAnnotation.CreateFileAttachment(pdfWriter, null, fileName, fs);
                            //PdfAnnotation action = PdfAnnotation.CreateFileAttachment(pdfWriter, null, fileName, null, attachment, fileNameWithOutExt);
                            //Paragraph pa = new Paragraph();
                            //Chunk chk1 = new Chunk("click here");

                            //chk1.SetAnchor("https://www.google.com");
                            //chk1.SetAnnotation(action);
                            //pa.Add(chk1);
                            document.Add(phrase);
                            document.Close();
                            pdfWriter.Close();
                            pdfWriter.Dispose();
                        }
                        pdf.Close();
                        pdf.Dispose();
                    }
                    document.Dispose();
                }
            }
            catch (Exception ex)
            {
            }
        }