Ejemplo n.º 1
0
        private void CopyExistingField(PdfPage toPage, PdfAnnotation currentAnnot)
        {
            PdfFormField field = MergeFieldsWithTheSameName(PdfFormField.MakeFormField(currentAnnot.GetPdfObject(), toPage
                                                                                       .GetDocument()));
            PdfArray kids = field.GetKids();

            if (kids != null)
            {
                field.GetPdfObject().Remove(PdfName.Kids);
                formTo.AddField(field, toPage);
                field.GetPdfObject().Put(PdfName.Kids, kids);
            }
            else
            {
                formTo.AddField(field, toPage);
            }
        }
        // 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);
            }
        }
         private void Form1_Load(object sender, EventArgs e)
         {
             //Create a simple test file
             string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
 
             using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
             {
                 using (Document doc = new Document(PageSize.LETTER))
                 {
                     using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                     {
                         doc.Open();
                         doc.Add(new Paragraph("This is a test"));
                         doc.Close();
                     }
                 }
             }
 
             //Create a new file from our test file with highlighting
             string highLightFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Highlighted.pdf");
 
             //Bind a reader and stamper to our test PDF
             PdfReader reader = new PdfReader(outputFile);
             
             using (FileStream fs = new FileStream(highLightFile, FileMode.Create, FileAccess.Write, FileShare.None))
             {
                 using (PdfStamper stamper = new PdfStamper(reader, fs))
                 {
                     //Create a rectangle for the highlight. NOTE: Technically this isn't used but it helps with the quadpoint calculation
                     iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(60.6755f, 749.172f, 94.0195f, 735.3f);
                     //Create an array of quad points based on that rectangle. NOTE: The order below doesn't appear to match the actual spec but is what Acrobat produces
                     float[] quad = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
 
                     //Create our hightlight
                     PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
 
                     //Set the color
                     highlight.Color = BaseColor.YELLOW;
 
                     //Add the annotation
                     stamper.AddAnnotation(highlight,1);
                 }
             }
 
             this.Close();
         }
 public virtual void TestCopyingPageWithAnnotationContainingIrtKey()
 {
     NUnit.Framework.Assert.That(() => {
         // TODO remove expected exception and thus enable assertions when DEVSIX-3585 is implemented
         String inFilePath            = sourceFolder + "annotation-with-irt.pdf";
         String outFilePath           = destinationFolder + "copy-annotation-with-irt.pdf";
         PdfDocument originalDocument = new PdfDocument(new PdfReader(inFilePath));
         PdfDocument outDocument      = new PdfDocument(new PdfWriter(outFilePath));
         originalDocument.CopyPagesTo(1, 1, outDocument);
         // During the second copy call we have to rebuild/preserve all the annotation relationship (IRT in this case),
         // so that we don't end up with annotation on one page referring to an annotation on another page as its IRT
         // or as its parent
         originalDocument.CopyPagesTo(1, 1, outDocument);
         originalDocument.Close();
         outDocument.Close();
         outDocument = new PdfDocument(new PdfReader(outFilePath));
         for (int pageNum = 1; pageNum <= outDocument.GetNumberOfPages(); pageNum++)
         {
             PdfPage page = outDocument.GetPage(pageNum);
             NUnit.Framework.Assert.AreEqual(4, page.GetAnnotsSize());
             NUnit.Framework.Assert.AreEqual(4, page.GetAnnotations().Count);
             bool foundMarkupAnnotation = false;
             foreach (PdfAnnotation annotation in page.GetAnnotations())
             {
                 PdfDictionary annotationPageDict = annotation.GetPageObject();
                 if (annotationPageDict != null)
                 {
                     NUnit.Framework.Assert.AreSame(page.GetPdfObject(), annotationPageDict);
                 }
                 if (annotation is PdfMarkupAnnotation)
                 {
                     foundMarkupAnnotation   = true;
                     PdfDictionary inReplyTo = ((PdfMarkupAnnotation)annotation).GetInReplyToObject();
                     NUnit.Framework.Assert.IsTrue(page.ContainsAnnotation(PdfAnnotation.MakeAnnotation(inReplyTo)), "IRT reference must point to annotation present on the same page"
                                                   );
                 }
             }
             NUnit.Framework.Assert.IsTrue(foundMarkupAnnotation, "Markup annotation expected to be present but not found"
                                           );
         }
         outDocument.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <AssertionException>())
     ;
 }
        public static PdfAnnotation ToPDFPolygon(this Autodesk.DesignScript.Geometry.Polygon polygon, string content, PdfWriter writer)
        {
            List <float> points = new List <float>();

            foreach (var pt in polygon.Points)
            {
                PDFCoords coords = pt.ToPDFCoords();
                points.Add(coords.X);
                points.Add(coords.Y);
            }

            iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(0, 0);

            var app  = new PdfContentByte(writer);
            var anno = PdfAnnotation.CreatePolygonPolyline(writer, rect, content, true, new PdfArray(points.ToArray()));

            return(anno);
        }
Ejemplo n.º 6
0
        //--------------------------------------------------------------------------------------------------
        void AddHeader(PdfStamper stamper, PdfReader reader, string stComment)
        {
            PdfContentByte canvas = stamper.GetOverContent(1);

            canvas.BeginText();
            canvas.SetFontAndSize(GetDefaultFont(), 12);
            Rectangle rect = reader.GetPageSizeWithRotation(1);

            canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stComment, (rect.Left + rect.Right) / 2, rect.Top - 12, 0);
            canvas.EndText();
            rect.Bottom = rect.Top - 18;
            float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
            PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);

            highlight.Color = BaseColor.YELLOW;
            highlight.Title = "PDFCompare";
            stamper.AddAnnotation(highlight, 1);
        }
