Esempio n. 1
0
        /// <summary>
        /// To set the value of the PDF Form field
        /// </summary>
        /// <param name="pdfFormFields">AcroFields</param>
        /// <param name="ctrlname">string</param>
        /// <param name="ctrlvalue">string</param>
        /// <param name="ischeckbox">bool</param>
        /// <param name="istextbox">bool</param>
        /// <param name="minLength">int</param>
        /// <param name="maxLength">int</param>
        public static void GenericClass(AcroFields pdfFormFields, string ctrlname, string ctrlvalue, bool ischeckbox, bool istextbox, int minLength, int maxLength)
        {
            if (ischeckbox == true)
            {
                pdfFormFields.SetField(ctrlname, ctrlvalue);
            }
            if (istextbox == true)
            {
                pdfFormFields.SetField(ctrlname, ctrlvalue);
            }
            else
            {
                if (ctrlvalue.Length != 0)
                {
                    int j = 0;
                    for (int i = minLength; i <= maxLength; i++)
                    {
                        if (j <= ctrlvalue.Length - 1 && pdfFormFields.GetField(i.ToString()) != null)
                        {
                            pdfFormFields.SetField(i.ToString(), ctrlvalue[j].ToString());

                            j++;
                        }
                    }
                }
            }
        }
Esempio n. 2
0
        private static void SetWeapons(ICharacter character, AcroFields form)
        {
            var n = 1;

            foreach (var weapon in character.Weapons.Take(3))
            {
                form.SetField($"Wpn{n} Name", weapon.Name);
                var statSearch = StatSearch(weapon);

                var attack = character.Abilities.FirstOrDefault(x => x.Name == statSearch)?.Bonus + weapon.AttackBonus;

                if (weapon.Prof)
                {
                    if (int.TryParse(character.Properities?.FirstOrDefault(x => x.Name == "ProfBonus")?.Value, out var intOut))
                    {
                        attack += intOut;
                    }
                }
                form.SetField($"Wpn{n} AtkBonus", $"{attack}");

                var damageString = string.Empty;
                foreach (var damage in weapon.Damages)
                {
                    damageString  = string.IsNullOrWhiteSpace(damageString) ? "" : damageString + " & ";
                    damageString +=
                        $"{damage.Dice} + {character.Abilities.FirstOrDefault(x => x.Name == (damage.Stat == "base" ? StatSearch(weapon) : damage.Stat))?.Bonus + int.Parse(damage.Bonus)} {damage.Type}";
                }
                form.SetField($"Wpn{n} Damage", damageString);
                n++;
            }
        }
        private void LlenarFormulario()
        {
            string pdfTemplate = @"\Sistemas-Hisotrias\Resources\formulario.pdf";
            string newFile     = @"\Sistemas-Hisotrias\Resources\formulariolleno.pdf";

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

            AcroFields pdfFormFields = pdfStamper.AcroFields;

            // Asigna los campos

            pdfFormFields.SetField("fecha", "df");
            pdfFormFields.SetField("hora", "lklk");
            pdfFormFields.SetField("c3", "dato 3");
            pdfFormFields.SetField("c4", "dato 4");

            string sTmp = "Datos asignados";

            MessageBox.Show(sTmp, "Terminado");

            // Cambia la propiedad para que no se pueda editar el PDF
            pdfStamper.FormFlattening = true;

            // Cierra el PDF
            pdfStamper.Close();
        }
Esempio n. 4
0
// ---------------------------------------------------------------------------
        public byte[] FillTemplate(byte[] pdf, Movie movie)
        {
            using (MemoryStream ms = new MemoryStream()) {
                PdfReader reader = new PdfReader(pdf);
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    AcroFields form  = stamper.AcroFields;
                    BaseColor  color = WebColors.GetRGBColor(
                        "#" + movie.entry.category.color
                        );
                    PushbuttonField bt = form.GetNewPushbuttonFromField(POSTER);
                    bt.Layout           = PushbuttonField.LAYOUT_ICON_ONLY;
                    bt.ProportionalIcon = true;
                    bt.Image            = Image.GetInstance(Path.Combine(IMAGE, movie.Imdb + ".jpg"));
                    bt.BackgroundColor  = color;
                    form.ReplacePushbuttonField(POSTER, bt.Field);

                    PdfContentByte           canvas = stamper.GetOverContent(1);
                    float                    size   = 12;
                    AcroFields.FieldPosition f      = form.GetFieldPositions(TEXT)[0];
                    while (AddParagraph(CreateMovieParagraph(movie, size),
                                        canvas, f, true) && size > 6)
                    {
                        size -= 0.2f;
                    }
                    AddParagraph(CreateMovieParagraph(movie, size), canvas, f, false);

                    form.SetField(YEAR, movie.Year.ToString());
                    form.SetFieldProperty(YEAR, "bgcolor", color, null);
                    form.SetField(YEAR, movie.Year.ToString());
                    stamper.FormFlattening = true;
                }
                return(ms.ToArray());
            }
        }
