public void FillAndFlattenForm(String line, PdfAcroForm form) { StringTokenizer tokenizer = new StringTokenizer(line, ";"); IDictionary <String, PdfFormField> fields = form.GetFormFields(); fields["name"].SetValue(tokenizer.NextToken()); fields["abbr"].SetValue(tokenizer.NextToken()); fields["capital"].SetValue(tokenizer.NextToken()); fields["city"].SetValue(tokenizer.NextToken()); fields["population"].SetValue(tokenizer.NextToken()); fields["surface"].SetValue(tokenizer.NextToken()); fields["timezone1"].SetValue(tokenizer.NextToken()); fields["timezone2"].SetValue(tokenizer.NextToken()); fields["dst"].SetValue(tokenizer.NextToken()); // If no fields have been explicitly included via partialFormFlattening(), // then all fields are flattened. Otherwise only the included fields are flattened. form.FlattenFields(); }
public virtual void CreateResultantPdf(String dest, byte[] src) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(new RandomAccessSourceFactory().CreateSource(src), new ReaderProperties()), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); IDictionary <String, PdfFormField> fields = form.GetFormFields(); fields["sunday_1_notes"].SetValue("It's Sunday today, let's go to the sea").SetBorderWidth(0); fields["sunday_2_notes"].SetValue("It's Sunday today, let's go to the park").SetBorderWidth(0); fields["sunday_3_notes"].SetValue("It's Sunday today, let's go to the beach").SetBorderWidth(0); fields["sunday_4_notes"].SetValue("It's Sunday today, let's go to the woods").SetBorderWidth(0); fields["sunday_5_notes"].SetValue("It's Sunday today, let's go to the lake").SetBorderWidth(0); fields["sunday_6_notes"].SetValue("It's Sunday today, let's go to the river").SetBorderWidth(0); // All fields will be flattened, because no fields have been explicitly included form.FlattenFields(); pdfDoc.Close(); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); Document doc = new Document(pdfDoc); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); // If no fields have been explicitly included, then all fields are flattened. // Otherwise only the included fields are flattened. form.FlattenFields(); Rectangle pos = form.GetField("Name").GetWidgets()[0].GetRectangle().ToRectangle(); // Custom parser gets position of the form field // to fill in the document with the parsed content. CustomXmlParser parser = new CustomXmlParser(doc, pos); parser.Parse("<root><div>Bruno <u>Lowagie</u></div></root>"); pdfDoc.Close(); }
public byte[] FromValues(string pdfTemplate, IDictionary <string, string> values) { PdfReader pdfReader = new PdfReader(pdfTemplate); MemoryStream newFile = new MemoryStream(); PdfWriter writer = new PdfWriter(newFile); using (PdfDocument ps = new PdfDocument(pdfReader, writer)) { PdfAcroForm pdfAcroForm = PdfAcroForm.GetAcroForm(ps, false); foreach (string f in values.Keys) { pdfAcroForm.GetField(f).SetValue(values[f]); } pdfAcroForm.FlattenFields(); ps.Close(); } return(newFile.ToArray()); }
private byte[] RemoverAssinaturasDigitais(byte[] fileBytes) { using PdfReader pdfReader = new PdfReader(new MemoryStream(fileBytes)); pdfReader.SetUnethicalReading(true); using MemoryStream outputStream = new MemoryStream(); using PdfWriter pdfWriter = new PdfWriter(outputStream); using PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true); form.FlattenFields(); pdfDocument.Close(); byte[] outputArray = outputStream.ToArray(); //pdfWriter.Close(); //outputStream.Close(); //pdfReader.Close(); return(outputArray); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); form.GetField("name").SetValue("CALIFORNIA"); form.GetField("abbr").SetValue("CA"); form.GetField("capital").SetValue("Sacramento"); form.GetField("city").SetValue("Los Angeles"); form.GetField("population").SetValue("36,961,664"); form.GetField("surface").SetValue("163,707"); form.GetField("timezone1").SetValue("PT (UTC-8)"); form.GetField("timezone2").SetValue("-"); form.GetField("dst").SetValue("YES"); // If no fields have been explicitly included via PartialFormFlattening(), // then all fields are flattened. Otherwise only the included fields are flattened. form.FlattenFields(); pdfDoc.Close(); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); // This method tells to generate an appearance Stream while flattening for all form fields that don't have one. // Generating appearances will slow down form flattening, // but otherwise the results can be unexpected in Acrobat. form.SetGenerateAppearance(true); PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H); // ӧ character is used here form.GetField("Name").SetValue("\u04e711111", font, 12f); // If no fields have been explicitly included, then all fields are flattened. // Otherwise only the included fields are flattened. form.FlattenFields(); pdfDoc.Close(); }
public virtual void FormFlatteningTest_DefaultAppearanceGeneration_Rot270() { String srcFilePattern = "FormFlatteningDefaultAppearance_270_"; String destPattern = "FormFlatteningDefaultAppearance_270_"; for (int i = 0; i < 360; i += 90) { String src = sourceFolder + srcFilePattern + i + ".pdf"; String dest = destinationFolder + destPattern + i + "_flattened.pdf"; String cmp = sourceFolder + "cmp_" + srcFilePattern + i + ".pdf"; PdfDocument doc = new PdfDocument(new PdfReader(src), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true); foreach (PdfFormField field in form.GetFormFields().Values) { field.SetValue("Test"); } form.FlattenFields(); doc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(dest, cmp, destinationFolder, "diff_")); } }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); form.GetField("course").SetValue("Copying and Pasting from StackOverflow"); form.GetField("name").SetValue("Some dude on StackOverflow"); form.GetField("date").SetValue("April 10, 2016"); form.GetField("description").SetValue( "In this course, people consistently ignore the existing documentation completely. " + "They are encouraged to do no effort whatsoever, but instead post their questions " + "on StackOverflow. It would be a mistake to refer to people completing this course " + "as developers. A better designation for them would be copy/paste artist. " + "Only in very rare cases do these people know what they are actually doing. " + "Not a single student has ever learned anything substantial during this course."); // If no fields have been explicitly included, then all fields are flattened. // Otherwise only the included fields are flattened. form.FlattenFields(); pdfDoc.Close(); }
private static bool LlenarForm(Dictionary <string, string> data, string pathEntrada, string pathSalida) { try { using (PdfDocument p = new PdfDocument(new PdfReader(pathEntrada), new PdfWriter(pathSalida))) { PdfAcroForm form = PdfAcroForm.GetAcroForm(p, true); foreach (string key in data.Keys) { data.TryGetValue(key, out string value); var field = form.GetField(key); field.SetValue(value); } form.FlattenFields(); } return(true); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } }
public void EditPdfFromListUsers(List <Tuple <string, Dictionary <string, string> > > listUsers) { foreach (var user in listUsers) { reader = new PdfReader(source); reader.SetUnethicalReading(true); writer = new PdfWriter($"{destination }\\{user.Item1}.pdf"); pdfDoc = new PdfDocument(reader, writer); form = PdfAcroForm.GetAcroForm(pdfDoc, true); sourcePDFFields = form.GetFormFields(); foreach (var dicItem in user.Item2) { if (dicItem.Value != null) { sourcePDFFields[dicItem.Key].SetValue(dicItem.Value); } } form.FlattenFields(); pdfDoc.Close(); } }
public virtual void GetFieldsForFlatteningTest() { String outPdfName = destinationFolder + "flattenedFormField.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFolder + "formFieldFile.pdf"), new PdfWriter(outPdfName )); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false); NUnit.Framework.Assert.AreEqual(0, form.GetFieldsForFlattening().Count); form.PartialFormFlattening("radioName"); form.PartialFormFlattening("Text1"); PdfFormField radioNameField = form.GetField("radioName"); PdfFormField text1Field = form.GetField("Text1"); NUnit.Framework.Assert.AreEqual(2, form.GetFieldsForFlattening().Count); NUnit.Framework.Assert.IsTrue(form.GetFieldsForFlattening().Contains(radioNameField)); NUnit.Framework.Assert.IsTrue(form.GetFieldsForFlattening().Contains(text1Field)); form.FlattenFields(); pdfDoc.Close(); PdfDocument outPdfDoc = new PdfDocument(new PdfReader(outPdfName)); PdfAcroForm outPdfForm = PdfAcroForm.GetAcroForm(outPdfDoc, false); NUnit.Framework.Assert.AreEqual(2, outPdfForm.GetFormFields().Count); outPdfDoc.Close(); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> /// <exception cref="Javax.Xml.Parsers.ParserConfigurationException"/> /// <exception cref="Org.Xml.Sax.SAXException"/> public virtual void ConvertToPdfAcroformFlattenAndCompare(String name, String sourceFolder, String destinationFolder , bool tagged) { String sourceHtml = sourceFolder + name + ".html"; if (tagged) { name = name + "Tagged"; } String outPdfPath = destinationFolder + name + ".pdf"; String outPdfPathAcro = destinationFolder + name + "_acro.pdf"; String outPdfPathFlatted = destinationFolder + name + "_acro_flatten.pdf"; String cmpPdfPath = sourceFolder + "cmp_" + name + ".pdf"; String cmpPdfPathAcro = sourceFolder + "cmp_" + name + "_acro.pdf"; String cmpPdfPathAcroFlatten = sourceFolder + "cmp_" + name + "_acro_flatten.pdf"; String diff1 = "diff1_" + name; String diff2 = "diff2_" + name; String diff3 = "diff3_" + name; //convert tagged PDF without acroform (from html with form elements) PdfWriter taggedWriter = new PdfWriter(outPdfPath); PdfDocument pdfTagged = new PdfDocument(taggedWriter); if (tagged) { pdfTagged.SetTagged(); } HtmlConverter.ConvertToPdf(new FileStream(sourceHtml, FileMode.Open, FileAccess.Read), pdfTagged, new ConverterProperties ().SetBaseUri(sourceFolder)); //convert PDF with acroform PdfWriter writerAcro = new PdfWriter(outPdfPathAcro); PdfDocument pdfTaggedAcro = new PdfDocument(writerAcro); if (tagged) { pdfTaggedAcro.SetTagged(); } ConverterProperties converterPropertiesAcro = new ConverterProperties(); converterPropertiesAcro.SetBaseUri(sourceFolder); converterPropertiesAcro.SetCreateAcroForm(true); HtmlConverter.ConvertToPdf(new FileStream(sourceHtml, FileMode.Open, FileAccess.Read), pdfTaggedAcro, converterPropertiesAcro ); System.Console.Out.WriteLine("html: file:///" + UrlUtil.ToNormalizedURI(sourceHtml).AbsolutePath + "\n"); //flatted created tagged PDF with acroform PdfDocument document = new PdfDocument(new PdfReader(outPdfPathAcro), new PdfWriter(outPdfPathFlatted)); PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, false); acroForm.FlattenFields(); document.Close(); //compare with cmp NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPath, cmpPdfPath, destinationFolder , diff1)); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPathAcro, cmpPdfPathAcro, destinationFolder , diff2)); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPathFlatted, cmpPdfPathAcroFlatten, destinationFolder, diff3)); //compare tags structure if tagged if (tagged) { CompareTagStructure(outPdfPath, cmpPdfPath); CompareTagStructure(outPdfPathAcro, cmpPdfPathAcro); CompareTagStructure(outPdfPathFlatted, cmpPdfPathAcroFlatten); } }
public void CreatePdfDocument(int id, string userId) { var dbDoc = _db.CreatedPdfDocumenten .Include(x => x.DocumentPartValues) .Include(x => x.DocumentPartValues.Select(p => p.PdfDocumentPart)) .Include(x => x.PdfDocument) .Include(x => x.UserInsert) .Include(x => x.Logo) .First(x => x.Id == id && x.UserInsert.Id == userId); var src = Path.Combine(_basePathTemplates, dbDoc.PdfDocument.FileName); var destination = Path.Combine(_basePathUserSavedPdfs, dbDoc.UserInsert.Email, dbDoc.FileName); Directory.CreateDirectory(Path.GetDirectoryName(destination)); iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(new PdfReader(src), new PdfWriter(destination)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); var fields = form.GetFormFields(); var values = dbDoc.DocumentPartValues.Select(x => new { x.Value, x.PdfDocumentPart.VeldNaam, x.PdfDocumentPart.Pagina }); var taalConfiguraties = _db.PdfConfiguraties.Where(x => x.Language == dbDoc.Taal).OrderBy(x => x.Key).ToList(); foreach (var field in fields) { var v = values.FirstOrDefault(va => va.VeldNaam == field.Key); PdfFormField toSet; fields.TryGetValue(field.Key, out toSet); // logo velden if (field.Key.ToLower().Contains("logo")) { if (toSet is PdfButtonFormField) { SetLogo(toSet, pdfDoc, Path.Combine(_basePathTemplates, dbDoc.Logo.FileName), field.Key.ToLower() == "logo voorzijde" ? 1 : 2); } else { // zou niet mogen maar anders komt er een fout bij flattenfields toSet.SetValue(field.Key); } continue; } // taalvelden if (field.Key.ToLower().Contains("footer") || field.Key.ToLower().Contains("afsluiting achterzijde")) { SetFooter(toSet, pdfDoc, 2, taalConfiguraties); continue; } // gewone velden if (v != null && v.Value != null) { if (toSet is PdfButtonFormField) { var foto = _db.Fotos.First(f => f.Id.ToString() == v.Value); var filename = Path.Combine(_basePathFotos, foto.Path, foto.Name); SetImage(toSet, pdfDoc, filename, v.Pagina); } else { // rekening houden met maxlen var tekst = GetTekstBeperktOpMaxLen(toSet, v.Value); toSet.SetValue(tekst); } } else { toSet.SetValue(""); } } form.FlattenFields(); pdfDoc.Close(); //dbDoc.IsCreated = true; //_db.SaveChanges(); }
public string CreatePDFFromDatabase(string hourlyApplicationID) { SqlDataReader dr = dataacess.GetPDF(hourlyApplicationID); if (dr.HasRows == false) { return("/EVerify/I9Template.pdf"); } Page1 page1 = Page1FromDataReader(dr); string src = HttpContext.Current.Server.MapPath("/EVerify/I9Template.PDF"); string dest = HttpContext.Current.Server.MapPath("/EVerify/" + page1.LastName + ".pdf"); string FormI9_PDF = "/EVerify/" + page1.LastName + ".pdf"; PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); System.Collections.Generic.IDictionary <string, iText.Forms.Fields.PdfFormField> fields = form.GetFormFields(); var font = iText.Kernel.Font.PdfFontFactory.CreateFont(iText.IO.Font.FontConstants.HELVETICA); var font2 = iText.Kernel.Font.PdfFontFactory.CreateFont(iText.IO.Font.FontConstants.ZAPFDINGBATS); var font3 = iText.Kernel.Font.PdfFontFactory.CreateFont(iText.IO.Font.FontConstants.HELVETICA_BOLD); foreach (KeyValuePair <string, iText.Forms.Fields.PdfFormField> item in fields) { //if (item.Key == "State") item.Value.SetValue("GA"); item.Value.SetFont(font3); } KeyValuePair <string, iText.Forms.Fields.PdfFormField> Last = fields.First(k => k.Key == "LastName"); Last.Value.SetValue(page1.LastName); KeyValuePair <string, iText.Forms.Fields.PdfFormField> First = fields.First(k => k.Key == "FirstName"); First.Value.SetValue(page1.FirstName); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Middle = fields.First(k => k.Key == "Middle"); Middle.Value.SetValue(page1.Middle); KeyValuePair <string, iText.Forms.Fields.PdfFormField> OtherName = fields.First(k => k.Key == "OtherName"); OtherName.Value.SetValue(page1.otherName); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Address = fields.First(k => k.Key == "Address"); Address.Value.SetValue(page1.Address); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Apt = fields.First(k => k.Key == "Apt"); Apt.Value.SetValue(page1.AptNum); KeyValuePair <string, iText.Forms.Fields.PdfFormField> City = fields.First(k => k.Key == "City"); City.Value.SetValue(page1.City); KeyValuePair <string, iText.Forms.Fields.PdfFormField> State = fields.First(k => k.Key == "State"); State.Value.SetValue(page1.State); if (page1.Zip > 0) { KeyValuePair <string, iText.Forms.Fields.PdfFormField> Zip = fields.First(k => k.Key == "ZIP"); Zip.Value.SetValue(page1.Zip.ToString()); } if (page1.Birth > 0) { KeyValuePair <string, iText.Forms.Fields.PdfFormField> Birth = fields.First(k => k.Key == "Birth"); Birth.Value.SetValue(formatIntToDateString(page1.Birth)); } KeyValuePair <string, iText.Forms.Fields.PdfFormField> SSN1 = fields.First(k => k.Key == "SSN1"); SSN1.Value.SetValue(page1.SSN.ToString().Substring(0, 3)); KeyValuePair <string, iText.Forms.Fields.PdfFormField> SSN2 = fields.First(k => k.Key == "SSN2"); SSN2.Value.SetValue(page1.SSN.ToString().Substring(3, 2)); KeyValuePair <string, iText.Forms.Fields.PdfFormField> SSN3 = fields.First(k => k.Key == "SSN3"); SSN3.Value.SetValue(page1.SSN.ToString().Substring(5, 4)); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Email = fields.First(k => k.Key == "Email"); Email.Value.SetValue(page1.Email); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Phone = fields.First(k => k.Key == "Phone"); Phone.Value.SetValue(page1.Phone.ToString()); if (page1.Citizenship == "4") { KeyValuePair <string, iText.Forms.Fields.PdfFormField> Citizen = fields.First(k => k.Key == "chkCitizen"); //float foo = 18; Citizen.Value.SetValue("X"); //Citizen.Value.SetValue("3", font2, 18) ; } else if (page1.Citizenship == "5") { KeyValuePair <string, iText.Forms.Fields.PdfFormField> NonCitizen = fields.First(k => k.Key == "chkNonCitizen"); NonCitizen.Value.SetValue("X"); } else if (page1.Citizenship == "6") { KeyValuePair <string, iText.Forms.Fields.PdfFormField> Perm = fields.First(k => k.Key == "chkPerm"); Perm.Value.SetValue("X"); } else if (page1.Citizenship == "7") { KeyValuePair <string, iText.Forms.Fields.PdfFormField> Alien = fields.First(k => k.Key == "chkAlien"); Alien.Value.SetValue("X"); } KeyValuePair <string, iText.Forms.Fields.PdfFormField> AlienNum1 = fields.First(k => k.Key == "AlienNum1"); AlienNum1.Value.SetValue(page1.AlienNum1); KeyValuePair <string, iText.Forms.Fields.PdfFormField> AuthorizationExpDate = fields.First(k => k.Key == "AuthorizationExpDate"); AuthorizationExpDate.Value.SetValue(formatIntToDateString(page1.AuthorizationExpDate)); KeyValuePair <string, iText.Forms.Fields.PdfFormField> AlienNum2 = fields.First(k => k.Key == "AlienNum2"); AlienNum2.Value.SetValue(page1.AlienNum2); KeyValuePair <string, iText.Forms.Fields.PdfFormField> I94Num = fields.First(k => k.Key == "I94Num"); I94Num.Value.SetValue(page1.I94Num); KeyValuePair <string, iText.Forms.Fields.PdfFormField> ForeignPPNum = fields.First(k => k.Key == "ForeignPPNum"); ForeignPPNum.Value.SetValue(page1.ForeignPPNum); KeyValuePair <string, iText.Forms.Fields.PdfFormField> ForeignPPCountry = fields.First(k => k.Key == "ForeignPPCountry"); ForeignPPCountry.Value.SetValue(page1.ForeignPPCountry); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Signature = fields.First(k => k.Key == "Signature"); Signature.Value.SetValue(page1.Signature); KeyValuePair <string, iText.Forms.Fields.PdfFormField> SignatureDate = fields.First(k => k.Key == "SignatureDate"); //SignatureDate.Value.SetValue(formatIntToDateString(page1.SignatureDate)); SignatureDate.Value.SetValue(DateTime.Now.ToShortDateString()); if (assistTemp == true) { KeyValuePair <string, iText.Forms.Fields.PdfFormField> chkAssistYes = fields.First(k => k.Key == "AssistYes"); chkAssistYes.Value.SetValue("X"); } else if (assistTemp == false) { KeyValuePair <string, iText.Forms.Fields.PdfFormField> chkAssistNo = fields.First(k => k.Key == "AssistNo"); chkAssistNo.Value.SetValue("X"); } if (page1.SignatureCertifyEmp == true) { KeyValuePair <string, iText.Forms.Fields.PdfFormField> chkSignatureEmployee = fields.First(k => k.Key == "chkSignatureEmployee"); chkSignatureEmployee.Value.SetValue("X"); //chkSignatureEmployee.Value.SetValue("3", font2, 18); } KeyValuePair <string, iText.Forms.Fields.PdfFormField> SignaturePrep = fields.First(k => k.Key == "SignaturePrep"); SignaturePrep.Value.SetValue(page1.SignaturePrep); if (page1.SignatureCertifyPrep == true) { KeyValuePair <string, iText.Forms.Fields.PdfFormField> chkSignaturePrep = fields.First(k => k.Key == "chkSignaturePrep"); chkSignaturePrep.Value.SetValue("X"); //chkSignatureEmployee.Value.SetValue("3", font2, 18); } KeyValuePair <string, iText.Forms.Fields.PdfFormField> SignaturePrepDate = fields.First(k => k.Key == "SignaturePrepDate"); SignaturePrepDate.Value.SetValue(formatIntToDateString(page1.SignaturePrepDate)); KeyValuePair <string, iText.Forms.Fields.PdfFormField> PrepLastName = fields.First(k => k.Key == "PrepLastName"); PrepLastName.Value.SetValue(page1.PrepLastName ?? ""); KeyValuePair <string, iText.Forms.Fields.PdfFormField> PrepFirstName = fields.First(k => k.Key == "PrepFirstName"); PrepFirstName.Value.SetValue(page1.PrepFirstName ?? ""); KeyValuePair <string, iText.Forms.Fields.PdfFormField> PrepAddress = fields.First(k => k.Key == "PrepAddress"); PrepAddress.Value.SetValue(page1.PrepAddress); KeyValuePair <string, iText.Forms.Fields.PdfFormField> PrepCity = fields.First(k => k.Key == "PrepCity"); PrepCity.Value.SetValue(page1.PrepCity); KeyValuePair <string, iText.Forms.Fields.PdfFormField> PrepState = fields.First(k => k.Key == "PrepState"); PrepState.Value.SetValue(page1.PrepState); KeyValuePair <string, iText.Forms.Fields.PdfFormField> PrepZip = fields.First(k => k.Key == "PrepZip"); PrepZip.Value.SetValue(page1.PrepZip.ToString()); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Barcode = fields.First(k => k.Key == "Barcode"); Barcode.Value.SetValue(page1.AppID); KeyValuePair <string, iText.Forms.Fields.PdfFormField> IPEmployee = fields.First(k => k.Key == "IPEmployee"); IPEmployee.Value.SetValue("1) " + page1.SignatureCertifyEmpIP); KeyValuePair <string, iText.Forms.Fields.PdfFormField> IPEmployer = fields.First(k => k.Key == "IPEmployer"); IPEmployer.Value.SetValue("2) " + page1.CertifyCertifySignatureIP); KeyValuePair <string, iText.Forms.Fields.PdfFormField> LastName2 = fields.First(k => k.Key == "LastName2"); LastName2.Value.SetValue(page1.LastName); KeyValuePair <string, iText.Forms.Fields.PdfFormField> FirstName2 = fields.First(k => k.Key == "FirstName2"); FirstName2.Value.SetValue(page1.FirstName); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Middle2 = fields.First(k => k.Key == "Middle2"); Middle2.Value.SetValue(page1.Middle); KeyValuePair <string, iText.Forms.Fields.PdfFormField> Citizenship2 = fields.First(k => k.Key == "Citizenship2"); if (page1.Citizenship == "4") { Citizenship2.Value.SetValue("Citizen"); } else if (page1.Citizenship == "5") { Citizenship2.Value.SetValue("Non-citizen national"); } else if (page1.Citizenship == "6") { Citizenship2.Value.SetValue("Permanent Resident"); } else if (page1.Citizenship == "7") { Citizenship2.Value.SetValue("Authorized Alien"); } //string tempDocTitle = ""; //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA1Title = fields.First(k => k.Key == "DocA1Title"); //if (page1.DocA1Title == "11") tempDocTitle = "Arrival / Departure Record(Form I - 94)"; //else if (page1.DocA1Title == "13") tempDocTitle = "Permanent Resident Card or Alien Registration Receipt"; //else if (page1.DocA1Title == "17") tempDocTitle = "Employment Authorization Document"; //else if (page1.DocA1Title == "24") tempDocTitle = "Foreign Passport with I - 94"; //else if (page1.DocA1Title == "25") tempDocTitle = "Foreign Passport with I - 551"; //else if (page1.DocA1Title == "29") tempDocTitle = "U.S.Passport or Passport Card"; //DocA1Title.Value.SetValue(tempDocTitle); //tempDocTitle = ""; //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA2Title = fields.First(k => k.Key == "DocA2Title"); //if (page1.DocA2Title == "11") tempDocTitle = "Arrival / Departure Record(Form I - 94)"; //else if (page1.DocA2Title == "13") tempDocTitle = "Permanent Resident Card or Alien Registration Receipt"; //else if (page1.DocA2Title == "17") tempDocTitle = "Employment Authorization Document"; //else if (page1.DocA2Title == "24") tempDocTitle = "Foreign Passport with I - 94"; //else if (page1.DocA2Title == "25") tempDocTitle = "Foreign Passport with I - 551"; //else if (page1.DocA2Title == "29") tempDocTitle = "U.S.Passport or Passport Card"; //DocA2Title.Value.SetValue(tempDocTitle); //tempDocTitle = ""; //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA3Title = fields.First(k => k.Key == "DocA3Title"); //if (page1.DocA3Title == "11") tempDocTitle = "Arrival / Departure Record(Form I - 94)"; //else if (page1.DocA3Title == "13") tempDocTitle = "Permanent Resident Card or Alien Registration Receipt"; //else if (page1.DocA3Title == "17") tempDocTitle = "Employment Authorization Document"; //else if (page1.DocA3Title == "24") tempDocTitle = "Foreign Passport with I - 94"; //else if (page1.DocA3Title == "25") tempDocTitle = "Foreign Passport with I - 551"; //else if (page1.DocA3Title == "29") tempDocTitle = "U.S.Passport or Passport Card"; //DocA3Title.Value.SetValue(tempDocTitle); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA1Issuer= fields.First(k => k.Key == "DocA1Issuer"); //DocA1Issuer.Value.SetValue(page1.DocA1Issuer); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA2Issuer = fields.First(k => k.Key == "DocA2Issuer"); //DocA2Issuer.Value.SetValue(page1.DocA2Issuer); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA3Issuer = fields.First(k => k.Key == "DocA3Issuer"); //DocA3Issuer.Value.SetValue(page1.DocA3Issuer); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA1Num = fields.First(k => k.Key == "DocA1Num"); //DocA1Num.Value.SetValue(page1.DocA1Num); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA2Num = fields.First(k => k.Key == "DocA2Num"); //DocA2Num.Value.SetValue(page1.DocA2Num); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA3Num = fields.First(k => k.Key == "DocA3Num"); //DocA3Num.Value.SetValue(page1.DocA3Num); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA1Date = fields.First(k => k.Key == "DocA1Date"); //DocA1Date.Value.SetValue(formatIntToDateString(page1.DocA1Date)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA2Date = fields.First(k => k.Key == "DocA2Date"); //DocA2Date.Value.SetValue(formatIntToDateString(page1.DocA2Date)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocA3Date = fields.First(k => k.Key == "DocA3Date"); //DocA3Date.Value.SetValue(formatIntToDateString(page1.DocA3Date)); //tempDocTitle = ""; //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocBTitle = fields.First(k => k.Key == "DocBTitle"); //if (page1.DocBTitle == "1") tempDocTitle = "Driver's license"; //else if (page1.DocBTitle == "2") tempDocTitle = "ID Card"; //else if (page1.DocBTitle == "3") tempDocTitle = "School ID card"; //else if (page1.DocBTitle == "4") tempDocTitle = "Voter registration card"; //else if (page1.DocBTitle == "5") tempDocTitle = "U.S. military card"; //else if (page1.DocBTitle == "6") tempDocTitle = "Military dependent's ID card"; //else if (page1.DocBTitle == "7") tempDocTitle = "U.S. Coast Guard Merchant Mariner Card"; //else if (page1.DocBTitle == "8") tempDocTitle = "Native American tribal document"; //else if (page1.DocBTitle == "9") tempDocTitle = "Canadian Driver's license"; //else if (page1.DocBTitle == "10") tempDocTitle = "School record or report card"; //else if (page1.DocBTitle == "11") tempDocTitle = "Doctor or hospital record"; //else if (page1.DocBTitle == "12") tempDocTitle = "Day-care or nursery school record"; //DocBTitle.Value.SetValue(tempDocTitle); //tempDocTitle = ""; //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocCTitle = fields.First(k => k.Key == "DocCTitle"); //if (page1.DocCTitle == "13") tempDocTitle = "Social Security Card"; //else if (page1.DocCTitle == "14") tempDocTitle = "Certification of Birth Abroad (Form FS-545)"; //else if (page1.DocCTitle == "15") tempDocTitle = "Certification of Report of Birth (Form DS-1350)"; //else if (page1.DocCTitle == "16") tempDocTitle = "U.S. birth certificate (original or certified copy)"; //else if (page1.DocCTitle == "17") tempDocTitle = "Native American tribal document"; //else if (page1.DocCTitle == "18") tempDocTitle = "U.S. Citizen ID Card (Form I-197)"; //else if (page1.DocCTitle == "19") tempDocTitle = "ID Card for Use of Resident Citizen in the United States (Form I-179)"; //else if (page1.DocCTitle == "20") tempDocTitle = "Employment authorization document issued by the U.S. Department of Homeland Security"; //DocCTitle.Value.SetValue(tempDocTitle); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocBIssuer = fields.First(k => k.Key == "DocBIssuer"); //DocBIssuer.Value.SetValue(page1.DocBIssuer); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocCIssuer = fields.First(k => k.Key == "DocCIssuer"); //DocCIssuer.Value.SetValue(page1.DocCIssuer); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocBNum = fields.First(k => k.Key == "DocBNum"); //DocBNum.Value.SetValue(page1.DocBNum); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocCNum = fields.First(k => k.Key == "DocCNum"); //DocCNum.Value.SetValue(page1.DocCNum); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocBDate = fields.First(k => k.Key == "DocBDate"); //DocBDate.Value.SetValue(formatIntToDateString(page1.DocBDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocCDate = fields.First(k => k.Key == "DocCDate"); //DocCDate.Value.SetValue(formatIntToDateString(page1.DocCDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> DocsAdditional = fields.First(k => k.Key == "DocsAdditional"); //DocsAdditional.Value.SetValue(page1.DocsAdditional); KeyValuePair <string, iText.Forms.Fields.PdfFormField> FirstWorkDate = fields.First(k => k.Key == "FirstWorkDate"); FirstWorkDate.Value.SetValue(formatIntToDateString(page1.FirstWorkDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifySignature = fields.First(k => k.Key == "CertifySignature"); //CertifySignature.Value.SetValue(page1.CertifySignature); //if (page1.CertifyCertifySignature == true) //{ // KeyValuePair<string, iText.Forms.Fields.PdfFormField> chkCertifySignature = fields.First(k => k.Key == "chkCertifySignature"); // chkCertifySignature.Value.SetValue("X"); // //chkSignatureEmployee.Value.SetValue("3", font2, 18); //} //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyDate = fields.First(k => k.Key == "CertifyDate"); //CertifyDate.Value.SetValue(formatIntToDateString(page1.CertifyDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyTitle = fields.First(k => k.Key == "CertifyTitle"); //CertifyTitle.Value.SetValue(page1.CertifyTitle); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyLastName = fields.First(k => k.Key == "CertifyLastName"); //CertifyLastName.Value.SetValue(page1.CertifyLastName); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyFirstName = fields.First(k => k.Key == "CertifyFirstName"); //CertifyFirstName.Value.SetValue(page1.CertifyFirstName); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyCompany = fields.First(k => k.Key == "CertifyCompany"); //CertifyCompany.Value.SetValue(page1.CertifyCompany); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyAddress = fields.First(k => k.Key == "CertifyAddress"); //CertifyAddress.Value.SetValue(page1.CertifyAddress); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyCity = fields.First(k => k.Key == "CertifyCity"); //CertifyCity.Value.SetValue(page1.CertifyCity); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyState = fields.First(k => k.Key == "CertifyState"); //CertifyState.Value.SetValue(page1.CertifyState); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> CertifyZip = fields.First(k => k.Key == "CertifyZip"); //CertifyZip.Value.SetValue(page1.CertifyZip.ToString()); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyLastName = fields.First(k => k.Key == "ReverifyLastName"); //ReverifyLastName.Value.SetValue(page1.ReverifyLastName); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyFirstName = fields.First(k => k.Key == "ReverifyFirstName"); //ReverifyFirstName.Value.SetValue(page1.ReverifyFirstName); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyMiddle = fields.First(k => k.Key == "ReverifyMiddle"); //ReverifyMiddle.Value.SetValue(page1.ReverifyMiddle); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyRehireDate = fields.First(k => k.Key == "ReverifyRehireDate"); //ReverifyRehireDate.Value.SetValue(formatIntToDateString(page1.ReverifyRehireDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyDocTitle = fields.First(k => k.Key == "ReverifyDocTitle"); //ReverifyDocTitle.Value.SetValue(page1.ReverifyDocTitle); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyDocNum = fields.First(k => k.Key == "ReverifyDocNum"); //ReverifyDocNum.Value.SetValue(page1.ReverifyDocNum); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyDocDate = fields.First(k => k.Key == "ReverifyDocDate"); //ReverifyDocDate.Value.SetValue(formatIntToDateString(page1.ReverifyDocDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifySignature = fields.First(k => k.Key == "ReverifySignature"); //ReverifySignature.Value.SetValue(page1.ReverifySignature); //if (page1.ReverifySignatureCertify == true) //{ // KeyValuePair<string, iText.Forms.Fields.PdfFormField> chkReverifySignature = fields.First(k => k.Key == "chkReverifySignature"); // chkReverifySignature.Value.SetValue("X"); // //chkSignatureEmployee.Value.SetValue("3", font2, 18); //} ////chkReverifySignature //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyDate = fields.First(k => k.Key == "ReverifyDate"); //ReverifyDate.Value.SetValue(formatIntToDateString(page1.ReverifyDate)); //KeyValuePair<string, iText.Forms.Fields.PdfFormField> ReverifyName = fields.First(k => k.Key == "ReverifyName"); //ReverifyName.Value.SetValue(page1.ReverifyName); form.FlattenFields(); pdf.Close(); return("/EVerify/" + page1.LastName + ".pdf"); }
private void buttonDrucker_Click(object sender, EventArgs e) { PdfDocument pdf = new PdfDocument(new PdfReader(System.IO.Path.Combine(Environment.CurrentDirectory, "Laufzettel Kartonagen+Schilder.pdf")), new PdfWriter(Program.druckPfad)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); IDictionary <String, PdfFormField> fields = form.GetFormFields(); PdfFormField toSet; int count = 1; textLog.AppendText(Uhrzeit.Count.ToString()); foreach (var item in Uhrzeit) { if (item.Text != "") { fields.TryGetValue("Name " + count, out toSet); toSet.SetValue(KundenName[count - 1].Text); fields.TryGetValue("Uhrzeit " + count, out toSet); toSet.SetValue(Uhrzeit[count - 1].Text); if (Transaktion[count - 1].Text.Contains("Ausliefern")) { fields.TryGetValue("AnAb " + count, out toSet); toSet.SetValue("Anliefern"); } else { fields.TryGetValue("AnAb " + count, out toSet); toSet.SetValue("Abholen"); } fields.TryGetValue("Anzahl " + count, out toSet); toSet.SetValue(Kartonzahl[count - 1].ToString()); fields.TryGetValue("Strasse " + count, out toSet); toSet.SetValue(Anschrift[count - 1].Text); fields.TryGetValue("Telefon " + count, out toSet); toSet.SetValue(Kontakt[count - 1].Text); fields.TryGetValue("Besonderheit " + count, out toSet); toSet.SetValue(Bemerkung[count - 1].Text); count++; } } fields.TryGetValue("Datum", out toSet); toSet.SetValue(dateTransaktion.Value.ToShortDateString()); fields.TryGetValue("Mitarbeiter", out toSet); toSet.SetValue(textMitarbeiter.Text); //fields.TryGetValue("Fahrzeug", out toSet); //toSet.SetValue(textFahrzeug.Text); form.FlattenFields(); try { pdf.Close(); } catch (Exception ex) { Program.FehlerLog(ex.ToString(), "Fehler beim schließen des PDF \r\n Bereits dokumentiert."); } //Program.showPDF(); Program.SendToPrinter(); textLog.AppendText("PDF Erfolgreich erzeugt"); }
// GET: Todos/Delete/5 public ActionResult GetPDF(int?id) { Trace.WriteLine("GET /Todos/GetPDF/" + id); if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Todo todo = db.Todoes.Find(id); if (todo == null) { return(HttpNotFound()); } //string filePath = HttpRuntime.AppDomainAppPath + "/PDF/NewEmployeeDetails.pdf"; //string filePathFilled = HttpRuntime.AppDomainAppPath + "/PDF/NewEmployeeDetailsFilled.pdf"; string filePath = MapPath("~/PDF/NewEmployeeDetails.pdf"); string filePathFilled = MapPath("~/PDF/NewEmployeeDetailsFilled.pdf"); PdfDocument pdf = new PdfDocument(new PdfReader(filePath), new PdfWriter(filePathFilled)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); PdfFont fontHELVETICA = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); string AsAboveAddressVaule = todo.AsAboveAddress ? "Yes" : ""; // empty string is false form.GetField("First Name").SetValue(todo.FirstName); form.GetField("Last Name").SetValue(todo.LastName); form.GetField("Full Address").SetValue(todo.FullAddress); if (todo.MailingAddress != null && AsAboveAddressVaule.Length <= 0) { PdfTextFormField mailingAddress = PdfFormField.CreateText(pdf, new Rectangle(227, 607, 310, 30), "mailingAddress", todo.MailingAddress, fontHELVETICA, 18); form.AddField(mailingAddress); } else { form.GetField("As Above").SetCheckType(PdfFormField.TYPE_CHECK).SetValue(AsAboveAddressVaule); } form.GetField("Email Address").SetValue(todo.EmailAddress).SetJustification(PdfFormField.ALIGN_LEFT); PdfTextFormField phoneNumber = PdfFormField.CreateText(pdf, new Rectangle(145, 538, 392, 30), "phoneNumber", "0" + todo.PhoneNumber.ToString(), fontHELVETICA, 18); form.AddField(phoneNumber); form.GetField("Citizenship Statas").SetValue(todo.CitizenStatus).SetJustification(PdfFormField.ALIGN_LEFT); form.GetField("Employment Start Date").SetValue(todo.EmploymentStartDate.ToString()).SetJustification(PdfFormField.ALIGN_LEFT); form.GetField("Employment Type").SetValue(todo.EmploymentType).SetJustification(PdfFormField.ALIGN_LEFT); form.GetField("Position Title").SetValue(todo.PositionTitle).SetJustification(PdfFormField.ALIGN_LEFT); form.GetField("Name").SetValue(todo.EmergencyContactName); form.GetField("Relationship").SetValue(todo.EmergencyContactRelationship); PdfTextFormField emergencyContactPhoneNumber = PdfFormField.CreateText(pdf, new Rectangle(145, 275, 392, 30), "emergencyPhoneNumber", "0" + todo.EmergencyContactPhoneNumber.ToString(), fontHELVETICA, 18); form.AddField(emergencyContactPhoneNumber); if (todo.EmployeeSignature != null) { ImageData imageData = ImageDataFactory.CreatePng(todo.EmployeeSignature); Image image = new Image(imageData).ScaleAbsolute(200, 50).SetFixedPosition(1, 190, 180); Document document = new Document(pdf); document.Add(image); } form.FlattenFields(); pdf.Close(); return(File(filePathFilled, "application/pdf"));; }
private static string CreatePdf(string strFileNameInput, string strFileNameOutput, Users user, int intKey) { PdfReader reader = new PdfReader(strFileNameInput); PdfDocument pdf = new PdfDocument(reader, new PdfWriter(strFileNameOutput)); try { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false); List <PdfAssociation> pdfAssociations = PdfAssociationDB.LoadPdfAssociation(intKey); // chiave template if (pdfAssociations == null) { throw new Exception("Associazioni field/pdf non valorizzate"); } if (pdfAssociations.Count == 1) { MessageBox.Show("Template non correttamente configurato", "Errore Configurazione", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(null); } // ciclo la lista e per ciascun ciclo vado a leggere il campo TIPO CAMPO foreach (var itempdf in pdfAssociations) { if (form.GetFormFields().ContainsKey(itempdf.PDF_FIELD)) // "txtMail, txtNameSurname ecc ecc" { switch (itempdf.TYPE) //"TXT","SIG" ecc ecc { case "TXT": MergePdfTxt(form, itempdf, user); break; case "SIG": AddSignature(form, itempdf); break; } } } #region //IDictionary<string, PdfFormField> keyValuePairs = form.GetFormFields(); //foreach (var item in keyValuePairs) //{ // item.Key --> Search modello + item.Key su pdf associati. // se esiste // in base al tipo campo fai switch // se txt : // se valore associato = "#CURRENTDATE#" fai insert data // se diverso fai verificare che non contenga campo "," // se non la contiene associ ute.campo corrispondente // se contiene virgola fai split //switch (item.Key) //{ // case "TXT": // MergePdfTxt(pdffieldName, Associazione rk) // break; // case "SIG": // AddSignature(pdffieldName) // break; // case default: // MessageBox.Show("Tipo Associazione non valido"); // break; //} //switch (item.Key) //{ // case "txtNameSurname": // item.Value.SetValue(ute.COGNOME + " " + ute.NOME); // break; // case "txtDate": // item.Value.SetValue(DateTime.Now.ToString("mm/dd/yyyy")); // break; // case "txtMail": // item.Value.SetValue(ute.MAIL); // break; // case "txtCell": // item.Value.SetValue(ute.CELL); // break; // case "txtSignature": // PdfArray position = form.GetField("txtSignature").GetWidgets()[0].GetRectangle(); // rectangle = position.ToRectangle(); // removeSigForBiometric = true; // break; //} //} #endregion form.FlattenFields(); pdf.Close(); reader.Close(); return(strFileNameOutput); } catch (Exception ex) { MessageBox.Show("Errore: " + ex.Message, "Configurazione errata", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(null); } finally { pdf.Close(); } }
public async Task <IActionResult> EmailCotizacion(int id) { MemoryStream stream = new MemoryStream(); Prospecto prospecto = await _context.Prospectos.SingleOrDefaultAsync(x => x.IdProspecto == id); string srcPdf = ""; if (prospecto.IdCompania.Equals(Constants.GuuidElectro)) { srcPdf = _hostingEnvironment.WebRootPath + "/pdf/" + Constants.CotizacionElectro; } else { srcPdf = _hostingEnvironment.WebRootPath + "/pdf/" + Constants.CotizacionAuto; } PdfWriter pdfWriter = new PdfWriter(stream); PdfDocument pdf = new PdfDocument(new PdfReader(srcPdf), pdfWriter); pdfWriter.SetCloseStream(false); PdfAcroForm pdfForm = PdfAcroForm.GetAcroForm(pdf, true); IDictionary <String, PdfFormField> fields = pdfForm.GetFormFields(); _utilities.FillPdf(fields, prospecto); pdfForm.FlattenFields(); pdf.Close(); stream.Flush(); stream.Position = 0; EmailService emailService = new EmailService(_emailConfiguration); EmailMessage emailMessage = new EmailMessage(); string src = ""; if (prospecto.IdCompania.Equals(Constants.GuuidElectro)) { emailMessage.FromAddresses = new List <EmailAddress>() { new EmailAddress { Name = "Qurii", Address = "*****@*****.**" } }; emailMessage.ToAddresses = new List <EmailAddress>() { new EmailAddress { Name = prospecto.PrimerNombre + " " + prospecto.SegundoNombre + " " + prospecto.PrimerApellido + " " + prospecto.SegundoApellido, Address = prospecto.Email } }; emailMessage.Subject = "[QURII] Cotización plan de ahorro programado"; switch (prospecto.Marca_exclusiva_bien) { case "YAMAHA": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionMotoMas.html"; break; case "AUTECO - BAJAJ": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionBajaj.html"; break; case "AUTECO - KAWASAKI": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionKawasaki.html"; break; case "AUTECO - KTM": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionKtm.html"; break; default: src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionElectroplan.html"; break; } } else { emailMessage.FromAddresses = new List <EmailAddress>() { new EmailAddress { Name = "Qurii", Address = "*****@*****.**" } }; emailMessage.ToAddresses = new List <EmailAddress>() { new EmailAddress { Name = prospecto.PrimerNombre + " " + prospecto.SegundoNombre + " " + prospecto.PrimerApellido + " " + prospecto.SegundoApellido, Address = prospecto.Email } }; emailMessage.Subject = "[Qurii] Cotización plan de ahorro programado"; switch (prospecto.Marca_exclusiva_bien) { case "KIA": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionKiaPlan.html"; break; case "HYUNDAI": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionAutokoreana.html"; break; case "VOLKSWAGEN": src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionAutofinanciera.html"; break; default: src = _hostingEnvironment.WebRootPath + "/emailtemplates/Cotizacion/CotizacionAutofinanciera.html"; break; } } emailMessage.Content = String.Format(_utilities.GetTemplate(src)); try { emailService.Send(emailMessage, stream, Constants.CotizacionPDF); TempData["EmailResult"] = "Success"; } catch (Exception ex) { TempData["EmailResult"] = "Ha ocurrido un error: " + ex.Message; } TempData.Keep("EmailResult"); // Auditoría 2019-06-29 AuditoriaProspectos auditor = new AuditoriaProspectos { FechaRegistro = DateTime.Now, IdProspecto = prospecto.IdProspecto, IPRegistro = HttpContext.Connection.RemoteIpAddress.ToString(), TipoDeMovimiento = "Email de cotización", UsuarioRegistrante = prospecto.ConfirmacionProspecto.UserId, DatosNuevos = _utilities.GetDatosJson(prospecto), DatosPrevios = "N/A" }; _context.Add(auditor); await _context.SaveChangesAsync(); return(RedirectToAction("Details", "Prospectos", new { id = prospecto.IdProspecto })); }
static void Main(string[] args) { Conf conf = new Conf(args); if (conf.show_help) { help(); return; } if (!conf.IsValid) { conf.messageBag.PrintErrors(); return; } if (conf.discover) { discover(conf); return; } InputFile filein = new InputFile(conf.fields_path); if (conf.fields_path != null && filein.fields.Count == 0) { new MessageBag("error", "No input fields provided in fields file").PrintErrors(); return; } try { PdfReader pdfReader = new PdfReader(conf.source_path); PdfWriter pdfWriter = new PdfWriter(conf.dest_path); PdfDocument doc = new PdfDocument(pdfReader, pdfWriter); PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true); IDictionary <string, PdfFormField> fields = form.GetFormFields(); if (conf.fields_path != null) { foreach (KeyValuePair <string, string> kvp in filein.fields) { string field_name = Regex.Replace(kvp.Key, @"^(circle|check|square|star|cross)-", "", RegexOptions.IgnoreCase); if (fields.ContainsKey(field_name)) { Console.Write(field_name); PdfFormField field; fields.TryGetValue(kvp.Key, out field); field.SetValue(kvp.Value); } } } foreach (KeyValuePair <string, string> kvp in conf.custom_fields) { string field_name = Regex.Replace(kvp.Key, @"^(circle|check|square|star|cross)-", "", RegexOptions.IgnoreCase); if (fields.ContainsKey(field_name)) { string t = form.GetField(field_name).GetFormType().ToString(); switch (t) { case "/Btn": if (Regex.IsMatch(kvp.Value, @"^(yes|on|1|true)$", RegexOptions.IgnoreCase)) { if (Regex.IsMatch(kvp.Key, @"^(circle|check|square|star|cross)-.*", RegexOptions.IgnoreCase)) { int checktype = PdfFormField.TYPE_CROSS; if (kvp.Key.StartsWith("circle")) { checktype = PdfFormField.TYPE_CIRCLE; } if (kvp.Key.StartsWith("check")) { checktype = PdfFormField.TYPE_CHECK; } if (kvp.Key.StartsWith("square")) { checktype = PdfFormField.TYPE_SQUARE; } if (kvp.Key.StartsWith("star")) { checktype = PdfFormField.TYPE_STAR; } form.GetField(field_name).SetCheckType(checktype).SetValue(kvp.Value, true); } } break; default: form.GetField(field_name).SetValue(kvp.Value); break; } } } if (!conf.preserve) { form.FlattenFields(); } doc.Close(); if (File.Exists(conf.dest_path)) { new MessageBag("message", conf.dest_path).PrintMessages(); } else { new MessageBag("error", "Process failed").PrintErrors(); } } catch (Exception e) { string message = conf.debug ? e.Message + Environment.NewLine + e.StackTrace + e.TargetSite : "Error"; new MessageBag("error", message).PrintErrors(); return; } }
private void buttonDrucker_Click(object sender, EventArgs e) { // Leeren / neubefüllen des Tablet-PDF´s Ordners var bestätigung = MessageBox.Show("PDF´s zum Mitnehmen neu erzeugen?", "Erinnerung", MessageBoxButtons.YesNo); if (bestätigung == DialogResult.Yes) { List <int> test = new List <int>(); try { if (Program.conn.State != ConnectionState.Open) { Program.conn.Open(); } MySqlCommand cmdReadKunde = new MySqlCommand("SELECT idUmzuege FROM Umzuege WHERE datBesichtigung = '" + Program.DateMachine(dateBesichtigung.Value.Date) + "';", Program.conn); MySqlDataReader rdrKunde = cmdReadKunde.ExecuteReader(); while (rdrKunde.Read()) { test.Add(rdrKunde.GetInt32(0)); } rdrKunde.Close(); Program.conn.Close(); } catch (Exception sqlEx) { Program.FehlerLog(sqlEx.ToString(), "Abrufen der Umzugsnummern zum Besichtigungsdatum (für das Ausliefern der PDFs)"); } Program.ordnerLeeren(); foreach (var item in test) { Umzug temps0 = new Umzug(item); temps0.druck(2); } textLog.AppendText("Ordner geleert, neue PDF´s erzeugt"); } // Drucken der Daten PdfDocument pdf = new PdfDocument(new PdfReader(System.IO.Path.Combine(Environment.CurrentDirectory, "Laufzettel Besichtigung.pdf")), new PdfWriter(Program.druckPfad)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); IDictionary <String, PdfFormField> fields = form.GetFormFields(); PdfFormField toSet; int zaehler = 1; String Uhrzeit = ""; String temp = ""; try { if (Program.conn.State != ConnectionState.Open) { Program.conn.Open(); } MySqlCommand cmdRead = new MySqlCommand("SELECT k.Anrede, k.Vorname, k.Nachname, k.Telefonnummer, k.Handynummer, u.StraßeA, u.HausnummerA, u.OrtA, u.PLZA, u.umzugsZeit FROM Kunden k, Umzuege u WHERE (u.Kunden_idKunden = k.idKunden AND u.datBesichtigung = '" + Program.DateMachine(dateBesichtigung.Value) + "') ORDER BY u.umzugsZeit ASc", Program.conn); MySqlDataReader rdr = cmdRead.ExecuteReader(); while (rdr.Read()) { fields.TryGetValue("Name " + zaehler, out toSet); toSet.SetValue(rdr[0] + " " + rdr[1] + " " + rdr[2]); fields.TryGetValue("Uhrzeit " + zaehler, out toSet); temp = rdr[9].ToString(); Uhrzeit = temp.Substring(0, 5); toSet.SetValue(Uhrzeit); fields.TryGetValue("Strasse " + zaehler, out toSet); toSet.SetValue(rdr[5] + " " + rdr[6] + " " + rdr[8] + " " + rdr[7]); //fields.TryGetValue("Ort " + zaehler, out toSet); //toSet.SetValue(rdr[8] + " " + rdr[7]); if (rdr[4].ToString() != "0") { fields.TryGetValue("Telefon " + zaehler, out toSet); toSet.SetValue(rdr[4] + ""); } else { fields.TryGetValue("Telefon " + zaehler, out toSet); toSet.SetValue(rdr[3] + ""); } zaehler++; } rdr.Close(); Program.conn.Close(); fields.TryGetValue("Mitarbeiter", out toSet); toSet.SetValue(textMitarbeiter.Text); fields.TryGetValue("Datum", out toSet); toSet.SetValue(dateBesichtigung.Value.ToShortDateString()); // Belegen aller Bemerkungsfelder fields.TryGetValue("Besonderheit 1", out toSet); toSet.SetValue(textBemerkung1.Text); fields.TryGetValue("Besonderheit 2", out toSet); toSet.SetValue(textBemerkung2.Text); fields.TryGetValue("Besonderheit 3", out toSet); toSet.SetValue(textBemerkung3.Text); fields.TryGetValue("Besonderheit 4", out toSet); toSet.SetValue(textBemerkung4.Text); fields.TryGetValue("Besonderheit 5", out toSet); toSet.SetValue(textBemerkung5.Text); fields.TryGetValue("Besonderheit 6", out toSet); toSet.SetValue(textBemerkung6.Text); fields.TryGetValue("Besonderheit 7", out toSet); toSet.SetValue(textBemerkung7.Text); fields.TryGetValue("Besonderheit 8", out toSet); toSet.SetValue(textBemerkung8.Text); fields.TryGetValue("Besonderheit 9", out toSet); toSet.SetValue(textBemerkung9.Text); fields.TryGetValue("Besonderheit 10", out toSet); toSet.SetValue(textBemerkung10.Text); fields.TryGetValue("Besonderheit 11", out toSet); toSet.SetValue(textBemerkung11.Text); fields.TryGetValue("Besonderheit 12", out toSet); toSet.SetValue(textBemerkung12.Text); fields.TryGetValue("Besonderheit 13", out toSet); toSet.SetValue(textBemerkung13.Text); } catch (Exception ex) { textLog.Text += ex.ToString(); } form.FlattenFields(); try { pdf.Close(); } catch (Exception ex) { Program.FehlerLog(ex.ToString(), "Fehler beim schließen des PDF \r\n Bereits dokumentiert."); } Program.SendToPrinter(); textLog.AppendText("PDF Erfolgreich erzeugt"); }