Example #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);
            }
        }
        // private void highlightPDFAnnotation(string readerPath, string outputFile, int pageno, string[] highlightText)
        private void highlightPDFAnnotation(string readerPath, string outputFile, string[] highlightText)
        {
            PdfReader      reader = new PdfReader(readerPath);
            PdfContentByte canvas;

            using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    int pageCount = reader.NumberOfPages;
                    for (int pageno = 1; pageno <= pageCount; pageno++)
                    {
                        var strategy = new HighLightTextLocation();
                        strategy.UndercontentHorizontalScaling = 100;

                        string currentText = PdfTextExtractor.GetTextFromPage(reader, pageno, strategy);
                        for (int i = 0; i < highlightText.Length; i++)
                        {
                            List <Rectangle> MatchesFound = strategy.GetTextLocations(highlightText[i].Trim(), StringComparison.CurrentCultureIgnoreCase);
                            foreach (Rectangle rect in MatchesFound)
                            {
                                float[] quad = { rect.Left - 3.0f, rect.Bottom, rect.Right, rect.Bottom, rect.Left - 3.0f, rect.Top + 1.0f, rect.Right, rect.Top + 1.0f };
                                //Create our hightlight
                                PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                                //Set the color
                                highlight.Color = BaseColor.YELLOW;

                                PdfAppearance appearance = PdfAppearance.CreateAppearance(stamper.Writer, rect.Width, rect.Height);
                                PdfGState     state      = new PdfGState();
                                state.BlendMode = new PdfName("Multiply");
                                appearance.SetGState(state);
                                appearance.Rectangle(0, 0, rect.Width, rect.Height);
                                appearance.SetColorFill(BaseColor.YELLOW);
                                appearance.Fill();

                                highlight.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);

                                //Add the annotation
                                stamper.AddAnnotation(highlight, pageno);
                            }
                        }
                    }
                }
            }
            reader.Close();
        }
        // 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);
            }
        }
Example #4
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";
        }
Example #5
0
        /// <summary>
        /// Highlights the PDF with Yellow annotation
        /// </summary>
        /// <param name="inputFile">File to read from</param>
        /// <param name="highLightFile">File to write to</param>
        /// <param name="pageno">Which page no to read</param>
        /// <param name="textToAnnotate">Texts to annotate</param>
        private void HighlightPDFAnnotation(string inputFile, string highLightFile, int pageno, params string[] textToAnnotate)
        {
            PdfReader reader = new PdfReader(inputFile);

            using (FileStream fs = new FileStream(highLightFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    MyLocationTextExtractionStrategy strategy = new MyLocationTextExtractionStrategy();
                    strategy.UndercontentHorizontalScaling = 100;

                    string currentText = PdfTextExtractor.GetTextFromPage(reader, pageno, strategy);
                    for (int i = 0; i < textToAnnotate.Length; i++)
                    {
                        if (string.IsNullOrWhiteSpace(textToAnnotate[i]))
                        {
                            continue;
                        }
                        var lstMatches = strategy.GetTextLocations(textToAnnotate[i].Trim(), StringComparison.CurrentCultureIgnoreCase);
                        if (!this.chkAnnotation.Checked)
                        {
                            lstMatches = lstMatches.Take(1).ToList();
                        }
                        foreach (iTextSharp.text.Rectangle rectangle in lstMatches)
                        {
                            float[] quadPoints = { rectangle.Left - 3.0f,
                                                   rectangle.Bottom,
                                                   rectangle.Right,
                                                   rectangle.Bottom,
                                                   rectangle.Left - 3.0f,
                                                   rectangle.Top + 1.0f,
                                                   rectangle.Right,
                                                   rectangle.Top + 1.0f };


                            PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer
                                                                                 , rectangle, null
                                                                                 , PdfAnnotation.MARKUP_HIGHLIGHT, quadPoints);
                            highlight.Color = BaseColor.YELLOW;


                            PdfGState state = new PdfGState();
                            state.BlendMode = new PdfName("Multiply");


                            PdfAppearance appearance = PdfAppearance.CreateAppearance(stamper.Writer, rectangle.Width, rectangle.Height);

                            appearance.SetGState(state);
                            appearance.Rectangle(0, 0, rectangle.Width, rectangle.Height);
                            appearance.SetColorFill(BaseColor.YELLOW);
                            appearance.Fill();

                            highlight.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);

                            //Add the annotation
                            stamper.AddAnnotation(highlight, pageno);
                        }
                    }
                }
            }
            reader.Close();
        }
Example #6
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);
        }