Ejemplo n.º 7
0
        private void Benny()
        {
            // create embedded media file
            PdfEmbeddedFile EmbeddedMediaFile = new PdfEmbeddedFile(Document, "Benny.mov");

            // Section 8.5 page 669 table 8.64
            PdfDisplayMedia DisplayMedia = new PdfDisplayMedia(EmbeddedMediaFile);

            // repeat count (zero is play indefinitly)
            DisplayMedia.RepeatCount(0);

            PdfRectangle AnnotRect = ImageSizePos.ImageArea(1920, 1080, 1.5, 2.0, 5.5, 7.0, ContentAlignment.TopLeft);

            // create PdfObject for annotation
            PdfAnnotation Annotation = new PdfAnnotation(Page, AnnotRect, DisplayMedia);

            return;
        }
        static void Main(string[] args)
        {
            //Initialize an instance of PdfDocument class and  load the file
            PdfDocument pdf = new PdfDocument(@"C:\Users\Administrator\Desktop\Annotation.pdf");

            //Get the first annotation in the first page
            PdfAnnotation annotation = pdf.Pages[0].AnnotationsWidget[0];

            //Add the modified text and set the formatting
            annotation.Text   = " Dedicate to the task of providing the world with an objective, scientific view of climate change and its political and economic impacts.";
            annotation.Border = new PdfAnnotationBorder(1f);
            annotation.Color  = new PdfRGBColor(Color.LightGreen);
            annotation.Flags  = PdfAnnotationFlags.Locked;

            //Save the file and view
            pdf.SaveToFile("result.pdf");
            System.Diagnostics.Process.Start("result.pdf");
        }
        public virtual void NoForbidReleaseObjectsModifyingTest()
        {
            String srcFile       = sourceFolder + "noForbidReleaseObjectsModifying.pdf";
            String stampReleased = sourceFolder + "noForbidReleaseObjectsModified.pdf";

            using (PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(destinationFolder + "noForbidReleaseObjectsModifying.pdf"
                                                                                           ), new StampingProperties().UseAppendMode())) {
                PdfAnnotation annots = doc.GetPage(1).GetAnnotations()[0];
                annots.SetRectangle(new PdfArray(new Rectangle(100, 100, 80, 50)));
                annots.GetRectangle().Release();
            }
            using (PdfDocument openPrev = new PdfDocument(new PdfReader(stampReleased))) {
                NUnit.Framework.Assert.IsTrue(new Rectangle(100, 100, 80, 50).EqualsWithEpsilon(openPrev.GetPage(1).GetAnnotations
                                                                                                    ()[0].GetRectangle().ToRectangle()));
            }
            NUnit.Framework.Assert.IsNotNull(new CompareTool().CompareByContent(srcFile, stampReleased, destinationFolder
                                                                                ));
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
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);
            }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
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)));
            }
        }
