private void createTextfield_withBorder_singleline(float seiteLinks, float seiteRechts, float seiteUnten, float seiteOben, string text, int fontsize)
        {
            TextField textField = CreateTextField(seiteLinks, seiteRechts, seiteUnten, seiteOben, text, fontsize);

            textField.BorderColor = BaseColor.RED;
            _pdfStamper.AddAnnotation(textField.GetTextField(), 1);
        }
Exemplo n.º 2
0
        private void CreateOutput(string PDFInput)
        {
            try
            {
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(@PDFInput);
                FileStream fs    = new FileStream(@PDFInput.Replace("Input", "Output"), FileMode.Create, FileAccess.Write);
                PdfStamper stamp = new PdfStamper(reader, fs);
                //Loop from here

                //MessageBox.Show(dataGridView1.RowCount.ToString());
                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    string comptype = dataGridView1.Rows[i].Cells[3].Value.ToString();

                    string complocation = dataGridView1.Rows[i].Cells[1].Value.ToString();

                    float llx = float.Parse(complocation.Split(' ')[0]);
                    float lly = float.Parse(complocation.Split(' ')[1]);
                    float urx = float.Parse(complocation.Split(' ')[2]);
                    float ury = float.Parse(complocation.Split(' ')[3]);


                    if (comptype == "TE")
                    {
                        int          x  = Int32.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString());
                        PdfFormField ff = PdfFormField.CreateTextField(stamp.Writer, false, false, 50);
                        ff.SetWidget(new iTextSharp.text.Rectangle(llx, lly, urx, ury), PdfAnnotation.HIGHLIGHT_INVERT);
                        ff.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
                        ff.FieldName = dataGridView1.Rows[i].Cells[0].Value.ToString();
                        stamp.AddAnnotation(ff, x);
                    }
                    else if (comptype == "CB")
                    {
                        int             x     = Int32.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString());
                        RadioCheckField fCell = new RadioCheckField(stamp.Writer, new iTextSharp.text.Rectangle(llx, lly, urx, ury), dataGridView1.Rows[i].Cells[0].Value.ToString(), "Yes");
                        fCell.CheckType = RadioCheckField.TYPE_CROSS;
                        PdfFormField footerCheck = null;
                        footerCheck = fCell.CheckField;
                        stamp.AddAnnotation(footerCheck, x);
                    }
                    else
                    {
                    }
                }
                //Loop Ends here

                stamp.Close();
                fs.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 3
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            // Create a reader for the original document
            PdfReader reader = new PdfReader(src);
            // Create a reader for the advertisement resource
            PdfReader ad = new PdfReader(RESOURCE);

            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create the advertisement annotation for the menubar
                    Rectangle       rect   = new Rectangle(400, 772, 545, 792);
                    PushbuttonField button = new PushbuttonField(
                        stamper.Writer, rect, "click"
                        );
                    button.BackgroundColor = BaseColor.RED;
                    button.BorderColor     = BaseColor.RED;
                    button.FontSize        = 10;
                    button.Text            = "Close this advertisement";
                    button.Image           = Image.GetInstance(
                        Path.Combine(Utility.ResourceImage, IMAGE)
                        );
                    button.Layout = PushbuttonField.LAYOUT_LABEL_LEFT_ICON_RIGHT;
                    button.IconHorizontalAdjustment = 1;
                    PdfFormField menubar = button.Field;
                    String       js      = "var f1 = getField('click'); f1.display = display.hidden;"
                                           + "var f2 = getField('advertisement'); f2.display = display.hidden;"
                    ;
                    menubar.Action = PdfAction.JavaScript(js, stamper.Writer);
                    // Add the annotation
                    stamper.AddAnnotation(menubar, 1);
                    // Create the advertisement annotation for the content
                    rect   = new Rectangle(400, 550, 545, 772);
                    button = new PushbuttonField(
                        stamper.Writer, rect, "advertisement"
                        );
                    button.BackgroundColor = BaseColor.WHITE;
                    button.BorderColor     = BaseColor.RED;
                    button.Text            = "Buy the book iText in Action 2nd edition";
                    button.Template        = stamper.GetImportedPage(ad, 1);
                    button.Layout          = PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM;
                    PdfFormField advertisement = button.Field;
                    advertisement.Action = new PdfAction(
                        "http://www.1t3xt.com/docs/book.php"
                        );
                    // Add the annotation
                    stamper.AddAnnotation(advertisement, 1);
                }
                return(ms.ToArray());
            }
        }
