private void goButton_Click(object sender, EventArgs e)
        {
            //TestPDF();  //find out whether acroform will work correctly

            //open file
            PdfDocument pdf = PdfReader.Open(@"YOURFILEPATHandNAME", PdfDocumentOpenMode.Modify);

            //fix some odd setting where filled fields don't always show                   SetupPDF(pdf);

            //find and fill fields
            PdfTextField txtEmployerName = (PdfTextField)(pdf.AcroForm.Fields["txtEmployerName"]);

            txtEmployerName.Value = new PdfString("My Name");

            PdfTextField txtEmployeeTitle = (PdfTextField)(pdf.AcroForm.Fields["txtEmployeeTitle"]);

            txtEmployeeTitle.Value = new PdfString("Bossin'");

            PdfCheckBoxField chxAttached = (PdfCheckBoxField)(pdf.AcroForm.Fields["chxAttached"]);

            chxAttached.Checked = true;

            //save file
            pdf.Save(@"NEWFILEPATHandNAMEHERE");
        }
Beispiel #2
0
        public void RenderAppearance_Empty()
        {
            PdfDocument testDoc = new PdfDocument();

            PdfTextField tf = new PdfTextField(testDoc);

            tf.Rectangle = new PdfRectangle(new XRect(0, 0, 200, 20));

            PdfPage p1 = testDoc.Pages.Add();

            testDoc.Catalog.AcroForm = new PdfAcroForm(testDoc);
            testDoc.AcroForm.Elements.SetValue(PdfAcroForm.Keys.Fields, new PdfAcroField.PdfAcroFieldCollection(new PdfArray(testDoc)));
            testDoc.AcroForm.Fields.Add(tf, 1);

            tf.Text = "Some Test Text";
            tf.PrepareForSave();

            Assert.IsTrue(tf.Elements.ContainsKey(PdfAnnotation.Keys.AP), "Text Field should have rendered an appearance stream.");

            tf.Text = string.Empty;

            tf.PrepareForSave();

            Assert.IsFalse(tf.Elements.ContainsKey(PdfAnnotation.Keys.AP), "Empty Text Field should NOT have an appearance stream.");
        }
 private void changeFont(PdfTextField textfield, int size)
 {
     if (textfield.Elements.ContainsKey("/DA") == false)
     {
         textfield.Elements.Add("/DA", new PdfString("/CoBo " + size + " Tf 0 g"));
     }
     else
     {
         textfield.Elements["/DA"] = new PdfString("/CoBo " + size + " Tf 0 g");
     }
 }
Beispiel #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Get PDF as byte array from file (or database, browser upload, remote storage, etc)
            byte[] pdfData = System.IO.File.ReadAllBytes(Server.MapPath(@"pdfs/RadPdfSampleForm.pdf"));

            //Load PDF byte array into RAD PDF
            this.PdfWebControl1.CreateDocument("Document Name", pdfData);

            //Create DocumentEditor object
            PdfDocumentEditor DocumentEditor1 =
                this.PdfWebControl1.EditDocument();

            //Fill out PDF field using field names
            ((PdfTextField)
             DocumentEditor1.Fields.Find("First Name"))
            .Value = "John";
            ((PdfTextField)
             DocumentEditor1.Fields.Find("Last Name"))
            .Value = "Smith";
            ((PdfCheckField)
             DocumentEditor1.Fields.Find("Product Support"))
            .Checked = true;

            //Add arrow object
            PdfArrowShape a =
                (PdfArrowShape)
                DocumentEditor1.Pages[0].CreateObject(PdfObjectCreatable.ShapeArrow);
            a.LineColor = new PdfColor(Color.Blue);
            a.LineWidth = 2;
            a.SetLine(200, 220, 40, 160);
            a.Moveable  = false;
            a.Resizable = false;
            a.Stylable  = false;
            a.Deletable = false;

            //Add text form field object
            PdfTextField f =
                (PdfTextField)
                DocumentEditor1.Pages[0].CreateObject(PdfObjectCreatable.FormFieldText);
            f.Resizable = false;
            f.Stylable  = false;
            f.Deletable = false;

            //Commit DocumentEditor changes
            DocumentEditor1.Save();
        }
    }
Beispiel #5
0
        static void Main(string[] args)
        {
            var path = @"C:\Templates_POC\template.pdf";

            var doc = PdfReader.Open(path, PdfDocumentOpenMode.Modify);

            if (doc.AcroForm == null)
            {
                Console.WriteLine("Error, PDF Form Not Found!");
                return;
            }

            PdfAcroForm form = doc.AcroForm;

            if (form.Elements.ContainsKey("/NeedAppearances"))
            {
                form.Elements["/NeedAppearances"] = new PdfBoolean(true);
            }
            else
            {
                form.Elements.Add("/NeedAppearances", new PdfBoolean(true));
            }

            //Create fields
            PdfTextField     merchantPorfileOwnerField = (PdfTextField)(form.Fields["merchant_profile_owners_email_2"]);
            PdfCheckBoxField checkField = (PdfCheckBoxField)(form.Fields["seasson_Mar"]);

            merchantPorfileOwnerField.ReadOnly = false;
            checkField.ReadOnly             = false;
            checkField.Checked              = true;
            merchantPorfileOwnerField.Value = new PdfString("TEST ON C#");

            doc.Save(@"C:\Templates_POC\newcopy.pdf");

            Console.WriteLine("Hello World! " + merchantPorfileOwnerField.Text);
        }