Esempio n. 5
0
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                string    filename  = string.Concat(Guid.NewGuid().ToString(), ".pdf");
                PdfReader pdfReader = new PdfReader(Server.MapPath("~/Artifacts/Members/Cert.pdf"));

                using (MemoryStream stream = new MemoryStream())
                {
                    PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);

                    AcroFields formFields = pdfStamper.AcroFields;
                    formFields.SetField("txtForename", "Rajesh"); // txtForename.Text.Trim());
                    formFields.SetField("txtSurname", "Dube");    // txtSurname.Text.Trim());

                    pdfStamper.FormFlattening     = true;
                    pdfStamper.Writer.CloseStream = false;
                    pdfStamper.Close();

                    Response.ContentType = "application/pdf";
                    Response.AddHeader("Content-disposition", string.Format("attachment; filename={0};", filename));
                    stream.WriteTo(Response.OutputStream);
                }
            }
            catch (Exception ex)
            {
                //lblMessage.Text = ex.Message;
            }
        }
Esempio n. 6
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)) {
                    AcroFields form = stamper.AcroFields;
                    form.SetField("choice_1", "NL");
                    form.SetListSelection("choice_2", new String[] { "German", "Spanish" });
                    String[] languages        = form.GetListOptionDisplay("choice_3");
                    String[] exportvalues     = form.GetListOptionExport("choice_3");
                    int      n                = languages.Length;
                    String[] new_languages    = new String[n + 2];
                    String[] new_exportvalues = new String[n + 2];
                    for (int i = 0; i < n; i++)
                    {
                        new_languages[i]    = languages[i];
                        new_exportvalues[i] = exportvalues[i];
                    }
                    new_languages[n]        = "Chinese";
                    new_exportvalues[n]     = "CN";
                    new_languages[n + 1]    = "Japanese";
                    new_exportvalues[n + 1] = "JP";
                    form.SetListOption("choice_3", new_exportvalues, new_languages);
                    form.SetField("choice_3", "CN");
                    form.SetField("choice_4", "Japanese");
                }
                return(ms.ToArray());
            }
        }
Esempio n. 7
0
        public static void memorystream()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                PdfReader  pdfReader  = new PdfReader(templateFile, null);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);

                AcroFields pdfFormFields = pdfStamper.AcroFields;
                pdfFormFields.AddSubstitutionFont(BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));

                pdfFormFields.SetField("Radio Button1", "1");
                pdfFormFields.SetField("Check Box101", "是");
                pdfFormFields.SetField("Currency", "是");
                //String[] values = pdfFormFields.GetAppearanceStates("Check Box101");
                //foreach (String value in values) {
                //	Console.WriteLine("values=" + value);
                //}
                pdfFormFields.SetField("Text21", "()聖島國際專利商標聯合事務所");
                pdfFormFields.SetField("Text74", "台北市松山區南京東路三段248號11樓之1");

                //pdfStamper.Writer.CloseStream = false;
                //pdfStamper.FormFlattening = true;//平面化
                pdfStamper.Close();
                pdfReader.Close();

                System.IO.File.WriteAllBytes(outputFile, ms.ToArray());
            }
        }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int courseId     = int.Parse(Request.QueryString["cid"]);
            int assignmentId = int.Parse(Request.QueryString["aid"]);

            //'--------------------------------------------------------
            //'Get Database info to display in PDF
            //'--------------------------------------------------------
            lms_Entities            db      = new ClientDBEntities();
            Course_BasicInfo_Result basInfo = db.Course_BasicInfo(assignmentId, courseId, LmsUser.UserId).FirstOrDefault();

            //'--------------------------------------------------------
            //'Fill out PDF and send to client browser
            //'--------------------------------------------------------
            PdfReader  pdf = new PdfReader(Server.MapPath("certificate.pdf"));
            PdfStamper ps  = new PdfStamper(pdf, Response.OutputStream);

            ps.FormFlattening    = true;
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment; filename=certificate.pdf");
            AcroFields af = ps.AcroFields;

            if (basInfo.completedDate != null)
            {
                af.SetField("CourseName", basInfo.title);
                af.SetField("StudentName", LmsUser.Firstname + " " + LmsUser.Lastname);
                af.SetField("CertificateDate", ((DateTime)basInfo.completedDate).ToLongDateString());
                af.SetField("companyName", LmsUser.CompanyName);
            }
            ps.Close();
        }