Exemplo n.º 4
0
        // ---------------------------------------------------------------------------

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

            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create pushbutton 1
                    PushbuttonField saveAs = new PushbuttonField(
                        stamper.Writer,
                        new Rectangle(636, 10, 716, 30),
                        "Save"
                        );
                    saveAs.BorderColor = BaseColor.BLACK;
                    saveAs.Text        = "Save";
                    saveAs.TextColor   = BaseColor.RED;
                    saveAs.Layout      = PushbuttonField.LAYOUT_LABEL_ONLY;
                    saveAs.Rotation    = 90;
                    PdfAnnotation saveAsButton = saveAs.Field;
                    saveAsButton.Action = PdfAction.JavaScript(
                        "app.execMenuItem('SaveAs')", stamper.Writer
                        );
                    // Create pushbutton 2
                    PushbuttonField mail = new PushbuttonField(
                        stamper.Writer,
                        new Rectangle(736, 10, 816, 30),
                        "Mail"
                        );
                    mail.BorderColor = BaseColor.BLACK;
                    mail.Text        = "Mail";
                    mail.TextColor   = BaseColor.RED;
                    mail.Layout      = PushbuttonField.LAYOUT_LABEL_ONLY;
                    mail.Rotation    = 90;
                    PdfAnnotation mailButton = mail.Field;
                    mailButton.Action = PdfAction.JavaScript(
                        "app.execMenuItem('AcroSendMail:SendMail')",
                        stamper.Writer
                        );
                    // Add the annotations to every page of the document
                    for (int page = 1; page <= n; page++)
                    {
                        stamper.AddAnnotation(saveAsButton, page);
                        stamper.AddAnnotation(mailButton, page);
                    }
                }
                return(ms.ToArray());
            }
        }
Exemplo n.º 5
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.º 6
0
        /// <summary>
        /// Adding named (empty) signature field to PDF document soft way (using existing stamper)
        /// </summary>
        /// <param name="stamper">Existing stamper</param>
        /// <param name="fieldName">Name of field</param>
        /// <param name="x">X coordinate on the page</param>
        /// <param name="y">Y coordinate on the page</param>
        /// <param name="width">Field width</param>
        /// <param name="height">Field height</param>
        /// <param name="page">The page to place field</param>
        /// <param name="flags">PdfAnnotation flags</param>
        /// <returns>Field added successfully or not</returns>
        public static bool AddSignatureField(ref PdfStamper stamper,
                                             string fieldName,
                                             float x,
                                             float y,
                                             float width,
                                             float height,
                                             int page  = 1,
                                             int flags = PdfAnnotation.FLAGS_PRINT)
        {
            bool result = false;

            try
            {
                PdfFormField field = CreateField(stamper.Writer, fieldName, new iTextSharp.text.Rectangle(x, y, width, height), page, flags);
                stamper.AddAnnotation(field, page);

                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }

            return(result);
        }
        public void PutRectAnno(float lx, float ly, float rx, float ry)
        {
            using (FileStream fs = new FileStream(highLightFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(lx, ly, rx, ry);

                    float[] quad = { rect.Left, rect.Top, rect.Right, rect.Top, rect.Left, rect.Bottom, rect.Right, rect.Bottom };


                    PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);


                    highlight.Color = BaseColor.YELLOW;



                    if (rect.Width > 0 && rect.Height > 0)
                    {
                        stamper.AddAnnotation(highlight, 1);
                    }


                    stamper.Close();
                }
                fs.Close();
            }
        }