Ejemplo n.º 14
0
// ---------------------------------------------------------------------------

        /**
         * Implementation of the cellLayout method.
         * @see com.itextpdf.text.pdf.PdfPCellEvent#cellLayout(
         * com.itextpdf.text.pdf.PdfPCell, com.itextpdf.text.Rectangle,
         * com.itextpdf.text.pdf.PdfContentByte[])
         */
        public void CellLayout(
            PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
        {
            try {
                PdfAnnotation annotation = PdfAnnotation.CreateFileAttachment(
                    writer,
                    new Rectangle(
                        position.Left - 20, position.Top - 15,
                        position.Left - 5, position.Top - 5
                        ),
                    description, fs
                    );
                annotation.Name = description;
                writer.AddAnnotation(annotation);
            }
            catch {
                throw;
            }
        }
Ejemplo n.º 15
0
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
        public static PdfAnnotation ToPDFPolygon(this Autodesk.DesignScript.Geometry.PolyCurve polycurve, string content, PdfWriter writer)
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
        {
            List <float> points = new List <float>();

            foreach (var curve in polycurve.Curves())
            {
                PDFCoords coords = curve.StartPoint.ToPDFCoords();
                points.Add(coords.X);
                points.Add(coords.Y);
            }

            iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(0, 0);

            var app  = new PdfContentByte(writer);
            var anno = PdfAnnotation.CreatePolygonPolyline(writer, rect, content, false, new PdfArray(points.ToArray()));

            return(anno);
        }
Ejemplo n.º 16
0
        private void Example2()
        {
            // create embedded media file
            PdfEmbeddedFile EmbeddedMediaFile = new PdfEmbeddedFile(Document, "Ring01.wav");

            PdfDisplayMedia DisplayMedia = new PdfDisplayMedia(EmbeddedMediaFile);
            //DisplayMedia.SetMediaWindow(MediaWindow.Hidden);

            PdfRectangle AnnotRect = new PdfRectangle(5.2, 3.7, 7.3, 5.8);

            // create PdfObject for annotation
            PdfAnnotation Annotation = new PdfAnnotation(Page, AnnotRect, DisplayMedia);

            PdfXObject Normal   = AnnotationArea(AnnotRect.Width, AnnotRect.Height, Color.Lavender, Color.Indigo, "Normal");
            PdfXObject RollOver = AnnotationArea(AnnotRect.Width, AnnotRect.Height, Color.Yellow, Color.Brown, "RollOver");
            PdfXObject Down     = AnnotationArea(AnnotRect.Width, AnnotRect.Height, Color.LightPink, Color.DarkRed, "Down");

            Annotation.Appearance(Normal, RollOver, Down);
            return;
        }
Ejemplo n.º 17
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
                                         ));
            }
        }
Ejemplo n.º 18
0
        public virtual void CreatePdf(String dest)
        {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            //Initialize document
            Document  document = new Document(pdf);
            Paragraph p        = new Paragraph("The example of text markup annotation.");

            document.ShowTextAligned(p, 20, 795, 1, TextAlignment.LEFT, VerticalAlignment.MIDDLE, 0);
            //Create text markup annotation
            PdfAnnotation ann = PdfTextMarkupAnnotation.CreateHighLight(new Rectangle(105, 790, 64, 10), new float[] {
                169, 790, 105, 790, 169, 800, 105, 800
            }).SetColor(ColorConstants.YELLOW).SetTitle(new PdfString("Hello!")).SetContents
                                    (new PdfString("I'm a popup.")).SetTitle(new PdfString("iText")).SetRectangle(new PdfArray
                                                                                                                      (new float[] { 100, 600, 200, 100 }));

            pdf.GetFirstPage().AddAnnotation(ann);
            //Close document
            document.Close();
        }