Esempio n. 9
0
 //Methode: Zum Erstellen der internen Begründung als PDF
 public void CreateReasonPdf()
 {
     //Laden der PDF-Vorlage in ein ByteArray. "Vorlagenordner" gibt die Bibliothek an und "vorlage" gibt den zu Namen der zu ladenden Datei an.
     reasonPdf = web.Folders[templateFolder].Files[templateReason].OpenBinary();
     //Initialisieren eines PDF-Readers von itextsharp (zum Lesen)
     using (PdfReader pdfReader = new PdfReader(reasonPdf))
     {
         using (MemoryStream memoryStream = new MemoryStream())
         {
             using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream, '\0', true))
             {
                 //Mit pdfstamper.AcroFields werden alle Formularfelder des PDFs geladen
                 AcroFields formFields = pdfStamper.AcroFields;
                 //Eintragen der Auftragsnummer und der Begründung in entsprechende Formularfelder (Syntax: fields.SetField(<Name des PDF-Feldes>, <string>);)
                 formFields.SetField(fieldReasonOrderNumber, orderNumber);
                 formFields.SetField(fieldReasonReason, root.SelectSingleNode(xReason, nsmgr).Value.ToString());
                 //Stellen der Felder auf Schreibgeschützt
                 formFields.SetFieldProperty(fieldReasonOrderNumber, "setfflags", PdfFormField.FF_READ_ONLY, null);
                 formFields.SetFieldProperty(fieldReasonReason, "setfflags", PdfFormField.FF_READ_ONLY, null);
             }
             //Bis zu dieser Stelle sind alle Editierungen des PDFS nur in einem MemoryStream vorhanden. Durch "ToArray()" wird dieser MemoryStream in ein ByteArray umgewandelt.
             reasonPdf = memoryStream.ToArray();
         }
     }
 }
Esempio n. 10
0
    private static decimal PopulateFeeRow(int counter, AcroFields pdfFormFields, string name, decimal price, decimal priceEB, int feecount, bool isearlybird, string priceoverride)
    {
        string fieldsno  = "no" + counter.ToString();
        string fieldname = "des" + counter.ToString();
        //string fieldqty = "qty" + counter.ToString();
        //string fieldunit = "unit" + counter.ToString();
        string fieldtotal = "amt" + counter.ToString();

        pdfFormFields.SetField(fieldsno, counter.ToString());
        pdfFormFields.SetField(fieldname, GeneralFunction.ConvertHTMLBreaksToBreaks(name));
        //pdfFormFields.SetField(fieldqty, feecount.ToString());
        //pdfFormFields.SetField(fieldunit, "S$ " + price.ToString("N"));
        //if (isearlybird) pdfFormFields.SetField(fieldunit, "S$ " + priceEB.ToString("N"));
        decimal feetotal = feecount * price;

        if (isearlybird)
        {
            feetotal = feecount * priceEB;
        }
        pdfFormFields.SetField(fieldtotal, "S$ " + feetotal.ToString("N"));

        if (priceoverride.Trim() != "")
        {
            pdfFormFields.SetField(fieldtotal, priceoverride);
            return(0); // return 0 because its paid or complimentary
        }


        return(feetotal);
    }
Esempio n. 11
0
        //Using PDF Template for Certificate
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                string    filename  = string.Concat(Guid.NewGuid().ToString(), ".pdf");
                PdfReader pdfReader = new PdfReader(Server.MapPath("~/Artifacts/Members/Cert.pdf"));

                using (FileStream stream = new FileStream(string.Concat(Server.MapPath("~/export/"), filename), FileMode.Create))
                {
                    PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);

                    AcroFields formFields = pdfStamper.AcroFields;
                    formFields.SetField("txtForename", "Shivmani"); //txtForename.Text.Trim());
                    formFields.SetField("txtSurname", "Tripathi");  // txtSurname.Text.Trim());

                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();

                    string script = string.Format("window.open('{0}');", string.Concat("/export/", filename));
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "newPDF", script, true);
                }
            }
            catch (Exception ex)
            {
                //lblMessage.Text = ex.Message;
            }
        }
        public Stream FillForm(Stream inputStream, PDFSampleForm model)
        {
            Stream     outStream  = new MemoryStream();
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;
            Stream     inStream   = null;

            try
            {
                pdfReader  = new PdfReader(inputStream);
                pdfStamper = new PdfStamper(pdfReader, outStream);
                AcroFields form = pdfStamper.AcroFields;
                form.SetField(SampleFormFieldNames.FirstName, model.FirstName);
                form.SetField(SampleFormFieldNames.LastName, model.LastName);
                form.SetField(SampleFormFieldNames.IAmAwesomeCheck, model.AwesomeCheck ? "Yes" : "Off");
                // set this if you want the result PDF to be uneditable.
                pdfStamper.FormFlattening = true;
                return(outStream);
            }
            finally
            {
                pdfStamper?.Close();
                pdfReader?.Close();
                inStream?.Close();
            }
        }