Exemplo n.º 8
0
// ---------------------------------------------------------------------------    
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public byte[] ManipulatePdf(byte[] src)  {
      // create a reader
      PdfReader reader = new PdfReader(src);
      using (MemoryStream ms = new MemoryStream()) {
        // create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Add an open action
          PdfWriter writer = stamper.Writer;
          PdfAction action = PdfAction.JavaScript(
            Utilities.ReadFileToString(
              Path.Combine(Utility.ResourceJavaScript, "post_from_html.js")
            ), 
            writer
          );
          writer.SetOpenAction(action);
          // create a submit button that posts data to the HTML page
          PushbuttonField button1 = new PushbuttonField(
            stamper.Writer, new Rectangle(90, 660, 160, 690), "post"
          );
          button1.Text = "POST TO HTML";
          button1.BackgroundColor = new GrayColor(0.7f);
          button1.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
          PdfFormField submit1 = button1.Field;
          submit1.Action = PdfAction.JavaScript(
            Utilities.ReadFileToString(Path.Combine(
              Utility.ResourceJavaScript, "post_to_html.js"
            )), 
            writer
          );
          // add the button
          stamper.AddAnnotation(submit1, 1);
        }
        return ms.ToArray();
      } 
    }  
Exemplo n.º 9
0
// ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public override 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 annotations for every screening
                    int           page = 1;
                    Rectangle     rect;
                    PdfAnnotation annotation;
                    foreach (string day in PojoFactory.GetDays())
                    {
                        foreach (Screening screening in PojoFactory.GetScreenings(day))
                        {
                            rect       = GetPosition(screening);
                            annotation = PdfAnnotation.CreateLink(
                                stamper.Writer, rect, PdfAnnotation.HIGHLIGHT_INVERT,
                                new PdfAction(string.Format(IMDB, screening.movie.Imdb))
                                );
                            stamper.AddAnnotation(annotation, page);
                        }
                        page++;
                    }
                }
                return(ms.ToArray());
            }
        }
        public string GeneratePdfForm(Loan loan, string inputFile, string xmlSettings, string scriptClassName, BaseColor color)
        {
            string templateFilename = inputFile;
            string outputFilename   = Environment.GetEnvironmentVariable("temp").ToString() + "\\" + Path.GetRandomFileName() + ".pdf";

            using (Stream inputPdf = new FileStream(templateFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream outputPdf = new FileStream(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader  = new PdfReader(inputPdf);
                    var stamper = new PdfStamper(reader, outputPdf)
                    {
                        FormFlattening = true
                    };

                    // Create a BaseFont representation of an internal font - Helvetica,
                    // using the Latin code page for Windows

                    iTextSharp.text.Font font = FontFactory.GetFont(@"c:\windows\fonts\timesi.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, .08f, iTextSharp.text.Font.ITALIC, BaseColor.RED);

                    BaseFont bsf = font.BaseFont;


                    var fieldData = getFieldData(scriptClassName, loan);

                    foreach (Plugin.Field lc in getFormFields(xmlSettings))
                    {
                        // This field will appear near the bottom left of the page (based on the Rectangle)

                        TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(lc.lx, lc.uy, lc.rx, lc.dy), lc.name);

                        tf.Text = fieldData.Get(lc.name);
                        tf.Font = bsf;

                        tf.Alignment = lc.align;
                        tf.Alignment = 6;

                        tf.TextColor = BaseColor.RED;

                        tf.SetExtraMargin(0f, 1.2f);

                        tf.Options = TextField.READ_ONLY;

                        // Add the TextField to the PDF on page 1
                        var pageNumber = 1;

                        stamper.FormFlattening = true;

                        stamper.AddAnnotation(tf.GetTextField(), pageNumber);
                    }

                    stamper.Close();
                    reader.Close();
                }
                // Save the changes to file
            }
            return(outputFilename);
        }
Exemplo n.º 11
0
        /// <summary>
        /// AppData contains the information needed to create a new PDF with overlayed information including name, description, website, and image.
        /// </summary>
        /// <param name="data">The data to use</param>
        static void addTextToPdf(AppData data)
        {
            using (PdfStamper stamper = new PdfStamper(new PdfReader(sourcePDF), File.Create(data.filename)))
            {
                // Create the header textbox
                TextField name = new TextField(stamper.Writer, new Rectangle(80, 932, 719, 1022), "Name");
                name.Text      = data.name;
                name.Alignment = Element.ALIGN_CENTER;

                // Get and set the image
                Image image;
                try
                {
                    image = Image.GetInstance(data.photo);
                } catch
                {
                    image = Image.GetInstance("../../files/default.png");
                }

                image.ScaleAbsolute(new Rectangle(80, 200, 721, 593));
                image.SetAbsolutePosition(79, 488);

                // Create the description textbox
                TextField description = new TextField(stamper.Writer, new Rectangle(80, 74, 719, 438), "Description");
                description.Options   = TextField.MULTILINE;
                description.Text      = data.description;
                description.Alignment = Element.ALIGN_CENTER;

                //calculate the font size
                float size = ColumnText.FitText(new Font(description.Font), data.description, new Rectangle(0, 0, 560, 365), 80, 0);
                description.FontSize = size;

                //Add the website URL if it exists
                TextField website = new TextField(stamper.Writer, new Rectangle(80, 30, 719, 60), "Website");
                website.Text      = data.website;
                website.Alignment = Element.ALIGN_CENTER;

                // Write and close
                stamper.AddAnnotation(name.GetTextField(), 1);
                stamper.GetOverContent(1).AddImage(image);
                stamper.AddAnnotation(description.GetTextField(), 1);
                stamper.AddAnnotation(website.GetTextField(), 1);
                stamper.Close();
            }
        }
Exemplo n.º 12
0
        public void HighLightText(String[] searchText)
        {
            //Create a new file from our test file with highlighting
            string highLightFile = Path.Combine(m_DirPath, "Highlighted.pdf");

            MyTextExtractionStrategy[,] arr_t = null;
            int Pages = 0;

            //Parse page 1 of the document above
            using (var r = new PdfReader(m_filename))
            {
                Pages = r.NumberOfPages;
                //Create an array of our strategy
                arr_t = new MyTextExtractionStrategy[r.NumberOfPages, searchText.Length];

                for (int i = 0; i < r.NumberOfPages; i++)
                {
                    for (int j = 0; j < searchText.Length; j++)
                    {
                        arr_t[i, j] = new MyTextExtractionStrategy(searchText[j], 1056f);
                        var ex = PdfTextExtractor.GetTextFromPage(r, i + 1, arr_t[i, j]);
                    }
                }
            }

            //Bind a reader and stamper to our test PDF
            PdfReader reader = new PdfReader(m_filename);

            using (FileStream fs = new FileStream(highLightFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    for (int i = 0; i < Pages; i++)
                    {
                        for (int j = 0; j < searchText.Length; j++)
                        {
                            var t = arr_t[i, j];
                            foreach (var p in t.m_SearchResultsList)
                            {
                                Rectangle rect = p.rect;
                                //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 highlight
                                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, i + 1);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 13
0
        public void CreatePdf(string path)
        {
            var reader = new PdfReader(path);
            var oot    = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            var stamp  = new PdfStamper(reader, oot);
            var field  = new TextField(stamp.Writer, new Rectangle(100, 100, 100, 100), "title");

            stamp.AddAnnotation(field.GetTextField(), 1);
            stamp.Close();
        }
Exemplo n.º 14
0
        public void AddWrongAnnotation(String src, String dest)
        {
            PdfReader     reader  = new PdfReader(src);
            PdfStamper    stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            PdfAnnotation comment = PdfAnnotation.CreateText(stamper.Writer,
                                                             new Rectangle(200, 800, 250, 820), "Finally Signed!",
                                                             "Bruno Specimen has finally signed the document", true, "Comment");

            stamper.AddAnnotation(comment, 1);
            stamper.Close();
        }
Exemplo n.º 15
0
        /*
         *
         * 以下4个方法都是用iTextSharp来实现,网上也有很多例子
         * 可以搜索学习
         *
         *
         */


        #region 给pdf文件重新添加文字内容
        private static bool AddText()
        {
            PdfReader reader = new PdfReader(@"E:\pdf\156281489401000002.pdf");

            FileStream out1 = new FileStream(@"E:\pdf\test.pdf", FileMode.Create, FileAccess.Write);

            PdfStamper stamp = new PdfStamper(reader, out1);

            try
            {
                //获得pdf总页数
                int count = reader.NumberOfPages;

                //设置文本域  iTextSharp.text.Rectangle(105, 100, 240, 125) 用来设置文本域的位置,四个参数分别为:llx、lly、urx、ury:
                //llx 为Left ,
                //lly 为Bottom,
                //urx 为Right,
                //ury 为Top       其中:Width = Right - Left     Heigth = Top - Bototom

                TextField fieldDate = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(460, 430, 540, 475), "date");
                fieldDate.BackgroundColor = BaseColor.WHITE;
                fieldDate.BorderWidth     = 1;
                fieldDate.BorderColor     = BaseColor.BLACK;
                fieldDate.BorderStyle     = 4;
                fieldDate.FontSize        = 11f;
                stamp.AddAnnotation(fieldDate.GetTextField(), 9);

                //创建文本
                Chunk  y_identity   = new Chunk("912365165354699654", FontFactory.GetFont("Futura", 11f, new BaseColor(0, 0, 0)));
                Chunk  y_phone      = new Chunk("96545632233", FontFactory.GetFont("Futura", 11f, new BaseColor(0, 0, 0)));
                Phrase p_y_identity = new Phrase(y_identity);
                Phrase p_y_phone    = new Phrase(y_phone);

                //PdfContentBye类,用来设置图像和文本的绝对位置
                PdfContentByte over = stamp.GetOverContent(2);
                ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER, p_y_identity, 240, 700, 0);
                ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER, p_y_phone, 210, 604, 0);

                stamp.FormFlattening = true;
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                stamp.Close();
                out1.Close();
                reader.Close();
            }
        }
Exemplo n.º 16
0
        public void ManipulatePdf(String src, String dest)
        {
            PdfReader      reader       = new PdfReader(src);
            PdfStamper     stamper      = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            Rectangle      linkLocation = new Rectangle(523, 770, 559, 806);
            PdfDestination destination  = new PdfDestination(PdfDestination.FIT);
            PdfAnnotation  link         = PdfAnnotation.CreateLink(stamper.Writer,
                                                                   linkLocation, PdfAnnotation.HIGHLIGHT_INVERT,
                                                                   3, destination);

            stamper.AddAnnotation(link, 1);
            stamper.Close();
        }
Exemplo n.º 17
0
        private static void AddFieldToPDF(PdfStamper pdfStamper)
        {
            TextField moreText = new TextField(pdfStamper.Writer,
                                               new iTextSharp.text.Rectangle(20, 20, 590, 780), "moreText");

            moreText.Visibility = TextField.VISIBLE_BUT_DOES_NOT_PRINT;
            moreText.Text       = "Use this space for any additional information";
            moreText.Options    = (TextField.MULTILINE);

            PdfFormField Fieldtxt = moreText.GetTextField();

            pdfStamper.AddAnnotation(Fieldtxt, 1);
        }
Exemplo n.º 18
0
// ---------------------------------------------------------------------------

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

            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    stamper.Writer.AddJavaScript(File.ReadAllText(RESOURCE));
                    AcroFields      form = stamper.AcroFields;
                    AcroFields.Item fd   = form.GetFieldItem("married");

                    PdfDictionary dictYes =
                        (PdfDictionary)PdfReader.GetPdfObject(fd.GetWidgetRef(0));
                    PdfDictionary yesAction = dictYes.GetAsDict(PdfName.AA);
                    if (yesAction == null)
                    {
                        yesAction = new PdfDictionary();
                    }
                    yesAction.Put(
                        new PdfName("Fo"),
                        PdfAction.JavaScript("ReadOnly = false);", stamper.Writer)
                        );
                    dictYes.Put(PdfName.AA, yesAction);

                    PdfDictionary dictNo =
                        (PdfDictionary)PdfReader.GetPdfObject(fd.GetWidgetRef(1));
                    PdfDictionary noAction = dictNo.GetAsDict(PdfName.AA);
                    if (noAction == null)
                    {
                        noAction = new PdfDictionary();
                    }
                    noAction.Put(
                        new PdfName("Fo"),
                        PdfAction.JavaScript("ReadOnly = true);", stamper.Writer)
                        );
                    dictNo.Put(PdfName.AA, noAction);

                    PdfWriter       writer = stamper.Writer;
                    PushbuttonField button = new PushbuttonField(
                        writer, new Rectangle(40, 690, 200, 710), "submit"
                        );
                    button.Text    = "validate and submit";
                    button.Options = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
                    PdfFormField validateAndSubmit = button.Field;
                    validateAndSubmit.Action = PdfAction.JavaScript(
                        "validate();", stamper.Writer
                        );
                    stamper.AddAnnotation(validateAndSubmit, 1);
                }
                return(ms.ToArray());
            }
        }
        public string GeneratePdfForm(Loan loan, string inputFile, string xmlSettings, string scriptClassName)
        {
            string templateFilename = inputFile;
            string outputFilename   = Environment.GetEnvironmentVariable("temp").ToString() + "\\" + Path.GetRandomFileName() + ".pdf";

            using (Stream inputPdf = new FileStream(templateFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream outputPdf = new FileStream(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader  = new PdfReader(inputPdf);
                    var stamper = new PdfStamper(reader, outputPdf)
                    {
                        FormFlattening = true
                    };

                    // Create a BaseFont representation of an internal font - Helvetica,
                    // using the Latin code page for Windows
                    var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);

                    var fieldData = getFieldData(scriptClassName, loan);

                    foreach (Plugin.Field lc in getFormFields(xmlSettings))
                    {
                        // This field will appear near the bottom left of the page (based on the Rectangle)
                        TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(lc.lx, lc.uy, lc.rx, lc.dy), lc.name)
                        {
                            Font = bf
                        };
                        tf.Alignment = lc.align;
                        tf.Alignment = 6;
                        tf.FontSize  = 8;
                        tf.SetExtraMargin(0f, 1.2f);
                        tf.Text    = fieldData.Get(lc.name);
                        tf.Options = TextField.READ_ONLY;
                        tf.GetAppearance();

                        // Add the TextField to the PDF on page 1
                        var pageNumber = 1;

                        stamper.FormFlattening = true;
                        stamper.AcroFields.GenerateAppearances = true;
                        stamper.AddAnnotation(tf.GetTextField(), pageNumber);
                    }

                    stamper.Close();
                    reader.Close();
                }
                // Save the changes to file
            }
            return(outputFilename);
        }