Ejemplo n.º 19
0
        public virtual void CreatePdf(String dest)
        {
            PdfDocument   pdf      = new PdfDocument(new PdfWriter(dest));
            Document      document = new Document(pdf);
            PdfAction     js       = PdfAction.CreateJavaScript("app.alert('Boo!');");
            PdfAnnotation la1      = ((PdfLinkAnnotation) new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetHighlightMode(
                                          PdfAnnotation.HIGHLIGHT_INVERT).SetAction(js)).SetBorderStyle(PdfAnnotation.STYLE_UNDERLINE);
            Link link1 = new Link("here", (PdfLinkAnnotation)la1);

            document.Add(new Paragraph().Add("Click ").Add(link1).Add(" if you want to be scared."));
            PdfAnnotation la2 = new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetDestination(PdfExplicitDestination
                                                                                                .CreateFit(2)).SetHighlightMode(PdfAnnotation.HIGHLIGHT_PUSH).SetBorderStyle(PdfAnnotation.STYLE_INSET
                                                                                                                                                                             );
            Link link2 = new Link("next page", (PdfLinkAnnotation)la2);

            document.Add(new Paragraph().Add("Go to the ").Add(link2).Add(" if you're too scared."));
            document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
            document.Add(new Paragraph().Add("There, there, everything is OK."));
            document.Close();
        }
Ejemplo n.º 20
0
        public void SaveComments(string namePDF, int page)
        {
            string oldFile = namePDF;
            string newFile = "temporal.pdf";

            PdfReader  pdfReader  = new PdfReader(oldFile);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));

            Point[] finalcoor = coorComentario.ToArray();
            for (int i = 1; i <= cantComentarios; i++)
            {
                string imageURL = directorio + "\\comment" + i + ".jpg";

                Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read, FileShare.Read);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                //int xpos = finalcoor[i - 1].X;
                //int ypos = finalcoor[i - 1].Y;
                Console.WriteLine("estas son las coordenadas" + finalcoor[i - 1].X + " y " + finalcoor[i - 1].Y);
                int xpos = 100;
                int ypos = 100;
                iTextSharp.text.Rectangle rect     = new iTextSharp.text.Rectangle(35 + xpos, 650 - ypos, 35 + xpos + Convert.ToSingle(image.Width * 0.5), 650 - ypos + Convert.ToSingle(image.Height * 0.5));
                PdfAnnotation             pdfStamp = PdfAnnotation.CreateStamp(pdfStamper.Writer, rect, null, Guid.NewGuid().ToString());
                image.SetAbsolutePosition(0, 0);
                PdfAppearance app = pdfStamper.GetOverContent(1).CreateAppearance(Convert.ToSingle(image.Width * 0.5), Convert.ToSingle(image.Height * 0.5));
                image.ScalePercent(50);
                app.AddImage(image);
                pdfStamp.SetAppearance(PdfName.N, app);
                pdfStamp.SetPage();
                pdfStamp.Flags = PdfAnnotation.FLAGS_PRINT;
                pdfStamper.AddAnnotation(pdfStamp, 1);
            }


            pdfStamper.Close();
            pdfReader.Close();
            File.Replace(newFile, oldFile, @"backup.pdf.bac");

            Console.WriteLine("Pdf modificado con exito, se ha guardado un backup de la versión anterior ");
            //axAcroPDF1.src = "C:\\Users\\Denisse\\Desktop\\prototipos\\prot2_ReconocerTexto\\prot2_ReconocerTexto\\bin\\Debug\\ejemploOK.pdf";
        }
Ejemplo n.º 21
0
        public void InsertResetButton(PdfPage page)
        {
            var bounds = page.GetBoundsForBox(PdfDisplayBox.Crop);

            var resetButtonBounds = new CGRect(90, bounds.Height - 680, 106, 32);
            var resetButton       = new PdfAnnotation(resetButtonBounds, PdfAnnotationSubtype.Widget.GetConstant(), null)
            {
                WidgetFieldType   = PdfAnnotationWidgetSubtype.Button.GetConstant(),
                WidgetControlType = PdfWidgetControlType.PushButton,
                Caption           = "Obliviate!"
            };

            page.AddAnnotation(resetButton);

            // Create PDFActionResetForm action to clear form fields.
            var resetFormAction = new PdfActionResetForm()
            {
                FieldsIncludedAreCleared = false
            };

            resetButton.Action = resetFormAction;
        }