Esempio n. 13
0
        private void StampTotalProfitMargin(AcroFields pdfFormFields)
        {
            //BUDGET
            var budgetIncome = SumSection("BUDGET", new List <string> {
                "Salgsinntekter"
            });
            var budgetCosts = SumSection("BUDGET", new List <string> {
                "Varekjøp"
            });

            pdfFormFields.SetField("BUDSJETTTotalt", String.Format("{0:0.00}", ((budgetIncome - budgetCosts) * 100) / budgetIncome));
            pdfFormFields.SetField("BUDSJETTTotalt_2", String.Format("{0:0.00}", ((budgetIncome - budgetCosts) * 100) / budgetIncome));

            //RESULT
            var resultPeriodIncome = SumSection("RESULT", new List <string> {
                "Salgsinntekter"
            });
            var resultPeriodCosts = SumSection("RESULT", new List <string> {
                "Varekjøp"
            });

            pdfFormFields.SetField("REGNSKAPTotalt", String.Format("{0:0.00}", ((resultPeriodIncome - resultPeriodCosts) * 100) / resultPeriodIncome));

            //RESULT_SOFAR
            var resultSofarIncome = SumSection("RESULT_SOFAR", new List <string> {
                "Salgsinntekter"
            });
            var resultSofarCosts = SumSection("RESULT_SOFAR", new List <string> {
                "Varekjøp"
            });

            pdfFormFields.SetField("REGNSKAPTotalt_2", String.Format("{0:0.00}", ((resultSofarIncome - resultSofarCosts) * 100) / resultSofarIncome));
        }
Esempio n. 14
0
 public void Map(AcroFields fields, int orderProduct, ProductTaxModel taxModel)
 {
     fields.SetField("DET_IMPOSTO_ICMS_ICMS_PICMS." + orderProduct, taxModel.IcmsAliquot.ToString());
     fields.SetField("DET_IMPOSTO_IPI_IPITRIB_PIPI." + orderProduct, taxModel.IpiAliquot.ToString());
     fields.SetField("DET_IMPOSTO_IPI_IPITRIB_VIPI." + orderProduct, taxModel.IpiValue.ToString());
     fields.SetField("DET_IMPOSTO_ICMS_ICMS_VICMS." + orderProduct, taxModel.IcmsValue.ToString());
 }
Esempio n. 15
0
        /// <summary>
        /// A partir do documento de modelo preenche os dados lidos
        /// </summary>
        /// <param name="Valores">Valores a serem preenchidos</param>
        /// <param name="NomeArquivo">Nome do arquivo a Ser gerado</param>
        private void PreencherModelo(string workFolder_, string caminhoCompletoArquivoAssinatura_, string contrato_, string CPF_, string municipio_, string NomeArquivo)
        {
            using (Stream newpdfStream = new FileStream(System.IO.Path.Combine(workFolder_ + "\\" + ConfigurationManager.AppSettings["Bradesco.DiretorioBalde"], NomeArquivo), FileMode.Create, FileAccess.ReadWrite))
            {
                PdfReader  pdfReader  = new PdfReader(caminhoCompletoArquivoAssinatura_);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, newpdfStream);

                AcroFields acroFields = pdfStamper.AcroFields;

                acroFields.SetField("contrato", contrato_);
                acroFields.SetField("Cidade", municipio_);
                acroFields.SetField("Dia", DateTime.Now.ToString("dd"));
                acroFields.SetField("Ano", DateTime.Now.Year.ToString().Substring(3, 1));
                acroFields.SetField("Mes", ToTitleCase(new DateTime(1900, DateTime.Now.Month, 1).ToString("MMMM", new CultureInfo("pt-BR"))));

                //marcando os campos como somente leitura
                acroFields.SetFieldProperty("contrato", "setfflags", PdfFormField.FF_READ_ONLY, null);
                acroFields.SetFieldProperty("Cidade", "setfflags", PdfFormField.FF_READ_ONLY, null);
                acroFields.SetFieldProperty("Dia", "setfflags", PdfFormField.FF_READ_ONLY, null);
                acroFields.SetFieldProperty("Ano", "setfflags", PdfFormField.FF_READ_ONLY, null);
                acroFields.SetFieldProperty("Mes", "setfflags", PdfFormField.FF_READ_ONLY, null);

                acroFields = null;
                pdfStamper.Close();
                pdfReader.Close();
                pdfReader.Dispose();
                pdfStamper.Dispose();
                newpdfStream.Close();
                newpdfStream.Dispose();
            }
        }
Esempio n. 16
0
 private static void SetProperties(ICharacter character, AcroFields form)
 {
     foreach (var prop in character.Properities)
     {
         form.SetField(prop.Name, prop.Value);
     }
     form.SetField("CharacterName 2", character.Properities.FirstOrDefault(x => x.Name == "Name")?.Value);
 }