Exemplo n.º 20
0
        public void AddTextField(ItemRef input, Rectangle rect)
        {
            int fieldFlags = TextField.MULTILINE;

            drawingFuncs.Add(() =>
            {
                TextField tf = new TextField(Writer, rect, input.UniqueId)
                {
                    Alignment   = Element.ALIGN_LEFT | Element.ALIGN_TOP,
                    BorderColor = BaseColor.BLACK,
                    BorderStyle = PdfBorderDictionary.STYLE_SOLID,
                    Text        = input.DefaultValue
                };
                PdfFormField pf = tf.GetTextField();

                if (input.IsMandatory)
                {
                    fieldFlags = fieldFlags | PdfFormField.FF_REQUIRED;
                }
                pf.SetFieldFlags(fieldFlags);
                stamper.AddAnnotation(pf, 1);
            });
        }
Exemplo n.º 21
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);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// METODO 3: Sostituire un acrofield di tipo signature con un acrofield di tipo checkbox
        /// Locking for a checkbox and checking it
        /// </summary>
        /// <param name="fieldName">string Name of the signaturefield to substitute</param>
        public void SubstituteSignature(string fieldName)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException(fieldName);
            }

            //Getting fields
            AcroFields form = reader.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a signatureBox with the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_SIGNATURE
                                )
                         .Select(kvp => new { kvp.Key, Position = form.GetFieldPositions(kvp.Key) })
                         ?.FirstOrDefault();

            //Checking if the query had results
            if (result == null)
            {
                throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_SIGNATURE);
            }

            //Removing field
            form.RemoveField(result.Key);

            //Creating new checkbox with signaturefield's coordinates
            //Note: We're replacing the first occurrence
            RadioCheckField checkbox = new RadioCheckField(stamper.Writer, result.Position[0].position, "i_was_a_signature_field", "Yes")
            {
                //Setting look
                CheckType       = RadioCheckField.TYPE_CHECK,
                Checked         = true,
                BorderWidth     = BaseField.BORDER_WIDTH_THIN,
                BorderColor     = BaseColor.BLACK,
                BackgroundColor = BaseColor.WHITE
            };

            //Adding checbox in signaturefield's page
            stamper.AddAnnotation(checkbox.CheckField, result.Position[0].page);
        }