Ejemplo n.º 22
0
        /// <summary>Copies page to the specified document.</summary>
        /// <remarks>
        /// Copies page to the specified document.
        /// <br/><br/>
        /// NOTE: Works only for pages from the document opened in reading mode, otherwise an exception is thrown.
        /// </remarks>
        /// <param name="toDocument">a document to copy page to.</param>
        /// <param name="copier">a copier which bears a specific copy logic. May be NULL</param>
        /// <returns>copied page.</returns>
        public virtual iText.Kernel.Pdf.PdfPage CopyTo(PdfDocument toDocument, IPdfPageExtraCopier copier)
        {
            PdfDictionary dictionary = GetPdfObject().CopyTo(toDocument, excludedKeys, true);

            iText.Kernel.Pdf.PdfPage page = new iText.Kernel.Pdf.PdfPage(dictionary);
            CopyInheritedProperties(page, toDocument);
            foreach (PdfAnnotation annot in GetAnnotations())
            {
                if (annot.GetSubtype().Equals(PdfName.Link))
                {
                    GetDocument().StoreLinkAnnotation(this, (PdfLinkAnnotation)annot);
                }
                else
                {
                    page.AddAnnotation(-1, PdfAnnotation.MakeAnnotation(((PdfDictionary)annot.GetPdfObject().CopyTo(toDocument
                                                                                                                    , false))), false);
                }
            }
            if (toDocument.IsTagged())
            {
                page.structParents = (int)toDocument.GetNextStructParentIndex();
                page.GetPdfObject().Put(PdfName.StructParents, new PdfNumber(page.structParents));
            }
            if (copier != null)
            {
                copier.Copy(this, page);
            }
            else
            {
                if (!toDocument.GetWriter().isUserWarnedAboutAcroFormCopying&& GetDocument().GetCatalog().GetPdfObject().
                    ContainsKey(PdfName.AcroForm))
                {
                    ILogger logger = LoggerFactory.GetLogger(typeof(iText.Kernel.Pdf.PdfPage));
                    logger.Warn(LogMessageConstant.SOURCE_DOCUMENT_HAS_ACROFORM_DICTIONARY);
                    toDocument.GetWriter().isUserWarnedAboutAcroFormCopying = true;
                }
            }
            return(page);
        }
Ejemplo n.º 23
0
        public void QuadrilateralPoints()
        {
            using (var obj = new PdfAnnotation()) {
                Assert.IsNotNull(obj.QuadrilateralPoints, "Q1");
                Assert.AreEqual(0, obj.QuadrilateralPoints.Length, "Q1b");

                var points = new CGPoint []
                {
                    new CGPoint(0, 1),
                    new CGPoint(2, 3),
                    new CGPoint(4, 5),
                    new CGPoint(6, 7),
                };

                obj.QuadrilateralPoints = points;
                Assert.AreEqual(points, obj.QuadrilateralPoints, "Q2");

                obj.QuadrilateralPoints = null;
                Assert.IsNotNull(obj.QuadrilateralPoints, "Q3");
                Assert.AreEqual(0, obj.QuadrilateralPoints.Length, "Q3b");
            }
        }
Ejemplo n.º 24
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public virtual byte[] ManipulatePdf(byte[] src)
        {
            locations = PojoFactory.GetLocations();
            // Create a reader
            PdfReader reader = new PdfReader(src);

            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Add the annotations
                    int           page = 1;
                    Rectangle     rect;
                    PdfAnnotation annotation;
                    Movie         movie;
                    foreach (string day in PojoFactory.GetDays())
                    {
                        foreach (Screening screening in PojoFactory.GetScreenings(day))
                        {
                            movie      = screening.movie;
                            rect       = GetPosition(screening);
                            annotation = PdfAnnotation.CreateText(
                                stamper.Writer, rect, movie.MovieTitle,
                                string.Format(INFO, movie.Year, movie.Duration),
                                false, "Help"
                                );
                            annotation.Color = new BaseColor(
                                System.Drawing.ColorTranslator.FromHtml("#" + movie.entry.category.color)
                                );
                            stamper.AddAnnotation(annotation, page);
                        }
                        page++;
                    }
                }
                return(ms.ToArray());
            }
        }