Esempio n. 17
0
 private static void SetSkills(ICharacter character, AcroFields form)
 {
     foreach (var skill in character.Skills)
     {
         form.SetField(skill.Name, $"{skill.Total}");
         form.SetField($"{skill.Name} Check Box", Helper.BoolToYesNo(skill.Prof));
     }
 }
Esempio n. 18
0
// ---------------------------------------------------------------------------
        public void SetFields(PdfStamper stamper)
        {
            AcroFields form = stamper.AcroFields;

            form.SetField("movie[0].#subform[0].title[0]", "The Misfortunates");
            form.SetField("movie[0].#subform[0].original[0]", "De helaasheid der dingen");
            form.SetField("movie[0].#subform[0].duration[0]", "108");
            form.SetField("movie[0].#subform[0].year[0]", "2009");
        }
        private void createSwatch_Click(object sender, RoutedEventArgs e)
        {
            var itemName     = this.itemName.Text;
            var composition  = this.compositionText.Text;
            var construction = this.constructionText.Text;
            var weight       = this.weightText.Text;
            var comments     = this.commentsText.Text;

            if (itemName != "")
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                var pdfName = itemName.Replace(" ", "_");
                dlg.FileName   = pdfName;
                dlg.DefaultExt = ".pdf";
                dlg.Filter     = "pdf file (.pdf)|*.pdf";

                Nullable <bool> result = dlg.ShowDialog();

                if (result == true)
                {
                    string filename = dlg.FileName;
                    //string existingFile = "tmp.pdf";
                    string currentDirectory   = Directory.GetCurrentDirectory();
                    string existingFile       = System.IO.Path.Combine(currentDirectory, "tmp.pdf");
                    var    existingFileStream = new FileStream(existingFile, FileMode.Open);


                    var pdfReader  = new PdfReader(existingFileStream);
                    var pdfStamper = new PdfStamper(pdfReader, new FileStream(filename, FileMode.Create));

                    AcroFields pdfFormFields = pdfStamper.AcroFields;

                    pdfFormFields.SetField("itemName", itemName);
                    pdfFormFields.SetField("composition", composition);
                    pdfFormFields.SetField("construction", construction);
                    pdfFormFields.SetField("weight", weight);
                    pdfFormFields.SetField("comments", comments);

                    MessageBox.Show("Finished");
                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();


                    //var par = iTextSharp.text.Paragraph.GetInstance(itemName);
                    //Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                    //PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create));
                    //doc.Open();
                    //doc.Add(par);
                    //doc.Close();
                }
            }
            else
            {
                MessageBox.Show("Please enter Fabrics Name !");
            }
        }
Esempio n. 20
0
    public static MemoryStream GenerateEntryDetailsSummary(Registration reg, Guid paymentGroupId)
    {
        EntryList entries = EntryList.GetEntryList(paymentGroupId, reg.Id, "");

        PdfReader pdfReader = null;

        PdfStamper pdfStamper    = null;
        AcroFields pdfFormFields = null;

        List <MemoryStream> memoryStreamPdfStamperList = new List <MemoryStream>();

        int rowcounter = 0;

        foreach (Entry entry in entries)
        {
            MemoryStream memoryStreamPdfStamper = null;
            pdfReader = new PdfReader(System.Configuration.ConfigurationSettings.AppSettings["PdfTemplateLocation"] + "ENTRY DETAILS.pdf");
            memoryStreamPdfStamper = new MemoryStream();
            pdfStamper             = new PdfStamper(pdfReader, memoryStreamPdfStamper);
            pdfFormFields          = pdfStamper.AcroFields;


            // Form filling
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            PopulateFeeRow(rowcounter, pdfFormFields, entry.Campaign, entry.Amount, 0, 1, false, "");

            pdfFormFields.SetField("ENTRY ID", entry.Serial);
            pdfFormFields.SetField("CAMPAIGN TITLE", entry.Campaign);
            pdfFormFields.SetField("CLIENT NAME", entry.Client);
            pdfFormFields.SetField("BRAND NAME", entry.Brand);
            pdfFormFields.SetField("CATEGORY", entry.CategoryPSDetail);

            rowcounter++;

            pdfStamper.FormFlattening     = true;
            pdfStamper.Writer.CloseStream = false;
            pdfStamper.Close();

            memoryStreamPdfStamperList.Add(memoryStreamPdfStamper);
        }


        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        MemoryStream docstream = CreatePdfDoc(memoryStreamPdfStamperList);

        foreach (MemoryStream memoryStreamPdfStamper in memoryStreamPdfStamperList)
        {
            memoryStreamPdfStamper.Dispose();
        }

        docstream.Position = 0;
        return(docstream);
    }
