public void Display() { // flatten the form to remove editting options... // set it to false to leave the form open to subsequent manual edits //pdfStamper.FormFlattening = false; _pdfStamper.Close(); _pdfStamper.Dispose(); //fire up the PDF viewer var acroreader = Process.Start(_filledPdfPath); Debug.Assert(acroreader != null, "acroreader != null"); //spawn a background thread to wait for the PDF Viewer (i.e. Acrobat Reader) to be closed so PDF file can be deleted... so these files don't pile up indefinitely //this obviously isn't foolproof... e.g. if the user closes iTRAACv2 prior to AcroReader... but it should be pretty good new Thread(delegate(object filepath) { try { acroreader.WaitForExit(); File.Delete((string)filepath); } catch (Exception ex) //this exception handler must be included as part of this pattern wherever else it's implemented { System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke((Action) delegate { throw ex; }, null); //toss any exceptions over to the main UI thread, per MSDN direction: http://msdn.microsoft.com/en-us/library/system.windows.application.dispatcherunhandledexception.aspx } }).Start(_filledPdfPath); }
/// <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(); } }
protected virtual void Dispose(bool disposing) { if (disposing) { //Disposing Stamper if not alerady disposed if (!stamperDisposed && stamper != null) { try { stamper.Dispose(); } catch (Exception e) { //Calling logger Log("ERROR WHILE DIPOSING STAMPER:\n" + e.ToString()); } } //Disposing reader if (reader != null) { try { reader.Dispose(); } catch (Exception e) { //Calling logger Log("ERROR WHILE DIPOSING READER:\n" + e.ToString()); } } //Disposing memoryStream if (memoryStream != null) { try { memoryStream.Dispose(); } catch (Exception e) { //Calling logger Log("ERROR WHILE DIPOSING MEMORYSTREAM:\n" + e.ToString()); } } } }
public void Dispose() { if (!closed) { stamper.FormFlattening = !preserveEdit; stamper.Writer.CloseStream = false; stamper.Dispose(); sheet.Dispose(); } ms.Dispose(); }
public void Dispose() { if (reader != null) { reader.Dispose(); } if (ms != null) { ms.Dispose(); } if (stamper != null) { stamper.Dispose(); } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } try { if (!disposing) { return; } if (_pdfStamper != null) { _pdfStamper.Dispose(); } } finally { _disposed = true; } }
public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { errorMessages = new List <string>(); PersonAliasService personAliasService = new PersonAliasService(rockContext); Person person = personAliasService.Get(action.Activity.Workflow.GetAttributeValue("Person").AsGuid()).Person; LocationService locationService = new LocationService(rockContext); Location currentMailingAddress = locationService.Get(action.Activity.Workflow.GetAttributeValue("CurrentMailingAddress").AsGuid()); Location previousMailingAddress = locationService.Get(action.Activity.Workflow.GetAttributeValue("PreviousMailingAddress").AsGuid()); if (previousMailingAddress == null) { previousMailingAddress = new Location(); } Location reference1Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference1Address").AsGuid()); Location reference2Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference2Address").AsGuid()); Location reference3Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference3Address").AsGuid()); Location reference4Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference4Address").AsGuid()); Dictionary <string, string> fields = new Dictionary <string, string>() { { "ministryOfInterest", action.Activity.Workflow.GetAttributeValue("MinistryOfInterest") }, { "intPersonID", person.Id.ToString() }, { "txtLastName", action.Activity.Workflow.GetAttributeValue("LastName") }, { "txtFirstName", action.Activity.Workflow.GetAttributeValue("FirstName") }, { "txtMiddleName", action.Activity.Workflow.GetAttributeValue("MiddleName") }, { "txtMaidenOtherName", action.Activity.Workflow.GetAttributeValue("MaidenOtherNames") }, { "txtParent", action.Activity.Workflow.GetAttributeValue("Parent") }, { "txtParentEmail", action.Activity.Workflow.GetAttributeValue("ParentEmail") }, { "txtParentHomePhone", action.Activity.Workflow.GetAttributeValue("ParentHomePhone") }, { "txtParentCellPhone", action.Activity.Workflow.GetAttributeValue("ParentCellPhone") }, { "txtDateOfBirth", action.Activity.Workflow.GetAttributeValue("DateofBirth").AsDateTime().Value.ToShortDateString() }, //{"txtSSN", action.Activity.Workflow.GetAttributeValue("")}, { "radGender", action.Activity.Workflow.GetAttributeValue("") }, { "radMale", action.Activity.Workflow.GetAttributeValue("Gender") == "Male"?"Yes":"No" }, { "radFemale", action.Activity.Workflow.GetAttributeValue("Gender") == "Female"?"Yes":"No" }, { "txtSCCAttendanceDuration", action.Activity.Workflow.GetAttributeValue("HowLongAttended") }, { "txtSCCMember", person.ConnectionStatusValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER.AsGuid()?"Yes":"No" }, { "txtSCCMemberPDFNo", person.ConnectionStatusValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER.AsGuid()?"No":"Yes" }, { "txtSCCInvolvement", action.Activity.Workflow.GetAttributeValue("CurrentParticipation") }, { "txtChurch", action.Activity.Workflow.GetAttributeValue("ChurchAtttended") }, { "txtStreet", currentMailingAddress.Street1 }, { "txtCity", currentMailingAddress.City }, { "txtState", currentMailingAddress.State }, { "txtZip", currentMailingAddress.PostalCode }, { "SaveUpToThisPoint", "" }, { "txtPrevStreet", previousMailingAddress.Street1 }, { "txtPrevCity", previousMailingAddress.City }, { "txtPrevState", previousMailingAddress.State }, { "txtPrevZip", previousMailingAddress.PostalCode }, { "radOutOfState", action.Activity.Workflow.GetAttributeValue("OutsideKentuckyIndiana") }, { "radOutOfStatePDFYes", action.Activity.Workflow.GetAttributeValue("OutsideKentuckyIndiana").AsBoolean()?"Yes":"No" }, { "radOutOfStatePDFNo", action.Activity.Workflow.GetAttributeValue("OutsideKentuckyIndiana").AsBoolean()?"No":"Yes" }, { "txtOutOfState_Dates", action.Activity.Workflow.GetAttributeValue("WhenOutsideKentuckyIndiana") }, { "txtOutOfState_State", action.Activity.Workflow.GetAttributeValue("StatesOutsideKentuckyIndiana") }, { "txtEmployer", action.Activity.Workflow.GetAttributeValue("CurrentEmployer") }, { "txtPosition", action.Activity.Workflow.GetAttributeValue("PositionHeld") }, { "txtWorkPhone", action.Activity.Workflow.GetAttributeValue("WorkPhone") }, { "txtHomePhone", action.Activity.Workflow.GetAttributeValue("HomePhone") }, { "txtCellPhone", action.Activity.Workflow.GetAttributeValue("CellPhone") }, //{"txtWorkEmail", action.Activity.Workflow.GetAttributeValue("")}, { "txtEmail", person.Email }, { "txtRef1Name", action.Activity.Workflow.GetAttributeValue("Reference1Name") }, //{"txtRef1Relationship", action.Activity.Workflow.GetAttributeValue("")}, { "radRef1YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference1Relationship") + "/" + action.Activity.Workflow.GetAttributeValue("Reference1YearsKnown") }, { "txtRef1Address", reference1Address.Street1 }, { "txtRef1City", reference1Address.City }, { "txtRef1State", reference1Address.State }, { "txtRef1Zip", reference1Address.PostalCode }, //{"txtRef1PersPhone", action.Activity.Workflow.GetAttributeValue("")}, //{"txtRef1PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef1WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference1WorkPhone") }, //{"txtRef1WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef1HomePhone", action.Activity.Workflow.GetAttributeValue("Reference1HomePhone") }, { "txtRef1CellPhone", action.Activity.Workflow.GetAttributeValue("Reference1CellPhone") }, { "txtRef1Email", action.Activity.Workflow.GetAttributeValue("Reference1Email") }, { "txtRef2Name", action.Activity.Workflow.GetAttributeValue("Reference2Name") }, //{"txtRef2Relationship", action.Activity.Workflow.GetAttributeValue("")}, { "radRef2YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference2Relationship") + "/" + action.Activity.Workflow.GetAttributeValue("Reference2YearsKnown") }, { "txtRef2Address", reference2Address.Street1 }, { "txtRef2City", reference2Address.City }, { "txtRef2State", reference2Address.State }, { "txtRef2Zip", reference2Address.PostalCode }, //{"txtRef2PersPhone", action.Activity.Workflow.GetAttributeValue("")}, //{"txtRef2PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef2WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference2WorkPhone") }, //{"txtRef2WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef2HomePhone", action.Activity.Workflow.GetAttributeValue("Reference2HomePhone") }, { "txtRef2CellPhone", action.Activity.Workflow.GetAttributeValue("Reference2CellPhone") }, { "txtRef2Email", action.Activity.Workflow.GetAttributeValue("Reference2Email") }, { "txtRef3Name", action.Activity.Workflow.GetAttributeValue("Reference3Name") }, //{"txtRef3Relationship", action.Activity.Workflow.GetAttributeValue("")}, { "radRef3YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference3Relationship") + "/" + action.Activity.Workflow.GetAttributeValue("Reference3YearsKnown") }, { "txtRef3Address", reference3Address.Street1 }, { "txtRef3City", reference3Address.City }, { "txtRef3State", reference3Address.State }, { "txtRef3Zip", reference3Address.PostalCode }, //{"txtRef3PersPhone", action.Activity.Workflow.GetAttributeValue("")}, //{"txtRef3PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef3WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference3WorkPhone") }, //{"txtRef3WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef3HomePhone", action.Activity.Workflow.GetAttributeValue("Reference3HomePhone") }, { "txtRef3CellPhone", action.Activity.Workflow.GetAttributeValue("Reference3CellPhone") }, { "txtRef3Email", action.Activity.Workflow.GetAttributeValue("Reference3Email") }, { "txtRef4Name", action.Activity.Workflow.GetAttributeValue("Reference4Name") }, //{"txtRef4Relationship", action.Activity.Workflow.GetAttributeValue("")}, { "radRef4YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference4Relationship") + "/" + action.Activity.Workflow.GetAttributeValue("Reference4YearsKnown") }, { "txtRef4Address", reference4Address?.Street1 }, { "txtRef4City", reference4Address?.City }, { "txtRef4State", reference4Address?.State }, { "txtRef4Zip", reference4Address?.PostalCode }, //{"txtRef4PersPhone", action.Activity.Workflow.GetAttributeValue("")}, //{"txtRef4PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef4WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference4WorkPhone") }, //{"txtRef4WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")}, { "txtRef4HomePhone", action.Activity.Workflow.GetAttributeValue("Reference4HomePhone") }, { "txtRef4CellPhone", action.Activity.Workflow.GetAttributeValue("Reference4CellPhone") }, { "txtRef4Email", action.Activity.Workflow.GetAttributeValue("Reference4Email") }, //{"txtPhysLimitations", action.Activity.Workflow.GetAttributeValue("")}, { "txtPhysLimitations", action.Activity.Workflow.GetAttributeValue("PhysicalLimitationsExplanation") }, { "txtPhysLimitationsPDF", action.Activity.Workflow.GetAttributeValue("PhysicalLimitationsExplanation") }, { "radPhysLimitationsPDFYes", action.Activity.Workflow.GetAttributeValue("PhysicalLimitations").AsBoolean()?"Yes":"No" }, { "radPhysLimitationsPDFNo", action.Activity.Workflow.GetAttributeValue("PhysicalLimitations").AsBoolean()?"No":"Yes" }, { "radCrimePersons", action.Activity.Workflow.GetAttributeValue("Crime").AsBoolean()?"Yes":"No" }, { "radCrimePersonsPDFNo", action.Activity.Workflow.GetAttributeValue("Crime").AsBoolean()?"No":"Yes" }, //{"radCrimeProperty", action.Activity.Workflow.GetAttributeValue("")}, { "radThreatToMinors", action.Activity.Workflow.GetAttributeValue("Threat").AsBoolean()?"Yes":"No" }, { "radThreatToMinorsPDFNo", action.Activity.Workflow.GetAttributeValue("Threat").AsBoolean()?"No":"Yes" }, { "radCrimeCounseled", action.Activity.Workflow.GetAttributeValue("CrimeCounsel").AsBoolean()?"Yes":"No" }, { "radCrimeCounseledPDFYes", action.Activity.Workflow.GetAttributeValue("CrimeCounsel").AsBoolean()?"Yes":"No" }, { "radCrimeCounseledPDFNo", action.Activity.Workflow.GetAttributeValue("CrimeCounsel").AsBoolean()?"No":"Yes" }, { "radNeedsStaffContact", action.Activity.Workflow.GetAttributeValue("Contact").AsBoolean()?"Yes":"No" }, { "radNeedsStaffContactPDFNo", action.Activity.Workflow.GetAttributeValue("Contact").AsBoolean()?"No":"Yes" }, { "personDetailPage", GlobalAttributesCache.Value("InternalApplicationRoot") + "/Person/" + person.Id }, { "txtAppSigned", "{{t:s;r:y;o:\"Applicant\";}}" }, { "txtAppDated", "{{t:d;r:y;o:\"Applicant\";l:\"Date\";dd:\"" + DateTime.Now.ToShortDateString() + "\";}}" }, { "txtAppPrintedName", person.FullNameFormal }, { "txtSOFSigned", "{{t:s;r:n;o:\"Applicant\";}}" }, { "txtSOFDated", "{{t:d;r:n;o:\"Applicant\";l:\"Date\";dd:\"" + DateTime.Now.ToShortDateString() + "\";}}" }, { "txtSOFPrintedName", person.FullNameFormal }, { "txtParentSignature", "{{t:s;r:y;o:\"Parent\";}}" }, { "txtDate1", "{{t:d;r:y;o:\"Parent\";l:\"Date\";dd:\"" + DateTime.Now.ToShortDateString() + "\";}}" }, { "radReadSOFYes", action.Activity.Workflow.GetAttributeValue("ReadStatementOfFaith").AsBoolean()?"Yes":"No" }, { "radReadSOFNo", action.Activity.Workflow.GetAttributeValue("ReadStatementOfFaith").AsBoolean()?"No":"Yes" }, { "radAgreeSOFYes", action.Activity.Workflow.GetAttributeValue("AgreeStatementOfFaith").AsBoolean()?"Yes":"No" }, { "radAgreeSOFNo", action.Activity.Workflow.GetAttributeValue("AgreeStatementOfFaith").AsBoolean()?"No":"Yes" }, { "txtSOFCommentsAmendments", String.IsNullOrEmpty(action.Activity.Workflow.GetAttributeValue("CommentsStatementOfFaith"))?" ":action.Activity.Workflow.GetAttributeValue("CommentsStatementOfFaith") }, }; BinaryFileService binaryFileService = new BinaryFileService(rockContext); BinaryFile PDF = null; var isMinorApplicant = GetAttributeValue(action, "IsMinorApplication", true).AsBoolean(); if (isMinorApplicant) { PDF = binaryFileService.Get(GetActionAttributeValue(action, "MinorVolunteerApplicationPDF").AsGuid()); } else { PDF = binaryFileService.Get(GetActionAttributeValue(action, "AdultVolunteerApplicationPDF").AsGuid()); } var pdfBytes = PDF.ContentStream.ReadBytesToEnd(); using (MemoryStream ms = new MemoryStream()) { PdfReader pdfReader = new PdfReader(pdfBytes); PdfStamper pdfStamper = new PdfStamper(pdfReader, ms); AcroFields pdfFormFields = pdfStamper.AcroFields; foreach (var field in fields) { if (pdfFormFields.Fields.ContainsKey(field.Key)) { pdfFormFields.SetField(field.Key, field.Value); } } // flatten the form to remove editting options, set it to false // to leave the form open to subsequent manual edits pdfStamper.FormFlattening = true; // close the pdf pdfStamper.Close(); //pdfReader.Close(); pdfStamper.Dispose(); pdfStamper = null; BinaryFile renderedPDF = new BinaryFile(); renderedPDF.CopyPropertiesFrom(PDF); renderedPDF.Guid = Guid.NewGuid(); renderedPDF.FileName = "VolunteerApplication_" + person.FirstName + person.LastName + ".pdf"; renderedPDF.BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(new Guid(BACKGROUND_CHECK_BINARY_FILE_TYPE)).Id; BinaryFileData pdfData = new BinaryFileData(); pdfData.Content = ms.ToArray(); renderedPDF.DatabaseData = pdfData; binaryFileService.Add(renderedPDF); rockContext.SaveChanges(); action.Activity.Workflow.SetAttributeValue("PDF", renderedPDF.Guid); } return(true); }
public async Task <bool> Handle(PdfGenerateCommand request, CancellationToken cancellationToken) { var list = new List <Designacao>(); foreach (var id in request.Designacoes) { var designacao = await _db.Designacoes .Include(q => q.AlunoPrincipal) .ThenInclude(a => a.DadosPublicador) .Include(q => q.AlunoAjudante) .ThenInclude(a => a.DadosPublicador) .FirstAsync(q => q.DesignacaoId == id); if (designacao == null || designacao.DesignacaoId != id) { throw new NaoEncontradoException(nameof(Designacao), id); } list.Add(designacao); } using (var reader = new PdfReader(_pathTemplate)) { PdfStamper stamper = null; try { stamper = new PdfStamper(reader, new FileStream(_pathNewPdf + request.NomeArquivo, FileMode.Create)); } catch (DirectoryNotFoundException ex) { throw ex; } AcroFields fields = stamper.AcroFields; try { int i = 1; foreach (var designacao in list) { fields.SetFieldProperty(PdfConstants.Partes[i].GetValueOrDefault("NomePrincipal"), "textsize", 12f, null); fields.SetField(PdfConstants.Partes[i].GetValueOrDefault("NomePrincipal"), designacao.AlunoPrincipal.DadosPublicador.NomeCompleto); if (designacao.AlunoAjudante != null) { fields.SetFieldProperty(PdfConstants.Partes[i].GetValueOrDefault("NomeAjudante"), "textsize", 12f, null); fields.SetField(PdfConstants.Partes[i].GetValueOrDefault("NomeAjudante"), designacao.AlunoAjudante.DadosPublicador.NomeCompleto); } fields.SetFieldProperty(PdfConstants.Partes[i].GetValueOrDefault("Data"), "textsize", 12f, null); fields.SetField(PdfConstants.Partes[i].GetValueOrDefault("Data"), designacao.Data.ToShortDateString()); fields.SetField(PdfConstants.Partes[i].GetValueOrDefault(designacao.Tipo.ToString()), "Yes"); fields.SetField(PdfConstants.Partes[i].GetValueOrDefault(designacao.Local.ToString()), "Yes"); i++; } } catch (ArgumentNullException ex) { throw ex; } stamper.Dispose(); return(true); } }
public string GenerateEndorsement(EndorsementDto endorsement) { if (endorsement == null) { return(null); } _logger.LogTrace("GenerateEndorsement invoked. "); var templatePath = GetResource(endorsement.TemplatePdfUrl, EndorsementConstant.S_TEMPLATE_PDF_PATH); _logger.LogTrace("GetResource done. TemplatePath: " + templatePath); if (!File.Exists(templatePath)) { _logger.LogTrace("Endorsement file does not exist at path: " + templatePath); throw new Exception("Template pdf file not exists! :: Path: " + templatePath + " :: templatePdfUrl: " + endorsement.TemplatePdfUrl); } if (_fileService.IsValidPdf(templatePath) == false) { _logger.LogTrace("IsValidPdf is false :: TemplatePath: " + templatePath); throw new Exception("Template pdf file is invalid! :: Path: " + templatePath + " :: templatePdfUrl: " + endorsement.TemplatePdfUrl); } var filename = string.Empty; var folderEndorsement = string.Empty; var endorsementPath = string.Empty; _logger.LogTrace("Endorsement is set to parseemptytext: " + endorsement.ParseEmptyText); if (endorsement.ParseEmptyText) { filename = string.Format(CertificateConstant.S_DOCUMENT_FILENAME_EMPTY_FORMAT, EndorsementConstant.S_DOCUMENT_FILENAME_EMPTY, endorsement.EndorsementCode); _logger.LogTrace("Empty Endorsement filename: " + filename); folderEndorsement = HttpContext.Current.Server.MapPath(EndorsementConstant.S_OUTPUT_PATH_EMPTY); _logger.LogTrace("Empty Endorsement folder: " + folderEndorsement); endorsementPath = folderEndorsement + filename; _logger.LogTrace("Empty Endorsement path: " + endorsementPath); //Cleanup once a week. CleanUpFile(folderEndorsement, TimeSpan.FromDays(7)); if (File.Exists(endorsementPath)) { _logger.LogTrace("Empty Endorsement exists already. Return path. " + endorsementPath); return(endorsementPath); } } else { filename = _fileService.GetFileName("endorsement", endorsement.ApplicationId, endorsement.ProductId); _logger.LogTrace("Endorsement file: " + filename); folderEndorsement = HttpContext.Current.Server.MapPath(EndorsementConstant.S_OUTPUT_PATH); _logger.LogTrace("Endorsement folder: " + folderEndorsement); CleanUpFile(folderEndorsement, TimeSpan.FromDays(1)); endorsementPath = folderEndorsement + filename; _logger.LogTrace("Endorsement path: " + endorsementPath); } if (File.Exists(endorsementPath)) { File.Delete(endorsementPath); _logger.LogTrace("Endorsement exists already. Delete file. " + endorsementPath); } var reader = new PdfReader(templatePath); var stamper = new PdfStamper(reader, new FileStream(endorsementPath, FileMode.Create)); try { _logger.LogTrace("Parse actual pdf document start. "); stamper.SetEncryption(PdfWriter.STRENGTH128BITS, string.Empty, endorsement.PdfPassword, PdfWriter.AllowPrinting | PdfWriter.AllowCopy | PdfWriter.AllowScreenReaders); var pdfFormFields = stamper.AcroFields; var imageExtensions = new string[] { EndorsementConstant.S_IMAGE_FILE_EXTENSION_PNG, EndorsementConstant.S_IMAGE_FILE_EXTENSION_JPG }; if (endorsement.VariableValues != null) { foreach (var variableValue in endorsement.VariableValues) { if (imageExtensions.Contains(Path.GetExtension(variableValue.Value))) { var signatureFile = GetResource(variableValue.Value, EndorsementConstant.S_SIGNATURE_IMAGE_PATH); if (!string.IsNullOrWhiteSpace(signatureFile)) { stamper.SetImage(variableValue.Key, signatureFile); } } else { pdfFormFields.SetField(variableValue.Key, variableValue.Value); } } } _logger.LogTrace("Parse actual pdf document done."); return(endorsementPath); } catch (Exception exception) { _logger.LogException(exception); throw; } finally { // flatten form fields and close document stamper.FormFlattening = true; stamper.Close(); stamper.Dispose(); reader.Close(); reader.Dispose(); } }
public string GenerateCertificate(Certificate certificate) { if (certificate == null) { return(null); } var templatePath = GetResource(certificate.TemplatePdfUrl, CertificateConstant.S_TEMPLATE_PDF_PATH); if (!File.Exists(templatePath)) { throw new Exception("Template pdf file not exists! :: Path: " + templatePath + " :: templatePdfUrl: " + certificate.TemplatePdfUrl); } var filename = _fileService.GetFileName("certificate", certificate.ApplicationId, certificate.ProductId); var folderCertificate = HttpContext.Current.Server.MapPath(CertificateConstant.S_OUTPUT_PATH); var certificatePath = folderCertificate + filename; CleanUpFile(folderCertificate, TimeSpan.FromDays(1)); var reader = new PdfReader(templatePath); var stamper = new PdfStamper(reader, new FileStream(certificatePath, FileMode.Create)); stamper.SetEncryption(PdfWriter.STRENGTH128BITS, string.Empty, certificate.PdfPassword, PdfWriter.AllowPrinting | PdfWriter.AllowCopy | PdfWriter.AllowScreenReaders); var pdfFormFields = stamper.AcroFields; pdfFormFields.SetField(CertificateFieldsConstant.S_DATE, certificate.Date); //producer pdfFormFields.SetField(CertificateFieldsConstant.S_PRODUCER, certificate.Producer.FullFormat); pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_NAME, certificate.Contact.Name); pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_PHONE, certificate.Contact.Phone); pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_FAX, certificate.Contact.Fax); pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_EMAIL, certificate.Contact.Email); //insured pdfFormFields.SetField(CertificateFieldsConstant.S_INSURED_NAME, certificate.Insured.Name); pdfFormFields.SetField(CertificateFieldsConstant.S_INSURED_ADDRESS, certificate.Insured.AddressFormat); //insurer var insurerNumber = 1; foreach (var insurer in certificate.Insurers.OrderBy(o => o.Letter)) { pdfFormFields.SetField(CertificateFieldsConstant.S_INSURER_NAME + insurerNumber, insurer.Name); pdfFormFields.SetField(CertificateFieldsConstant.S_INSURER_NAIC + insurerNumber, insurer.Naic); insurerNumber += 1; } var policyGL = certificate.PolicySectionGl; if (policyGL != null) { //General Liability pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_INSURER_LETTER, policyGL.InsurerLetter); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_COMMERCIAL, policyGL.TakeCommercial); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_CLAIMS_MADE, policyGL.TakeClaimsMade); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OCCURRENCE, policyGL.TakeOccur); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY1, string.IsNullOrEmpty(policyGL.OtherLiability1) == false); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY1_TEXT, policyGL.OtherLiability1); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY2, string.IsNullOrEmpty(policyGL.OtherLiability2) == false); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY2_TEXT, policyGL.OtherLiability2); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_AGGREGATE_POLICY, policyGL.TakeAggregatePolicy); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_AGGREGATE_PROJECT, policyGL.TakeAggregateProject); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_AGGREGATE_LOCATION, policyGL.TakeAggregateLoc); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_POLICY_NUMBER, policyGL.Number); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_EFFECTIVE_DATE, policyGL.EffectiveDate); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_EXPIRY_DATE, policyGL.ExpiryDate); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_OCCURRENCE, policyGL.LimitOccurance); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_DAMAGE, policyGL.LimitDamage); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_MEDICAL_EXPENSE, policyGL.LimitMedical); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_PERSONAL_INJURY, policyGL.LimitPersonal); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_AGGREGATE, policyGL.LimitAggregate); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_PRODUCTS, policyGL.LimitProducts); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_OTHER_TEXT, policyGL.LimitOtherText); if (string.IsNullOrEmpty(policyGL.LimitOtherText) == false) { pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_OTHER_VALUE, policyGL.LimitOtherValue); } pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_ADDITIONAL_INSURED, policyGL.IsAdditionalInsured); pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_SUBROGATION_WAIVER, policyGL.IsAdditionalInsured); } var policyAutomobile = certificate.PolicyAutomobile; if (policyAutomobile != null) { //Automobile pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_INSURER_LETTER, policyAutomobile.InsurerLetter); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_ANY_AUTO, policyAutomobile.TakeAnyAuto); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_ALL_OWNED_AUTOS, policyAutomobile.TakeAllOwnedAutos); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_SCHEDULED_OWNED_AUTOS, policyAutomobile.TakeScheduledOwnedAutos); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_HIRED_OWNED_AUTOS, policyAutomobile.TakeHiredOwnedAutos); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_NON_OWNED_AUTOS, policyAutomobile.TakeNonOwnedAutos); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER1, string.IsNullOrEmpty(policyAutomobile.Other1) == false); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER1_TEXT, policyAutomobile.Other1); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER2, string.IsNullOrEmpty(policyAutomobile.Other2) == false); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER2_TEXT, policyAutomobile.Other2); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_POLICY_NUMBER, policyAutomobile.Number); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_EFFECTIVE_DATE, policyAutomobile.EffectiveDate); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_EXPIRY_DATE, policyAutomobile.ExpiryDate); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_COMBINED, policyAutomobile.LimitCombined); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_INJURY_PERSON, policyAutomobile.LimitInjuryPerson); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_INJURY_ACCIDENT, policyAutomobile.LimitInjuryAccident); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_PROPERTY_DAMAGE, policyAutomobile.LimitPropertyDamage); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_OTHER_TEXT, policyAutomobile.LimitOtherText); if (string.IsNullOrEmpty(policyAutomobile.LimitOtherText) == false) { pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_OTHER, policyAutomobile.LimitOtherValue); } pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_ADDITIONAL_INSURED, policyAutomobile.IsAdditionalInsured); pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_SUBROGATION_WAIVER, policyAutomobile.IsAdditionalInsured); } var policyUmbrella = certificate.PolicyUmbrella; if (policyUmbrella != null) { //Umbrella pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_INSURER_LETTER, policyUmbrella.InsurerLetter); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIABILITY, policyUmbrella.TakeLiability); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_OCCURRENCE, policyUmbrella.TakeOccur); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_EXCESS, policyUmbrella.TakeExcess); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_CLAIMS_MADE, policyUmbrella.TakeClaimsMade); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_DED, policyUmbrella.TakeDed); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_RETENTION, policyUmbrella.TakeRetention); if (policyUmbrella.TakeRetention) { pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_RETENTION, policyUmbrella.LimitiRetention); } pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_POLICY_NUMBER, policyUmbrella.Number); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_EFFECTIVE_DATE, policyUmbrella.EffectiveDate); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_EXPIRY_DATE, policyUmbrella.ExpiryDate); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_OCCURRENCE, policyUmbrella.LimitOccurrence); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_AGGREGATE, policyUmbrella.LimitAggregate); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_OTHER_TEXT, policyUmbrella.LimitOtherText); if (string.IsNullOrEmpty(policyUmbrella.LimitOtherText) == false) { pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_OTHER, policyUmbrella.LimitOtherValue); } pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_ADDITIONAL_INSURED, policyUmbrella.IsAdditionalInsured); pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_SUBROGATION_WAIVER, policyUmbrella.IsAdditionalInsured); } var policyWorker = certificate.PolicyWorker; if (policyWorker != null) { //Workers Compensation and Employers's Liability pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_INSURER_LETTER, policyWorker.InsurerLetter); pdfFormFields.SetFieldYesNo(CertificateFieldsConstant.S_WORKER_EXCLUDED_PARTNER, policyWorker.TakeAnyExcludedPartner); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_POLICY_NUMBER, policyWorker.Number); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_EFEECTIVATE_DATE, policyWorker.EffectiveDate); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_EXPIRY_DATE, policyWorker.ExpiryDate); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_STATUTORY, policyWorker.TakeLimitStatutory); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_OTHER, policyWorker.TakeLimitOther); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_LIMIT_ACCIDENT, policyWorker.LimitAccident); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_LIMIT_EMPLOYEE, policyWorker.LimitEmployee); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_LIMIT_POLICY, policyWorker.LimitPolicy); pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_SUBROGATION_WAIVER, policyWorker.IsAdditionalInsured); } var policyOther = certificate.PolicyOther; if (policyOther != null) { //Other pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_INSURER_LETTER, policyOther.InsurerLetter); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_TYPE, policyOther.InsuranceName); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_POLICY_NUMBER, policyOther.Number); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_EFFECITVE_DATE, policyOther.EffectiveDate); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_EXPIRY_DATE, policyOther.ExpiryDate); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_LIMITS, policyOther.LimitFormat); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_ADDITIONAL_INSURED, policyOther.IsAdditionalInsured); pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_SUBROGATION_WAIVER, policyOther.IsAdditionalInsured); } pdfFormFields.SetField(CertificateFieldsConstant.S_DESCRIPTION, certificate.Description); for (var i = 0; i < certificate.DescriptionColumn.Count(); i++) { CustomCoverage customCoverage = certificate.DescriptionColumn.ElementAt(i); pdfFormFields.SetField(CertificateFieldsConstant.S_DESCRIPTIONCOLUMN + (i + 1), customCoverage.FullFormat); } pdfFormFields.SetField(CertificateFieldsConstant.S_HOLDER, certificate.Holder.FullFormat); //add signature image var signatureFile = GetResource(certificate.SignatureImageUrl, CertificateConstant.S_SIGNATURE_IMAGE_PATH); stamper.SetImage(CertificateFieldsConstant.S_SIGNATURE, signatureFile); // flatten form fields and close document stamper.FormFlattening = true; stamper.Close(); stamper.Dispose(); reader.Close(); reader.Dispose(); return(certificatePath); }