Ejemplo n.º 25
0
 private static ICollection<PdfIndirectReference> GetAllUsedNonFlushedOCGs(IDictionary<PdfPage, PdfPage> page2page
     , PdfDictionary toOcProperties) {
     // NOTE: the PDF is considered to be valid and therefore the presence of OСG in OCProperties.OCGs is not checked
     ICollection<PdfIndirectReference> fromUsedOcgs = new LinkedHashSet<PdfIndirectReference>();
     // Visit the pages in parallel to find non-flush OSGs
     PdfPage[] fromPages = page2page.Keys.ToArray(new PdfPage[0]);
     PdfPage[] toPages = page2page.Values.ToArray(new PdfPage[0]);
     for (int i = 0; i < toPages.Length; i++) {
         PdfPage fromPage = fromPages[i];
         PdfPage toPage = toPages[i];
         // Copy OCGs from annotations
         IList<PdfAnnotation> toAnnotations = toPage.GetAnnotations();
         IList<PdfAnnotation> fromAnnotations = fromPage.GetAnnotations();
         for (int j = 0; j < toAnnotations.Count; j++) {
             if (!toAnnotations[j].IsFlushed()) {
                 PdfDictionary toAnnotDict = toAnnotations[j].GetPdfObject();
                 PdfDictionary fromAnnotDict = fromAnnotations[j].GetPdfObject();
                 PdfAnnotation toAnnot = toAnnotations[j];
                 PdfAnnotation fromAnnot = fromAnnotations[j];
                 if (!toAnnotDict.IsFlushed()) {
                     iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromOcDict(toAnnotDict.GetAsDictionary(PdfName.OC
                         ), fromAnnotDict.GetAsDictionary(PdfName.OC), fromUsedOcgs, toOcProperties);
                     iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetNormalAppearanceObject(), 
                         fromAnnot.GetNormalAppearanceObject(), fromUsedOcgs, toOcProperties);
                     iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetRolloverAppearanceObject(
                         ), fromAnnot.GetRolloverAppearanceObject(), fromUsedOcgs, toOcProperties);
                     iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetDownAppearanceObject(), fromAnnot
                         .GetDownAppearanceObject(), fromUsedOcgs, toOcProperties);
                 }
             }
         }
         PdfDictionary toResources = toPage.GetPdfObject().GetAsDictionary(PdfName.Resources);
         PdfDictionary fromResources = fromPage.GetPdfObject().GetAsDictionary(PdfName.Resources);
         iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromResources(toResources, fromResources, fromUsedOcgs
             , toOcProperties);
     }
     return fromUsedOcgs;
 }
Ejemplo n.º 26
0
        public void AddNavigationTest()
        {
            String         src     = srcFolder + "primes.pdf";
            String         dest    = outFolder + "primes_links.pdf";
            PdfReader      reader  = new PdfReader(src);
            PdfStamper     stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            PdfDestination d       = new PdfDestination(PdfDestination.FIT);
            Rectangle      rect    = new Rectangle(0, 806, 595, 842);
            PdfAnnotation  a10     = PdfAnnotation.CreateLink(stamper.Writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, 2, d);

            stamper.AddAnnotation(a10, 1);
            PdfAnnotation a1 = PdfAnnotation.CreateLink(stamper.Writer, rect, PdfAnnotation.HIGHLIGHT_PUSH, 1, d);

            stamper.AddAnnotation(a1, 2);
            stamper.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(dest, srcFolder + "cmp_primes_links.pdf", outFolder, "diff_");

            if (errorMessage != null)
            {
                Assert.Fail(errorMessage);
            }
        }
Ejemplo n.º 27
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc    = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfPage     firstPage = pdfDoc.GetFirstPage();

            PdfAnnotation sticky          = firstPage.GetAnnotations()[0];
            Rectangle     stickyRectangle = sticky.GetRectangle().ToRectangle();
            PdfAnnotation replySticky     = new PdfTextAnnotation(stickyRectangle)

                                            // This method specifies whether initially the annotation is displayed open or not.
                                            .SetOpen(false)
                                            .SetStateModel(new PdfString("Marked"))
                                            .SetState(new PdfString("Marked"))
                                            .SetIconName(new PdfName("Comment"))

                                            // This method sets an annotation to which the current annotation is "in reply".
                                            // Both annotations shall be on the same page of the document.
                                            .SetInReplyTo(sticky)

                                            // This method sets the text label that will be displayed in the title bar of the annotation's pop-up window
                                            // when open and active. This entry will identify the user who added the annotation.
                                            .SetText(new PdfString("Bruno"))

                                            // This method sets the text that will be displayed for the annotation or the alternate description,
                                            // if this type of annotation does not display text.
                                            .SetContents("Marked set by Bruno")

                                            // This method sets a complete set of enabled and disabled flags at once. If not set specifically
                                            // the default value is 0.
                                            // The argument is an integer interpreted as set of one-bit flags
                                            // specifying various characteristics of the annotation.
                                            .SetFlags(sticky.GetFlags() + PdfAnnotation.HIDDEN);

            firstPage.AddAnnotation(replySticky);
            pdfDoc.Close();
        }