Esempio n. 21
0
        private string ImprintPdf(string pdfPath, string orderId, string date, string amount)
        {
            try
            {
                PdfReader reader = null;

                //var tempPath = Path.GetTempFileName().Replace(".tmp", ".pdf");
                var tempPath = Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";

                lock (this)
                {
                    //reader = new PdfReader(File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath(pdfPath)));
                    reader = new PdfReader(File.ReadAllBytes(pdfPath));
                }

                List <string> _lstFields = null;
                _lstFields = reader.AcroFields.Fields.Keys.OfType <string>().ToList();

                PdfStamper formFiller = new PdfStamper(reader, new FileStream(tempPath, FileMode.Create));

                AcroFields formFields = formFiller.AcroFields;
                formFields.GenerateAppearances = true;

                if (formFields != null && formFields.Fields.Count > 0)
                {
                    foreach (string fieldKey in formFields.Fields.Keys)
                    {
                        if (fieldKey == "orderid")
                        {
                            formFields.SetField(fieldKey, orderId);
                        }
                        else if (fieldKey == "amount")
                        {
                            formFields.SetField(fieldKey, amount);
                        }
                        else if (fieldKey == "date")
                        {
                            formFields.SetField(fieldKey, date);
                        }
                    }
                }
                formFiller.FormFlattening = true;
                formFiller.Close();

                byte[] imageArray = File.ReadAllBytes(tempPath);
                File.Delete(tempPath);
                return(Convert.ToBase64String(imageArray));
            }
            catch (Exception ex)
            {
                Log log = new Log();
                log.ErrorLog(MODULE, "CreditPayment", ex.Message);
                return(null);
            }
        }
Esempio n. 22
0
        private void StampTitles(AcroFields pdfFormFields)
        {
            string period = Dictionary["Period"] + ", " + Dictionary["Year"];

            pdfFormFields.SetField("period1", period);
            pdfFormFields.SetField("period2", period);
            pdfFormFields.SetField("period3", period);

            pdfFormFields.SetField("title1", "Resultatrapport");
            pdfFormFields.SetField("title2", "Fortjenesteoversikt");
        }
Esempio n. 23
0
        public static byte[] fill_template(byte[] templateFile, List <FormElement> elements)
        {
            using (MemoryStream output = new MemoryStream())
                using (PdfReader pdfReader = new PdfReader(templateFile))
                    using (PdfStamper stamper = new PdfStamper(pdfReader, output))
                    {
                        //without this line of code, farsi fonts would not be visible
                        stamper.AcroFields.AddSubstitutionFont(GetFont().BaseFont);

                        AcroFields form = stamper.AcroFields;
                        form.GenerateAppearances = true;

                        elements.Where(e => !string.IsNullOrEmpty(e.Name) && form.Fields.ContainsKey(e.Name))
                        .ToList().ForEach(e =>
                        {
                            switch (form.GetFieldType(e.Name))
                            {
                            case AcroFields.FIELD_TYPE_TEXT:
                            case AcroFields.FIELD_TYPE_COMBO:
                            case AcroFields.FIELD_TYPE_RADIOBUTTON:
                                form.SetField(e.Name, e.Type == FormElementTypes.Numeric ? e.FloatValue.ToString() : e.TextValue);
                                break;

                            case AcroFields.FIELD_TYPE_CHECKBOX:
                                form.SetField(e.Name, e.BitValue.HasValue && e.BitValue.Value ? "Yes" : "Off");
                                break;

                            case AcroFields.FIELD_TYPE_LIST:
                                form.SetListOption(e.Name,
                                                   e.TextValue.Split('~').Select(t => t.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToArray(), null);
                                form.SetField(e.Name, null);
                                break;

                            case AcroFields.FIELD_TYPE_PUSHBUTTON:
                                break;

                            case AcroFields.FIELD_TYPE_SIGNATURE:
                                break;
                            }
                        });

                        //by doing this, the form will not be editable anymore
                        stamper.FormFlattening = true;

                        //to make a specific field not editable
                        //stamper.PartialFormFlattening("[field_name]");

                        stamper.Close();
                        pdfReader.Close();

                        return(output.GetBuffer());
                    }
        }
Esempio n. 24
0
// ---------------------------------------------------------------------------
        public byte[] FillData(PdfReader reader)
        {
            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    AcroFields form = stamper.AcroFields;
                    form.SetField("title", "The Misfortunates");
                    form.SetField("director", "Felix Van Groeningen");
                    form.SetField("year", "2009");
                    form.SetField("duration", "108");
                }
                return(ms.ToArray());
            }
        }