Beispiel #6
0
        private static void FillPDF(Dictionary <string, string> submittedFields, PdfDocument PDFDocument)
        {
            if (PDFDocument == null || PDFDocument.AcroForm == null)
            {
                throw new Exception("No PDF with fillable form submitted");
            }

            PdfAcroForm af = PDFDocument.AcroForm;


            //make sure fields are enabled
            if (af.Elements.ContainsKey(PdfAcroForm.Keys.NeedAppearances))
            {
                af.Elements[PdfAcroForm.Keys.NeedAppearances] = new PdfSharp.Pdf.PdfBoolean(true);
            }
            else
            {
                af.Elements.Add(PdfAcroForm.Keys.NeedAppearances, new PdfSharp.Pdf.PdfBoolean(true));
            }


            //Turn on unicode support
            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode);

            //foreach (PDFField sField in submittedFields)
            foreach (KeyValuePair <string, string> sField in submittedFields)
            {
                try {
                    var field = af.Fields[sField.Key];
                    if (field is PdfTextField && (!sField.Key.EndsWith("_QRFill") && !sField.Key.EndsWith("_Code39Fill") && !sField.Key.EndsWith("_PDF417Fill")))
                    {
                        // filling in a text field
                        PdfTextField tf = (PdfTextField)field;

                        tf.ReadOnly = false;
                        if (Helper.IsChinese(sField.Value)) //override font if chinese is detected.
                        {
                            if (true)                       // remove evenatully - was used for switching different rendering methods
                            {
                                //Note: This will work for text Fields.. but make sure they are not linked (ie. multiple fileds with same name)
                                // If you want to make this more generic for all form fields you need to account for the possilbility
                                // that a form field could have several phyical outputs across multiple pages.  You can find the same
                                // properties but you need to check the KIDS collection for the field.  When there is only one display
                                // for a form field then the properties are rolled up to the form field itself - so the below works.
                                PdfRectangle rect = field.Elements.GetRectangle("/Rect");

                                if (tf.HasKids)
                                {
                                    throw new Exception("Multiple render locations found for text field" + sField.Key + ".  This can be supported, or just create separate fields for now.");
                                }

                                tf.Value = new PdfSharp.Pdf.PdfString(sField.Value, PdfStringEncoding.Unicode);

                                //also a bit of pain to locate the acutaly page the field is on... but OK.
                                XGraphics gfx = null;
                                foreach (var page in PDFDocument.Pages)
                                {
                                    if (page.Reference == field.Elements["/P"])
                                    {
                                        if (gfx != null)   //dispose of object before getting a new one.  Should actually never happen... but better safe than sorry....
                                        {
                                            gfx.Dispose();
                                        }
                                        gfx = XGraphics.FromPdfPage(page);
                                        break;
                                    }
                                }


                                XFont targetFont = new XFont("MicrosoftJhengHei", tf.Font.Size, XFontStyle.Regular, options);   //It's "KaigenSansSC" behind the scenes, but this may help with some rendering....
                                // Draw the text over the field
                                gfx.DrawString(sField.Value, targetFont, XBrushes.Black, new XRect(Math.Min(rect.X1, rect.X2), gfx.PageSize.Height - Math.Min(rect.Y1, rect.Y2) - Math.Abs(rect.Height), Math.Abs(rect.Width), Math.Abs(rect.Height)), XStringFormats.TopLeft);
                                gfx.Dispose();

                                //Theb hide the field
                                if (tf.Elements.ContainsKey("/F") == true)
                                {
                                    tf.Elements.SetInteger("/F", 6);
                                }


                                //original filling routine.. still kept here for refernce ... and since it will allow extracting form values from the PDF later.
                                tf.Font = targetFont;   // this is and the below is necessary to set both the view and edit font of the field.

                                if (tf.Elements.ContainsKey("/DA") == false)
                                {
                                    tf.Elements.Add(PdfTextField.Keys.DA, new PdfString($"/{targetFont.Name} {targetFont.Size} Tf 0 g"));
                                }
                                else
                                {
                                    tf.Elements[PdfTextField.Keys.DA] = new PdfString($"/{targetFont.Name} {targetFont.Size} Tf 0 g");
                                }
                            }
                        }
                        tf.Value = new PdfSharp.Pdf.PdfString(sField.Value, PdfStringEncoding.Unicode);
                    }
                    else if (field is PdfCheckBoxField)
                    {
                        if (sField.Value != null && sField.Value.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase))
                        {
                            ((PdfCheckBoxField)field).Checked = true;
                        }
                        else
                        {
                            ((PdfCheckBoxField)field).Checked = false;
                        }
                    }
                    else if (field is PdfComboBoxField)
                    {
                        ((PdfComboBoxField)field).Value = new PdfString(sField.Value);
                    }
                    else if (field is PdfRadioButtonField)
                    {
                        ((PdfRadioButtonField)field).Value = new PdfName(sField.Value);
                    }
                    else if (field is PdfListBoxField)
                    {
                        string[] items = sField.Value.Split(",");
                        //PdfSharp.Pdf.PdfArray paNew = new PdfSharp.Pdf.PdfArray();
                        PdfArray pas = (PdfArray)(((PdfListBoxField)field).Value);
                        //PdfItem[] pis = pas.Elements.Items;
                        pas.Elements.Clear();
                        foreach (string sitem in items)

                        {
                            pas.Elements.Add(new PdfString(sitem));
                        }


                        //PdfListBoxField pl = (PdfListBoxField)field;
                        //PdfSharp.Pdf.PdfArray pa = (PdfSharp.Pdf.PdfArray)pl.Value;
                        //string values = "";
                        //foreach (PdfString pi in pa.Elements.Items)
                        //{
                        //    if (values.Length > 0) values += ", ";
                        //    values += pi.Value;
                        //}
                        //dictPDFFields.Add(key, values);
                    }
                    else if (field is PdfSignatureField)
                    {
                        if (sField.Value == "")
                        {
                            continue;
                        }

                        //Note: The below wroks because a named singature fields only appear once in a document.
                        // If you want to make this more generic for all form fields you need to account for the possilbility
                        // that a form field could have several phyical outputs across multiple pages.  You can find the same
                        // properties but you need to check the KIDS collection for the field.  When there is only one display
                        // for a form field then the properties are rolled up to the form field itself - so the below works.
                        PdfSignatureField sig = (PdfSignatureField)field;
                        OverlayImageOnField(PDFDocument, sField.Value, sig.Elements.GetRectangle("/Rect"), sig.Elements["/P"]);
                    }
                    else if (field is PdfTextField && (sField.Key.EndsWith("_QRFill") || sField.Key.EndsWith("_Code39Fill") || sField.Key.EndsWith("_PDF417Fill")))
                    {
                        if (sField.Value == "")
                        {
                            continue;
                        }

                        //Note: This will work for text Fields.. but make sure they are not linked (ie. multiple fileds with same name)
                        // If you want to make this more generic for all form fields you need to account for the possilbility
                        // that a form field could have several phyical outputs across multiple pages.  You can find the same
                        // properties but you need to check the KIDS collection for the field.  When there is only one display
                        // for a form field then the properties are rolled up to the form field itself - so the below works.
                        PdfRectangle rect = field.Elements.GetRectangle("/Rect");

                        PdfTextField tf = (PdfTextField)field;

                        if (tf.HasKids)
                        {
                            throw new Exception("Multiple render locations found on barcode fill.  This can be supported, or just create separate fields for now.");
                        }

                        tf.Value = new PdfSharp.Pdf.PdfString(sField.Value, PdfStringEncoding.Unicode);

                        //This hides the field
                        if (tf.Elements.ContainsKey("/F") == true)
                        {
                            tf.Elements.SetInteger("/F", 6);
                        }

                        MessagingToolkit.Barcode.BarcodeEncoder benc = new BarcodeEncoder();
                        benc.Width  = Convert.ToInt32((rect.X2 - rect.X1) * 5); //I just made up that rule - but seems to work well for laser printers.
                        benc.Height = Convert.ToInt32((rect.Y2 - rect.Y1) * 5);

                        if (sField.Key.EndsWith("_Code39Fill"))
                        {
                            benc.Encode(BarcodeFormat.Code39, sField.Value);
                        }
                        else if (sField.Key.EndsWith("_PDF417Fill"))
                        {
                            benc.Encode(BarcodeFormat.PDF417, sField.Value);
                        }
                        else                                                                                            //_QRFill
                        {
                            benc.ErrorCorrectionLevel = MessagingToolkit.Barcode.QRCode.Decoder.ErrorCorrectionLevel.M; //M=15%  H=25% L=7% (default)
                            benc.Encode(BarcodeFormat.QRCode, sField.Value);
                        }

                        byte[] qrCodeAsPngByteArr = benc.GetImageData(SaveOptions.Png);
                        OverlayImageOnField(PDFDocument, qrCodeAsPngByteArr, rect, field.Elements["/P"]);
                    }
                } catch (Exception e) {
                    throw new Exception("Fill of Field '" + sField.Key + "' ('" + sField.Value + "') failed.  " + e.Message);
                }
            }
        }
 private static CompositeProperty asCompositeProperty(PdfTextField o)
 {
     return(new CompositeProperty(o.Name, typeof(string)));
 }