Exemplo n.º 23
0
// ---------------------------------------------------------------------------

        /**
         * Show keys and values passed to the query string with GET
         */
        protected void DoGet(byte[] pdf, Stream stream)
        {
            // We get a resource from our web app
            PdfReader reader = new PdfReader(pdf);

            // Now we create the PDF
            using (PdfStamper stamper = new PdfStamper(reader, stream)) {
                // We add a submit button to the existing form
                PushbuttonField button = new PushbuttonField(
                    stamper.Writer, new Rectangle(90, 660, 140, 690), "submit"
                    );
                button.Text            = "POST";
                button.BackgroundColor = new GrayColor(0.7f);
                button.Visibility      = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
                PdfFormField submit = button.Field;
                submit.Action = PdfAction.CreateSubmitForm(
                    WebContext.Request.RawUrl, null, 0
                    );
                stamper.AddAnnotation(submit, 1);
                // We add an extra field that can be used to upload a file
                TextField file = new TextField(
                    stamper.Writer, new Rectangle(160, 660, 470, 690), "image"
                    );
                file.Options         = TextField.FILE_SELECTION;
                file.BackgroundColor = new GrayColor(0.9f);
                PdfFormField upload = file.GetTextField();
                upload.SetAdditionalActions(PdfName.U,
                                            PdfAction.JavaScript(
                                                "this.getField('image').browseForFileToSubmit();"
                                                + "this.getField('submit').setFocus();",
                                                stamper.Writer
                                                )
                                            );
                stamper.AddAnnotation(upload, 1);
            }
        }
 private void CreateSignatureField(PdfReader reader, PdfStamper stamper, string signingBlock)
 {
     if (signingBlock == null)
     {
         return;
     }
     if (!DoesSignatureFieldExist(reader, signingBlock))
     {
         PdfFormField signatureField = PdfFormField.CreateSignature(stamper.Writer);
         signatureField.SetWidget(new Rectangle(100, 100, 200, 200), null);
         signatureField.Flags     = PdfAnnotation.FLAGS_PRINT;
         signatureField.FieldName = signingBlock;
         signatureField.Page      = 1;
         stamper.AddAnnotation(signatureField, 1);
     }
 }