Esempio n. 25
0
        private static void SetWeapons(ICharacter character, AcroFields form)
        {
            var n = 1;

            foreach (var weapon in character.Weapons.Take(3))
            {
                form.SetField($"Wpn{n} Name", weapon.Name);
                form.SetField($"Wpn{n} AtkBonus", $"{createAttackBonus(character, weapon)}");
                form.SetField($"Wpn{n} Damage", createDamageString(character, weapon));
                n++;
            }
            String additionalWeapons = "";

            foreach (var weapon in character.Weapons.Skip(3))
            {
                additionalWeapons += weapon.Name + ";  " + "Atk +" + createAttackBonus(character, weapon) + ";  " + createDamageString(character, weapon) + Environment.NewLine;
            }
            form.SetFieldProperty("AttacksSpellcasting", "textsize", 8f, null);
            form.SetField("AttacksSpellcasting", additionalWeapons);

            int?createAttackBonus(ICharacter person, Weapon weapon)
            {
                var statSearch = StatSearch(weapon);

                var attack = person.Abilities.FirstOrDefault(x => x.Name == statSearch)?.Bonus + weapon.AttackBonus;

                if (weapon.Prof)
                {
                    if (int.TryParse(person.Properities?.FirstOrDefault(x => x.Name == "ProfBonus")?.Value, out var intOut))
                    {
                        attack += intOut;
                    }
                }

                return(attack);
            }

            string createDamageString(ICharacter person, Weapon weapon)
            {
                var damageString = string.Empty;

                foreach (var damage in weapon.Damages)
                {
                    damageString  = string.IsNullOrWhiteSpace(damageString) ? "" : damageString + " & ";
                    damageString +=
                        $"{damage.Dice} + {person.Abilities.FirstOrDefault(x => x.Name == (damage.Stat == "base" ? StatSearch(weapon) : damage.Stat))?.Bonus + int.Parse(damage.Bonus)} {damage.Type}";
                }

                return(damageString);
            }
        }
Esempio n. 26
0
        public void Print()
        {
            try
            {
                String pdfTemp = CoreUtils.GetSetting(CoreEnums.Settings.Standalone_Signin_FormsDir).ToString() + "Blank_Timesheet.pdf";
                String newFile = CoreUtils.GetSetting(CoreEnums.Settings.Standalone_Signin_OutputDir).ToString() + "Timesheet-" + BeginDate.ToString("MM-dd-yyyy") + "-" + EndDate.ToString("MM-dd-yyyy") + ".pdf";

                pdfReader     = new PdfReader(pdfTemp);
                pdfStamper    = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
                pdfFormFields = pdfStamper.AcroFields;

                pdfFormFields.SetField("EID", Ecode);
                pdfFormFields.SetField("EmpName", Ename);
                pdfFormFields.SetField("PayPeriodEnd", EndDate.ToString("MM-dd-yyyy"));
                pdfFormFields.SetField("Begin1_1", dtBegin1_1.ToString("MM-dd-yyyy"));
                pdfFormFields.SetField("Begin1_2", dtBegin1_2.ToString("MM-dd-yyyy"));
                pdfFormFields.SetField("Begin2_1", dtBegin2_1.ToString("MM-dd-yyyy"));
                pdfFormFields.SetField("Begin2_2", dtBegin2_2.ToString("MM-dd-yyyy"));

                DateTime cBeginDate = BeginDate;

                while (cBeginDate <= EndDate)
                {
                    string RowName = cBeginDate.ToString("dddd") + "_" + WhichWeek(cBeginDate);
                    Double hours   = CalculateHours(cBeginDate);

                    if (cBeginDate <= dtBegin1_2)
                    {
                        TotalHoursWeek1 += hours;
                    }
                    else
                    {
                        TotalHoursWeek2 += hours;
                    }

                    pdfFormFields.SetField(RowName, hours.ToString());
                    cBeginDate = cBeginDate.AddDays(1);
                }

                pdfFormFields.SetField("RegTotal1", Convert.ToString(TotalHoursWeek1));
                pdfFormFields.SetField("RegTotal2", Convert.ToString(TotalHoursWeek2));

                FormattedDataTable.Rows.Add(dtRow);
                pdfStamper.Close();
                CoreUtils.ShowMessage("Sign-In Logs", "PDF Printed", CoreEnums.ErrorType.Notice);
            }
            catch (Exception e)
            {
                CoreUtils.ShowMessage("Sign In Logs", e.Message);
            }
        }