Ejemplo n.º 28
0
        /// <summary>Removes annotation content item from the tag structure.</summary>
        /// <remarks>
        /// Removes annotation content item from the tag structure.
        /// If annotation is not added to the document or is not tagged, nothing will happen.
        /// </remarks>
        /// <returns>
        ///
        /// <see cref="TagTreePointer"/>
        /// instance which points at annotation tag parent if annotation was removed,
        /// otherwise returns null.
        /// </returns>
        public virtual TagTreePointer RemoveAnnotationTag(PdfAnnotation annotation)
        {
            PdfStructElem structElem        = null;
            PdfDictionary annotDic          = annotation.GetPdfObject();
            PdfNumber     structParentIndex = (PdfNumber)annotDic.Get(PdfName.StructParent);

            if (structParentIndex != null)
            {
                PdfObjRef objRef = document.GetStructTreeRoot().FindObjRefByStructParentIndex(annotDic.GetAsDictionary(PdfName
                                                                                                                       .P), structParentIndex.IntValue());
                if (objRef != null)
                {
                    PdfStructElem parent = (PdfStructElem)objRef.GetParent();
                    parent.RemoveKid(objRef);
                    structElem = parent;
                }
            }
            annotDic.Remove(PdfName.StructParent);
            if (structElem != null)
            {
                return(new TagTreePointer(document).SetCurrentStructElem(structElem));
            }
            return(null);
        }
Ejemplo n.º 29
0
        // ---------------------------------------------------------------------------

        /**
         * Creates the PDF.
         * @return the bytes of a PDF file.
         */
        public byte[] CreatePdf()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Document document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();
                    document.Add(new Paragraph(
                                     "This is a list of Kubrick movies available in DVD stores."
                                     ));
                    IEnumerable <Movie> movies = PojoFactory.GetMovies(1)
                                                 .Concat(PojoFactory.GetMovies(4))
                    ;
                    List   list     = new List();
                    string RESOURCE = Utility.ResourcePosters;
                    foreach (Movie movie in movies)
                    {
                        PdfAnnotation annot = PdfAnnotation.CreateFileAttachment(
                            writer, null,
                            movie.GetMovieTitle(false), null,
                            Path.Combine(RESOURCE, movie.Imdb + ".jpg"),
                            string.Format("{0}.jpg", movie.Imdb)
                            );
                        ListItem item = new ListItem(movie.GetMovieTitle(false));
                        item.Add("\u00a0\u00a0");
                        Chunk chunk = new Chunk("\u00a0\u00a0\u00a0\u00a0");
                        chunk.SetAnnotation(annot);
                        item.Add(chunk);
                        list.Add(item);
                    }
                    document.Add(list);
                }
                return(ms.ToArray());
            }
        }
Ejemplo n.º 30
0
        // ********************************************************************
        // Fct:     GetNextPdfComment
        //
        // Descr:   -
        //
        // Owner:   erst
        // ********************************************************************
        private static bool GetNextPdfComment(PdfPage page, ref float x, ref float y, ref string content, ref int annotNo)
        {
            // Collects all comment annotations in the document
            Collection <PdfAnnotation> annotations = new Collection <PdfAnnotation>(page.GetAnnotations());

            while (annotNo <= annotations.Count)
            {
                PdfAnnotation annot = annotations[annotNo - 1];   // Array starts with index 0, annotNo starts with 1
                if (annot.GetType().Equals((typeof(iText.Kernel.Pdf.Annot.PdfTextAnnotation))))
                {
                    PdfDictionary annotDictionary = annot.GetPdfObject();

                    //Rect is the annotation rectangle defining the location of the annotation on the page
                    PdfArray Arr = annotDictionary.GetAsArray(PdfName.Rect);

                    //int x = Arr.GetAsNumber(0).IntValue();
                    //int y = Arr.GetAsNumber(1).IntValue();

                    Rectangle rect = annotDictionary.GetAsRectangle(PdfName.Rect);
                    x = rect.GetX();
                    y = rect.GetY();

                    //Read the content
                    content = annotDictionary.Get(PdfName.Contents).ToString();

                    annotNo++;
                    return(true);
                }
                else
                {
                    annotNo++;
                }
            }

            return(false);
        }