Exemplo n.º 25
0
        public void AddField(String src, String dest)
        {
            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            // create a signature form field
            PdfFormField field = PdfFormField.CreateSignature(stamper.Writer);

            field.FieldName = SIGNAME;
            // set the widget properties
            field.SetWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_OUTLINE);
            field.Flags = PdfAnnotation.FLAGS_PRINT;
            // add the annotation
            stamper.AddAnnotation(field, 1);
            // close the stamper
            stamper.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);
            }
        }
         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();
         }
        // 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();
        }
Exemplo n.º 29
0
        private bool CreteTextField(string fieldName, float x, float y, float width, string fieldText, PdfStamper stamper)
        {
            var          baseFont  = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfFormField field     = PdfFormField.CreateTextField(stamper.Writer, false, false, 50);
            TextField    textField = new TextField(stamper.Writer, new Rectangle(x, y, x + width, y + 10), fieldName);

            textField.Text     = fieldText;
            textField.FontSize = 8;
            textField.Font     = baseFont;
            //field.SetWidget(new Rectangle(x, y - 10, x + width, y), PdfAnnotation.HIGHLIGHT_INVERT);
            //field.Flags = PdfAnnotation.FLAGS_PRINT;
            //field.RichValue = fieldText;
            //field.FieldName = fieldName;

            stamper.AddAnnotation(textField.GetTextField(), 1);

            return(true);
        }
        /// <summary>
        /// Adds a blank signature field at the specified location.
        /// </summary>
        /// <param name="pdf">The PDF.</param>
        /// <param name="signatureRect">The signature location.</param>
        /// <param name="signaturePage">the page on which the signature appears</param>
        /// <returns>The new PDF.</returns>
        private static byte[] AddBlankSignatureField(byte[] pdf, Rectangle signatureRect, int signaturePage)
        {
            var pdfReader = new PdfReader(pdf);

            using (var ms = new MemoryStream())
            {
                var pdfStamper     = new PdfStamper(pdfReader, ms);
                var signatureField = PdfFormField.CreateSignature(pdfStamper.Writer);
                signatureField.SetWidget(signatureRect, null);
                signatureField.Flags = PdfAnnotation.FLAGS_PRINT;
                signatureField.Put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"));
                signatureField.FieldName = "ClientSignature";
                signatureField.Page      = signaturePage;
                pdfStamper.AddAnnotation(signatureField, signaturePage);
                pdfStamper.Close();
                return(ms.ToArray());
            }
        }