Esempio n. 27
0
        private void btnCalCoTax_Click(object sender, EventArgs e)
        {
            int   index;                                                      // declaring the index as a vairble so it is not outside the scope as I am using the Try catch block.
            Regex rgx      = new Regex(@"^c\d{4}$");                          // checks to match C####
            Regex rgxHours = new Regex(@"^(\d+(\.\d{1,2})?|[.](\d{1,2})?)$"); // checks to match a valid hours worked

            if (!rgx.IsMatch(txtEmployeeID.Text.ToLower()) || !rgxHours.IsMatch(txtHoursWork.Text))
            {
                MessageBox.Show("Operation failed\nPlease ensure that both Employee ID and Hours Worked are correct\nFormat Employee ID: C###");
            }
            else
            {
                try
                {
                    index = Array.FindIndex(contractors, a => a.EmployeeID == txtEmployeeID.Text.ToUpper()); //getting the index of the contractors array that matches the employeeID entered
                }
                catch
                {
                    MessageBox.Show("The Employee ID you entered does not exist");
                    return; //Leave the method.
                }



                saveFilePath.FileName   = "Tax Report " + contractors[index].EmployeeID + " " + contractors[index].FirstName + " " + contractors[index].Surname; //setting the file name to ID + Name
                saveFilePath.Filter     = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
                saveFilePath.DefaultExt = "pdf";
                saveFilePath.ShowDialog();
                string newFile = saveFilePath.FileName;

                string pdfTemplatePath = System.IO.Path.GetFullPath("taxTemplate.pdf"); //pdf Template location

                string fullName = contractors[index].FirstName + " " + contractors[index].Surname;



                PdfReader  pdfReader     = new PdfReader(pdfTemplatePath);
                PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
                AcroFields pdfFormFields = pdfStamper.AcroFields;
                //Set all the fields to their correct values.
                pdfFormFields.SetField("EmployeeID", contractors[index].EmployeeID);
                pdfFormFields.SetField("Name", fullName);
                pdfFormFields.SetField("Department", contractors[index].Department);
                pdfFormFields.SetField("Salary", "$" + (contractors[index].HourlyRate) * decimal.Parse(txtHoursWork.Text));
                pdfFormFields.SetField("TaxPayable", "$" + ((contractors[index].HourlyRate) * decimal.Parse(txtHoursWork.Text) * contractors[index].TaxRate).ToString("0.00"));

                pdfStamper.FormFlattening = true; //making the pdf fields no longer editable

                pdfStamper.Close();               //close the PDF
            }
        }
Esempio n. 28
0
        private string createPDF(string place, string manufacturer, string model, string serialNo, string type, string damageDesc, string user)
        {
            if (!Directory.Exists(Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents") + @"\PDF"))
            {
                Directory.CreateDirectory(Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents") + @"\PDF");
            }
            var       template = Serwis.Properties.Resources.template;
            string    newFile  = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents") + @"\PDF\confirmation_" + serialNo + "_" + DateTime.Now.ToShortDateString() + ".pdf";
            PdfReader reader   = new PdfReader(template);

            using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
            {
                AcroFields fields = stamper.AcroFields;

                // set form fields
                fields.SetField("place", place);
                fields.SetField("date", DateTime.Now.ToLocalTime().ToString());
                fields.SetField("manufacturer", manufacturer);
                fields.SetField("model", model);
                fields.SetField("serialNo", serialNo);
                fields.SetField("type", type);
                fields.SetField("damageDesc", damageDesc);
                fields.SetField("user", user);

                // flatten form fields and close document
                stamper.FormFlattening = true;
                stamper.Close();
            }
            return(newFile);
        }
Esempio n. 29
0
        public bool addToPDFWithOneItem(Item i1)
        {
            FileStream tempFile = new FileStream(tempFilePath, FileMode.Create);

            PdfReader  pdfReader  = new PdfReader(formPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, tempFile);
            AcroFields fields     = pdfStamper.AcroFields;

            fields.SetField("ID#1", i1.CategoryID + i1.ItemID.ToString());
            fields.SetField("Name#1", i1.ItemName);
            fields.SetField("Value#1", i1.ItemValue.ToString());
            fields.SetField("MinBid#1", i1.MinBid.ToString());

            fields.SetField("ID#2", "");
            fields.SetField("Name#2", "");
            fields.SetField("Value#2", "");
            fields.SetField("MinBid#2", "");

            pdfStamper.Close();
            tempFile.Close();
            pdfReader.Close();
            addPage();

            return(true);
        }
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            string pdfTemplate = @"D:\To Be Converted\sbimf.pdf";
            string newFile     = @"D:\Converted\sbimf_filled.pdf";

            parseUsingPDFBox(pdfTemplate);
            PdfReader  pdfReader     = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfFormFields.SetField("Name", txtName.Text.ToString());
            pdfFormFields.SetField("DOB", txtDOB.Text.ToString());
            pdfFormFields.SetField("BranchCode", txtBranchCode.Text.ToString());
            pdfFormFields.SetField("PhoneNo", txtPhone.Text.ToString());
            pdfFormFields.SetField("Email", txtEmail.Text.ToString());
            pdfFormFields.SetField("SubBrockerCode", txtSubBrockerCode.Text.ToString());
            pdfFormFields.SetField("ARNNo", txtARN.Text.ToString());
            pdfFormFields.SetField("Folio", txtFolio.Text.ToString());

            pdfStamper.FormFlattening = false;

            // close the pdf
            pdfStamper.Close();

            Process.Start("D:\\Converted\\sbimf_filled.pdf");
        }