public static DocumentModel GetDocumentModel(Guid idFirmInstitutionSDG, string documentType)
 {
     DocumentModel documentModel = new DocumentModel();
     using (UpsilabEntities context = new UpsilabEntities())
     {
         documentModel = context.DocumentModel.Include("FirmInstitution").Where(x => x.FirmInstitution.idFirmInstitution == idFirmInstitutionSDG && (x.DocumentType == null || x.DocumentType == documentType) && (x.IsDeleted == null || x.IsDeleted == false)).FirstOrDefault();
     }
     return documentModel;
 }
 public static DocumentModel GetDocumentModelFromId(Guid id)
 {
     DocumentModel documentModel = new DocumentModel();
     using (UpsilabEntities context = new UpsilabEntities())
     {
         documentModel = context.DocumentModel.Include("FirmInstitution").FirstOrDefault(x => x.IdDocumentModel == id);
     }
     return documentModel;
 }
예제 #3
0
        public void WriteDoc(string filename)
        {
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            var document = new DocumentModel();
            document.Sections.Add(
                  new Section(document,
                  new Paragraph(document, Statistic.GetInstance().Score().PlayerName + " " + Statistic.GetInstance().Score().GetScore())));

            document.Save(filename+".docx");
        }
        public XmlSaveObjectVer1_0_0()
        {
            CharacterModelCollection = new Collection<CharacterModel>();
            PlaceModelCollection = new Collection<PlaceModel>();
            StoryFrameModelCollection = new Collection<StoryFrameModel>();
            ItemModelCollection = new Collection<ItemModel>();

            CharaMarkCollection = new Collection<CharacterMark>();
            StoryFrameMarkCollection = new Collection<StoryFrameMark>();

            DocumentModel = new DocumentModel();
        }
 public static void SetModelId (this IDocument document, DocumentModel model, int modelId)
 {
     if (model == DocumentModel.EduProgram) {
         document.EduProgramId = modelId;
     } 
     else if (model == DocumentModel.EduProgramProfile) {
         document.EduProgramProfileId = modelId;
     }
     else {
         throw new ArgumentException ("Wrong model argument.");
     }
 }
예제 #6
0
        /// <summary>
        /// Initializes a new instance of class WordDocument
        /// </summary>
        public WordDocument()
        {
            try
            {
                var k = new Key();
                ComponentInfo.SetLicense(k.WordKey);

                _innerDocument = new DocumentModel();
                emdCache = new List<EntityMetadata>();
                InitializesStyles();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }
        public XmlSaveObjectVer2_0_0()
        {
            CharacterModelCollection = new Collection<CharacterModel>();
            PlaceModelCollection = new Collection<PlaceModel>();
            StoryFrameModelCollection = new Collection<StoryFrameModel>();
            ItemModelCollection = new Collection<ItemModel>();

            CharaMarkCollection = new Collection<CharacterMark>();
            StoryFrameMarkCollection = new Collection<StoryFrameMark>();

            CharacterStoryRelationModelCollection = new Collection<CharacterStoryRelationModel>();
            ItemStoryRelationModelCollection = new Collection<ItemStoryRelationModel>();
            TimelineEventModelCollection = new Collection<TimelineEventModel>();

            DocumentModel = new DocumentModel();
        }
 public static void SaveSectionContentToFile(DocumentModel model, string sectionName, string htmlContent)
 {
     try
     {
         var path = GetSectionPath(model, sectionName);
         if (!Directory.Exists(path))
         {
             CreateRecursDir(path);
         }
         var pathFile = string.Format("{0}\\{1}.html", path, GetNameDirFromString(sectionName));
         File.WriteAllText(pathFile, htmlContent);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
 public static string GetPdfContentFromFile(DocumentModel model)
 {
     try
     {
         var text = "";
         var path = GetPdfPath(model);
         var pathFile = string.Format("{0}\\{1}.html", path, GetNameDirFromString(model.Name));
         if (File.Exists(pathFile)) 
         {
             text = File.ReadAllText(pathFile);
         }
         return text;
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
 public static string GetSectionContentFromFile(DocumentModel model, string sectionName) 
 {
     try
     {
         var html = "";
         var path = GetSectionPath(model, sectionName);
         var pathFile = string.Format("{0}\\{1}.html", path, GetNameDirFromString(sectionName));
         if (File.Exists(pathFile))
         {
             html = File.ReadAllText(pathFile);
         }
         return html;                
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
예제 #11
0
        static void Main(string[] args)
        {
            XmlUpgradeObject settings;
            using (var file = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Files\Upgrade.xml")))
                settings = XmlUpgradeObject.Deserialize(file);

            var xml = LoadDocument(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Files\ServerSettings.xml"));
            var model = new DocumentModel(xml.ChildNodes.OfType<XmlProcessingInstruction>());

            Console.WriteLine("Current version: " + model.CurrentVersion);
            Console.WriteLine("Current environment: " + model.Environment);

            var context = new XmlTransformContext(xml, 0);
            bool hasChanges = false;
            foreach (var patch in settings.Patches.OrderBy(p => p.Version))
            {
                if (patch.Version <= model.CurrentVersion)
                {
                    Console.WriteLine("Patch version {0}: skipped", patch.Version);
                    continue;
                }
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Applying patch version " + patch.Version);
                Console.ForegroundColor = ConsoleColor.Gray;
                foreach (var transformationObject in patch.Transformations)
                {
                    var command = transformationObject.CreateCommand();
                    command.Execute(context);
                }
                model.CurrentVersion = patch.Version;
                hasChanges = true;
            }
            if (!hasChanges)
            {
                Console.WriteLine("No changes was made.");
                return;
            }
            model.Save(xml);
            xml.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ServerSettings-modified.xml"));
        }
        public void UpdateDocuments (IList<DocumentInfo> documents, DocumentModel model, int itemId)
        {
            var originalDocuments = default (IList<DocumentInfo>);

            if (model == DocumentModel.EduProgram) {
                originalDocuments = ModelContext.Query<DocumentInfo> ()
                    .Where (d => d.EduProgramId == itemId)
                    .ToList ();
            }
            else if (model == DocumentModel.EduProgramProfile) {
                originalDocuments = ModelContext.Query<DocumentInfo> ()
                    .Where (d => d.EduProgramProfileId == itemId)
                    .ToList ();
            }
            else {
                throw new ArgumentException ("Wrong model argument.");
            }

            foreach (var document in documents) {
                var originalDocument = originalDocuments.SingleOrDefault (d => d.DocumentID == document.DocumentID);
                if (originalDocument == null) {
                    document.SetModelId (model, itemId);
                    ModelContext.Add<DocumentInfo> (document);
                }
                else {
                    CopyCstor.Copy<DocumentInfo> (document, originalDocument);
                    ModelContext.Update<DocumentInfo> (originalDocument);

                    // do not delete this document later
                    originalDocuments.Remove (originalDocument);
                }
            }

            // should delete all remaining documents
            foreach (var originalDocument in originalDocuments) {
                ModelContext.Remove<DocumentInfo> (originalDocument);
            }
        }
예제 #13
0
        public async Task ManageModelsAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleManageModelsAsync

            var client = new DocumentModelAdministrationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Check number of custom models in the FormRecognizer account, and the maximum number of models that can be stored.
            AccountProperties accountProperties = await client.GetAccountPropertiesAsync();

            Console.WriteLine($"Account has {accountProperties.Count} models.");
            Console.WriteLine($"It can have at most {accountProperties.Limit} models.");

            // List the first ten or fewer models currently stored in the account.
            AsyncPageable <DocumentModelInfo> models = client.GetModelsAsync();

            int count = 0;
            await foreach (DocumentModelInfo modelInfo in models)
            {
                Console.WriteLine($"Custom Model Info:");
                Console.WriteLine($"  Model Id: {modelInfo.ModelId}");
                if (string.IsNullOrEmpty(modelInfo.Description))
                {
                    Console.WriteLine($"  Model description: {modelInfo.Description}");
                }
                Console.WriteLine($"  Created on: {modelInfo.CreatedOn}");
                if (++count == 10)
                {
                    break;
                }
            }

            // Create a new model to store in the account
#if SNIPPET
            Uri trainingFileUri = < trainingFileUri >;
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            BuildModelOperation operation = await client.StartBuildModelAsync(trainingFileUri, DocumentBuildMode.Template);

            Response <DocumentModel> operationResponse = await operation.WaitForCompletionAsync();

            DocumentModel model = operationResponse.Value;

            // Get the model that was just created
            DocumentModel newCreatedModel = await client.GetModelAsync(model.ModelId);

            Console.WriteLine($"Custom Model with Id {newCreatedModel.ModelId} has the following information:");

            Console.WriteLine($"  Model Id: {newCreatedModel.ModelId}");
            if (string.IsNullOrEmpty(newCreatedModel.Description))
            {
                Console.WriteLine($"  Model description: {newCreatedModel.Description}");
            }
            Console.WriteLine($"  Created on: {newCreatedModel.CreatedOn}");

            // Delete the model from the account.
            await client.DeleteModelAsync(newCreatedModel.ModelId);

            #endregion
        }
예제 #14
0
        public virtual async Task <DocumentModel> PrepareDocumentModel(DocumentModel documentModel, Document document, SimpleDocumentModel simpleModel)
        {
            var model = documentModel == null ? new DocumentModel()
            {
                Published = true
            } : documentModel;

            if (document != null)
            {
                model = document.ToModel();
            }
            else
            {
                if (simpleModel != null)
                {
                    model.CustomerId = simpleModel.CustomerId;
                    if (!string.IsNullOrEmpty(simpleModel.OrderId))
                    {
                        model.ObjectId    = simpleModel.OrderId;
                        model.ReferenceId = (int)Reference.Order;
                        var order = await _orderService.GetOrderById(simpleModel.OrderId);

                        if (order != null)
                        {
                            model.Number         = order.OrderNumber.ToString();
                            model.TotalAmount    = order.OrderTotal;
                            model.OutstandAmount = order.PaymentStatus == Core.Domain.Payments.PaymentStatus.Paid ? 0 : order.OrderTotal;
                            model.CurrencyCode   = order.CustomerCurrencyCode;
                            model.Name           = string.Format(_localizationService.GetResource("Order.Document"), model.Number);
                            model.DocDate        = order.CreatedOnUtc;
                            model.DueDate        = order.CreatedOnUtc;
                            model.Quantity       = 1;
                            model.Username       = $"{order.BillingAddress?.FirstName} {order.BillingAddress?.LastName}";
                        }
                    }
                    if (!string.IsNullOrEmpty(model.CustomerId))
                    {
                        model.CustomerEmail = (await _customerService.GetCustomerById(simpleModel.CustomerId))?.Email;
                    }

                    if (!string.IsNullOrEmpty(simpleModel.ProductId))
                    {
                        model.ObjectId    = simpleModel.ProductId;
                        model.ReferenceId = (int)Reference.Product;
                        var product = await _productService.GetProductById(simpleModel.ProductId);

                        if (product != null)
                        {
                            model.Name     = product.Name;
                            model.Number   = product.Sku;
                            model.Quantity = 1;
                        }
                    }
                }
            }
            var types = await _documentTypeService.GetAll();

            foreach (var item in types)
            {
                model.AvailableDocumentTypes.Add(new SelectListItem {
                    Text = item.Name, Value = item.Id
                });
            }
            return(model);
        }
 public string uptadeDocument([FromBody] DocumentModel document)
 {
     return(docDao.UpdateDocument(document));
 }
    static void Example1()
    {
        int numberOfProjects = 3;
        int itemsPerProject  = 8;

        string projectsRangeName = "Projects";
        string itemsRangeName    = "Items";

        // Create relational data.
        var projects = new DataTable(projectsRangeName);

        projects.Columns.Add("Id", typeof(int));
        projects.Columns.Add("Name", typeof(string));

        var items = new DataTable(itemsRangeName);

        items.Columns.Add("ProjectId", typeof(int));
        items.Columns.Add("Date", typeof(DateTime));
        items.Columns.Add("Hours", typeof(int));
        items.Columns.Add("Unit", typeof(double));
        items.Columns.Add("Price", typeof(double));

        // Create DataSet with parent-child relation.
        var data = new DataSet();

        data.Tables.Add(projects);
        data.Tables.Add(items);
        data.Relations.Add(itemsRangeName, projects.Columns["Id"], items.Columns["ProjectId"]);

        for (int projectIndex = 1; projectIndex <= numberOfProjects; projectIndex++)
        {
            int    id   = projectIndex;
            string name = $"Project {projectIndex}";

            projects.Rows.Add(id, name);

            for (int itemIndex = 1; itemIndex <= itemsPerProject; itemIndex++)
            {
                DateTime date = DateTime.Today
                                .AddMonths(projectIndex - numberOfProjects)
                                .AddDays(itemIndex - itemsPerProject);
                int    hours = itemIndex % 3 + 6;
                double unit  = projectIndex * 35.0;
                double price = hours * unit;

                items.Rows.Add(id, date, hours, unit, price);
            }
        }

        var document = DocumentModel.Load("MergeNestedRanges.docx");

        // Customize mail merging to achieve calculation of "TotalPrice" for each project.
        document.MailMerge.FieldMerging += (sender, e) =>
        {
            if (e.RangeName == "Projects" && e.FieldName == "TotalPrice")
            {
                var total = data.Tables[e.RangeName].Rows[e.RecordNumber - 1]
                            .GetChildRows(itemsRangeName).Sum(item => (double)item["Price"]);

                var totalRun = new Run(e.Document, total.ToString("0.00"));
                totalRun.CharacterFormat = e.Field.CharacterFormat.Clone();

                e.Inline = totalRun;
                e.Cancel = false;
            }
        };

        // Execute nested mail merge.
        document.MailMerge.Execute(data, null);

        document.Save("Merged Nested Ranges Output1.docx");
    }
 private static string GetRoot(DocumentModel model)
 {
     try
     {
         using (UpsilabEntities context = new UpsilabEntities())
         {
             var root = ConfigurationManager.DocumentModelRootPath;
             var fetch = context.FirmInstitution.Where(x => x.idFirmInstitution == model.IdFirmInstitution).FirstOrDefault();
             if (fetch == null) 
             {
                 throw new Exception("Institution introuvable");
             }
             var dirName = GetNameDirFromString(fetch.FirmInstitutionName);
             var path = string.Format("{0}\\{1}\\DocumentModels\\", root, dirName);
             return path;
         }
     }
     catch (Exception e) 
     {
         throw new Exception("Institution introuvable");
     }
 }
 private static string GetSectionPath(DocumentModel model, string sectionName)
 {
     var root = GetRoot(model);
     var dirName = GetNameDirFromString(model.Name);
     sectionName = GetNameDirFromString(sectionName);
     var path = string.Format("{0}\\{1}\\sections\\", root, dirName);
     return path;
 }
예제 #19
0
        //Business Logics for Life Insurance
        private bool RecordNewLifeInsurance(InsuranceModel insurance, ClientModel client, PolicyCoverageDetailModel policyCoverage, DocumentModel document, CoverageModel coverage)
        {
            ValidateAddInsurance validation = new ValidateAddInsurance();
            bool isCorrectAge  = validation.ValidateForAge(client.Age);
            bool isClientAdded = _repository.Create(client);

            if (isClientAdded)
            {
                bool isInsuranceAdded = _repository.Create(insurance);
                if (isInsuranceAdded)
                {
                    bool isDocumentAdded = _repository.Create(document);
                    if (isDocumentAdded)
                    {
                        bool isCoverageAdded = _repository.Create(coverage);
                        if (isCoverageAdded)
                        {
                            bool isPolicyCoverageAdded = _repository.Create(policyCoverage);
                            if (isPolicyCoverageAdded)
                            {
                                return(_repository.Save());
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
예제 #20
0
        //Record Insurance
        public bool Record(InsuranceModel insurance, ClientModel client, PolicyCoverageDetailModel policyCoverage, DocumentModel document, CoverageModel coverage)
        {
            InsuranceModel.InsuranceTypes type = insurance.InsuranceType;
            switch (type)
            {
            case InsuranceModel.InsuranceTypes.MOTOR_INSURANCE:
                return(RecordNewMotorInsurance(insurance, client, policyCoverage, document, coverage));

            case InsuranceModel.InsuranceTypes.LIFE_INSURANCE:
                return(RecordNewLifeInsurance(insurance, client, policyCoverage, document, coverage));

            default: return(false);
            }
            //_repository.Create(InsuranceModel insurance, ClientModel client, PolicyCoverageDetailModel policyCoverage, DocumentModel document, CoverageModel coverage);
        }
예제 #21
0
 public ApiController(DocumentModel model, RouteService router)
 {
     _model  = model;
     _router = router;
 }
        public static string ParserHtmlMethod(DocumentModel documentModel, Guid idDocument, string strHtml, string logoUrl, bool isproduct, FirmInstitutionViewModel firmCGP)
        {
            var userConnecte = SessionManager.GetUserSession();
            //var firmCGP = FirmInstitutionBL.GetFirmInstitutionCgpByIdDocument(idDocument); //FirmInstitutionBL.GetFirmInstitutionByUser(userConnecte);  //GetFirmCGP();
            var firmSDG = GetFirmSDG();
                        
            
            strHtml = strHtml.Replace("[" + FieldsEditorBL.DATE_FAIT_A + "]",DateTime.Now.ToString("d"));
            strHtml = strHtml.Replace("[sdg_lieu_fait_a]", firmSDG.FirmCity);

            if (!isproduct)
            {
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_ETABLISSEMENT_CGP + "]",
                    firmCGP != null ? firmCGP.FirmInstitutionName : string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.PRENOM_CGP_CONNECTE + "]",
                    userConnecte != null ? userConnecte.UserFirstName : string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_CGP_CONNECTE + "]",
                    userConnecte != null ? userConnecte.UserName : string.Empty);
            }
            else
            {
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_ETABLISSEMENT_CGP + "]",string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.PRENOM_CGP_CONNECTE + "]",string.Empty);
                strHtml = strHtml.Replace("[" + FieldsEditorBL.NOM_CGP_CONNECTE + "]",string.Empty);
            }


            var valDico = new Dictionary<string, string>();
            var fieldDico = new Dictionary<string, FieldValueModel>();


            var listNameKey = FieldValuesBL.GetAllNameKeyForMapping(documentModel.IdDocumentModel);
            listNameKey.ToList().ForEach(u => valDico.Add(u.NameKey, string.Empty));
            listNameKey.ToList().ForEach(u => fieldDico.Add(u.NameKey, u));
            var dico = FieldValuesBL.GetForMapping(idDocument);

            foreach (var item in dico)
            {
                valDico[item.Key] = item.Value;
            }

            foreach (var fv in valDico)
            {
                var value = fv.Value;
                var nk = fieldDico[fv.Key] ?? new FieldValueModel() { Value = string.Empty };
                var type = (nk != null && !string.IsNullOrEmpty(nk.Value)) ? nk.Value : "";

                switch (type)
                {
                    case "radio":
                    case "radiogroup":
                    case "civilite":
                        var rad_pattern = string.Format("ckvalue=\"{0}_{1}\"", fv.Key, value);
                        var rad_replace = "checked";
                        strHtml = strHtml.Replace(rad_pattern, rad_replace);
                        break;
                    case "checkbox":
                        var cbx_pattern = string.Format("value=\"[{0}]\"", fv.Key);
                        var cbx_replace = (value == "True") ? "checked" : "";
                        strHtml = strHtml.Replace(cbx_pattern, cbx_replace);
                        break;
                    case "ibanfield":
                        string[] ibanwords = value.Split(' ');
                        for (int i = 0; i < ibanwords.Length; i++)
                        {
                            var iban_pattern = string.Format("ibanvalue=\"{0}_{1}\"", fv.Key, i);
                            var iban_replace = string.Format("value=\"{0}\"", ibanwords[i]);  //ibanwords[i];
                            strHtml = strHtml.Replace(iban_pattern, iban_replace);
                        }
                        break;

                    case "numeric":
                        if(!String.IsNullOrEmpty(value)) 
                        {
                            decimal d = 0;
                            Decimal.TryParse(value.Replace('.',','), out d);
                            if (d > 0)
                            {
                                var f = new NumberFormatInfo { NumberGroupSeparator = " ", CurrencyDecimalDigits = 2 }; //TODO cultureInfo
                                value = d.ToString("n", f);
                            }
                        }
                        strHtml = strHtml.Replace("[" + fv.Key + "]", !string.IsNullOrEmpty(value) ? value : string.Empty);
                        break;

                    case "datetime":                        
                        if (!string.IsNullOrEmpty(value))
                        {
                            var dt = DateTime.MinValue;
                            DateTime.TryParse(value, CultureInfo.CreateSpecificCulture("Fr"), DateTimeStyles.None, out dt);
                            if (dt == DateTime.MinValue) 
                            {
                                DateTime.TryParse(value, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dt);
                            }                            
                            if (dt != DateTime.MinValue)
                            {
                                value = dt.ToString("dd/MM/yyyy");
                            }
                        }
                        strHtml = strHtml.Replace("[" + fv.Key + "]", !string.IsNullOrEmpty(value) ? value : string.Empty);
                        break;
                    default:
                        strHtml = strHtml.Replace("[" + fv.Key + "]", !string.IsNullOrEmpty(value) ? value : string.Empty);
                        break;
                }

            }
            strHtml = strHtml.Replace("[logo]", logoUrl + "NextStatge.jpg");
            return strHtml;
        }
예제 #23
0
        public void GenerateReportForMeeting(Meeting meeting, Commission commission, string type)
        {
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            ComponentInfo.FreeLimitReached +=
                (s, args) => args.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;

            var document = new DocumentModel();

            //String.Format(
            //    "Отчёт по встрече комиссии, специализирующейся на профиле ({0}).{1} Название комиссии - {2}.{1} Количество человек : {3} {1} " +
            //    "День проведения - {4} {1} Место встречи - {5} {1} Дата начала собрания - {6} {1} Длительность - {7} {1} УЧАСТНИКИ: {1}",
            //    commission.Profile.Description, Environment.NewLine, commission.Name, commission.Consist.Count,
            //    meeting.Date.ToShortDateString(), meeting.Venue, meeting.Date.ToShortTimeString(),
            //    meeting.DurationInMinutes)),

            var mainParagraph = new Paragraph(document,
                                              new Run(document,
                                                      String.Format("Отчёт по встрече комиссии, специализирующейся на профиле ({0})",
                                                                    commission.Profile.Description)),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("Название комиссии - {0}", commission.Name)),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("Количество человек : {0}", commission.Consist.Count)),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("День проведения - {0}", meeting.Date.ToShortDateString())),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("Место встречи - {0}", meeting.Venue)),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("Дата начала собрания - {0}", meeting.Date.ToShortTimeString())),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("Длительность - {0} минут", meeting.DurationInMinutes)),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                              new Run(document, String.Format("УЧАСТНИКИ:")),
                                              new SpecialCharacter(document, SpecialCharacterType.LineBreak));

            var table = new Table(document);

            var rowCount = meeting.Participants.Count;

            for (int i = 0; i < rowCount; i++)
            {
                var participant = meeting.Participants[i];
                var row         = new TableRow(document);
                table.Rows.Add(row);

                var cells = new List <TableCell>();

                var paragraph = new Paragraph(document, (i + 1).ToString());
                var cell      = new TableCell(document, paragraph);
                cells.Add(cell);

                paragraph = new Paragraph(document, participant.Name);
                cell      = new TableCell(document, paragraph);
                cells.Add(cell);

                paragraph = new Paragraph(document, participant.Surname);
                cell      = new TableCell(document, paragraph);
                cells.Add(cell);

                paragraph = new Paragraph(document, participant.Patronymic);
                cell      = new TableCell(document, paragraph);
                cells.Add(cell);

                paragraph = new Paragraph(document, participant.Role.ToString());
                cell      = new TableCell(document, paragraph);
                cells.Add(cell);

                paragraph = new Paragraph(document, participant.PassportData);
                cell      = new TableCell(document, paragraph);
                cells.Add(cell);

                AddCellsToRow(row, cells);
            }

            var mainSection = new Section(document, mainParagraph,
                                          new Paragraph(document, new SpecialCharacter(document, SpecialCharacterType.LineBreak)), table);

            document.Sections.Add(mainSection);

            var path = String.Format("{0}\\{1}.{2}", Environment.CurrentDirectory,
                                     String.Format("{0}-{1}", meeting.Commission.ToString(), meeting.Date.ToFileTime()), type);

            document.Save(path);

            Process.Start(path);
        }
예제 #24
0
 public void Reset()
 {
     DocumentModel = new DocumentModel();
 }
예제 #25
0
 public DocumentModelBuilder()
 {
     DocumentModel = new DocumentModel();
 }
 private void SetDocumentModel()
 {
     DocumentModel      = new DocumentModel();
     DocumentModel.Text = ModelsComposite.DocumentModel.Text;
 }
예제 #27
0
 public object FromEntry(DocumentModel.DynamoDBEntry entry)
 {
     S3ClientCache cache;
     if (!S3Link.Caches.TryGetValue(context, out cache))
     {
         throw new InvalidOperationException("Must use S3Link.Create");
     }
     return new S3Link(cache, entry.AsString());
 }            
예제 #28
0
 public object FromEntry(DocumentModel.DynamoDBEntry entry)
 {
     S3ClientCache cache;
     if (!S3Link.Caches.TryGetValue(context, out cache))
     {
         cache = S3Link.CreatClientCacheFromContext(context);
     }
     return new S3Link(cache, entry.AsString());
 }            
 public static string GetSignatureParametersContentFromFile(DocumentModel model)
 {
     try
     {
         var json = "";
         var path = GetPdfPath(model);
         var pathFile = string.Format("{0}\\SignatureParameters.json", path);
         if (File.Exists(pathFile))
         {
             json = File.ReadAllText(pathFile);
         }
         return json;
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
 public string post([FromBody] DocumentModel document)
 {
     return(docDao.CreateDocument(document));
 }
예제 #31
0
        private void ValidateDocumentModel(DocumentModel model, string description = null, IReadOnlyDictionary <string, string> tags = null)
        {
            ValidateDocumentModelInfo(model, description, tags);

            // TODO add validation for Doctypes https://github.com/Azure/azure-sdk-for-net-pr/issues/1432
        }
 private static string GetPdfPath(DocumentModel model) 
 {
     var root = GetRoot(model);
     var dirName = GetNameDirFromString(model.Name);
     var path = string.Format("{0}\\{1}\\pdf\\", root, dirName);
     return path;
 }
예제 #33
0
 private void InitDoc()
 {
     document = new DocumentModel();
     SetDefautFormatsDoc();
 }
        public async Task AnalyzeWithCustomModelFromUriAsync()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            Uri    trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);

            // Firstly, create a custom built model we can use to recognize the custom document. Please note
            // that models can also be built using a graphical user interface such as the Form Recognizer
            // Labeling Tool found here:
            // https://aka.ms/azsdk/formrecognizer/labelingtool

            var adminClient = new DocumentModelAdministrationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            BuildModelOperation buildOperation = await adminClient.StartBuildModelAsync(trainingFileUri);

            await buildOperation.WaitForCompletionAsync();

            DocumentModel customModel = buildOperation.Value;

            // Proceed with the custom document recognition.

            DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:FormRecognizerAnalyzeWithCustomModelFromUriAsync
#if SNIPPET
            string modelId = "<modelId>";
            string fileUri = "<fileUri>";
#else
            Uri    fileUri = DocumentAnalysisTestEnvironment.CreateUri("Form_1.jpg");
            string modelId = customModel.ModelId;
#endif

            AnalyzeDocumentOperation operation = await client.StartAnalyzeDocumentFromUriAsync(modelId, fileUri);

            await operation.WaitForCompletionAsync();

            AnalyzeResult result = operation.Value;

            Console.WriteLine($"Document was analyzed with model with ID: {result.ModelId}");

            foreach (AnalyzedDocument document in result.Documents)
            {
                Console.WriteLine($"Document of type: {document.DocType}");

                foreach (KeyValuePair <string, DocumentField> fieldKvp in document.Fields)
                {
                    string        fieldName = fieldKvp.Key;
                    DocumentField field     = fieldKvp.Value;

                    Console.WriteLine($"Field '{fieldName}': ");

                    Console.WriteLine($"  Content: '{field.Content}'");
                    Console.WriteLine($"  Confidence: '{field.Confidence}'");
                }
            }
            #endregion

            // Iterate over lines and selection marks on each page
            foreach (DocumentPage page in result.Pages)
            {
                Console.WriteLine($"Lines found on page {page.PageNumber}");
                foreach (var line in page.Lines)
                {
                    Console.WriteLine($"  {line.Content}");
                }

                Console.WriteLine($"Selection marks found on page {page.PageNumber}");
                foreach (var selectionMark in page.SelectionMarks)
                {
                    Console.WriteLine($"  Selection mark is '{selectionMark.State}' with confidence {selectionMark.Confidence}");
                }
            }

            // Iterate over the document tables
            for (int i = 0; i < result.Tables.Count; i++)
            {
                Console.WriteLine($"Table {i + 1}");
                foreach (var cell in result.Tables[i].Cells)
                {
                    Console.WriteLine($"  Cell[{cell.RowIndex}][{cell.ColumnIndex}] has content '{cell.Content}' with kind '{cell.Kind}'");
                }
            }

            // Delete the model on completion to clean environment.
            await adminClient.DeleteModelAsync(customModel.ModelId);
        }
예제 #35
0
        public IActionResult Index()
        {
            // If using Professional version, put your serial key below.
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");


            var html = @"
                <html>
                <head>
                
                <style>
                  @page {
                    size: A5 landscape;
                    margin: 6cm 1cm 1cm;
                    mso-header-margin: 1cm;
                    mso-footer-margin: 1cm;
                    
                  }

                  body {
                    background: #FFF;
                    border: 1pt solid black;
                    padding: 20pt;
                    width: 700px;
                  }

                  br {
                    page-break-before: always;
                  }

                  p { margin: 0; }
                  header { color: #000; text-align: center; font-family: 'Tangerine', serif; font-size: 48px;}
                  main { color: #00B050; }
                  footer { color: #0070C0; text-align: right; }
                </style>
                </head>

                <body>
                  <header>
                    <img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/certificate_top.jpg' alt='Certificate Top'/>
                  </header>
                  <main>
<div style='text-align: center;'>Matthew Bowles</div>
<div style='text-align: center;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/certificate_trucking.jpg' alt='TQS llc'/>
                  </main>
                  <footer>
                    <img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/certificate_footer_logo.jpg' alt='Certificate Top'/>
                  </footer>
                </body>
                </html>";

            var htmlLoadOptions = new HtmlLoadOptions();

            using (var htmlStream = new MemoryStream(htmlLoadOptions.Encoding.GetBytes(html)))
            {
                // Load input HTML text as stream.
                var document = DocumentModel.Load(htmlStream, htmlLoadOptions);
                // Save output PDF file.

                document.Save(@"wwwroot/Output.pdf");
            }

            return(View());
        }
 private static IEnumerable<Fields> GetSharedFields(DocumentModel document) 
 {
     var list = new List<Fields>();
     using (UpsilabEntities context = new UpsilabEntities())
     {
         var fetch = context.DocumentModel.Include("Fields").Where(x => x.IdFirmInstitution == document.IdFirmInstitution && x.IdDocumentModel != document.IdDocumentModel).ToList();
         foreach(var doc in fetch) 
         {
             if (doc.Fields != null)
             {
                 var listFields = doc.Fields.ToList();
                 var shared = (from item in listFields where item.IsShared == true select item).ToList();
                 list.AddRange(shared);
             }
         }
     }
     return list;
 }
예제 #37
0
        //Business Logics for Motor Insurance
        private bool RecordNewMotorInsurance(InsuranceModel insurance, ClientModel client, PolicyCoverageDetailModel policyCoverage, DocumentModel document, CoverageModel coverage)
        {
            ValidateAddInsurance validation = new ValidateAddInsurance();
            bool isCorrectAge = validation.ValidateForAge(client.Age);

            //_repository.Create(InsuranceModel insurance, ClientModel client, PolicyCoverageDetailModel policyCoverage, DocumentModel document, CoverageModel coverage);
            throw new NotImplementedException();
        }
 public EditorViewModel(DocumentModel document)
 {
     Document      = document;
     Format        = new FormatModel();
     FormatCommand = new RelayCommand(ToggleWrap);
 }
 public static SignEditeurDocumentModel EntityToModel(DocumentModel entity) {
     var model = new SignEditeurDocumentModel {
         IdDocument = entity.IdDocumentModel,
         IdFirmInstitution = entity.IdFirmInstitution,
         Name = entity.Name,
         DocumentType = entity.DocumentType,
         //HtmlTemplate = entity.HtmlTemplate,
         DateCreated = entity.DateCreated,
         DateModified = entity.DateModified.GetValueOrDefault()
     };
     model.HtmlTemplate = DocumentModelFileBL.GetPdfContentFromFile(entity);
     return model;
 }
예제 #40
0
 protected virtual void LerDocumento(string filePathName)
 {
     document            = DocumentModel.Load(filePathName);
     this.LayoutDocument = LayoutPage.DefinedByDoc;
 }
        private static DocumentModel AddDocumentModel(Guid idFirmInstitutionSDG, SignEditeurDocumentModel model)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                DocumentModel entity = new DocumentModel
                {
                    IdDocumentModel = Guid.NewGuid(),
                    IdFirmInstitution = idFirmInstitutionSDG,
                    DocumentType = model.DocumentType,
                    //HtmlTemplate = model.HtmlTemplate,
                    Name = model.Name,
                    DateCreated = DateTime.Now
                };

                context.DocumentModel.AddObject(entity);

                if (model.Fields != null)
                {
                    foreach (var field in model.Fields)
                    {
                        if (field == null) continue;
                        field.DateCreated = DateTime.Now;
                        field.IdDocumentModel = entity.IdDocumentModel;
                        var fieldEntity = FieldModelToEntity(field);
                        context.Fields.AddObject(fieldEntity);
                    }
                }
                context.SaveChanges();

                DocumentModelFileBL.SavePdfContentToFile(entity, model.HtmlTemplate);

                return entity;
            }
        }
예제 #42
0
        private void CreateAndOpenWordDocument(List <DetailForReport> detailsForReport)
        {
            var reportsDirectoryPath = Directory.GetCurrentDirectory() + "\\reports";

            if (!Directory.Exists(reportsDirectoryPath))
            {
                Directory.CreateDirectory(reportsDirectoryPath);
            }

            int rowCount = detailsForReport.Count;

            ComponentInfo.SetLicense("FREE-LIMITED-KEY");

            var document = new DocumentModel();

            var section = new Section(document);

            document.Sections.Add(section);

            // Create a table with 100% width.
            var table = new Table(document);

            table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
            section.Blocks.Add(table);

            for (int r = 0; r < rowCount; r++)
            {
                // Create a row and add it to table.
                var row = new TableRow(document);
                table.Rows.Add(row);

                // Add detail name
                var cell = new TableCell(document);
                cell.CellFormat.PreferredWidth = new TableWidth(50, TableWidthUnit.Percentage);
                var paragraph = new Paragraph(document, $"{detailsForReport[r].DetailName}");

                cell.Blocks.Add(paragraph);
                row.Cells.Add(cell);

                // Add detail count
                cell = new TableCell(document);
                cell.CellFormat.PreferredWidth = new TableWidth(50, TableWidthUnit.Percentage);
                paragraph = new Paragraph(document, $"{detailsForReport[r].Count} pcs");

                cell.Blocks.Add(paragraph);
                row.Cells.Add(cell);
            }

            var exportTime = DateTime.Now.ToString("dd-MMM-yyyy HH_mm_ss", CultureInfo.InvariantCulture);
            var detailName = SelectedNodeTag.Name;
            var fileName   = $"{detailName} {exportTime}.docx";

            var filePath = $"{reportsDirectoryPath}\\{fileName}";

            document.Save(filePath);

            Process.Start(new ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
예제 #43
0
        public async Task GetAndListOperationsAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleGetAndListOperations

            var client = new DocumentModelAdministrationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Make sure there is at least one operation, so we are going to build a custom model.
#if SNIPPET
            Uri trainingFileUri = new Uri("<trainingFileUri>");
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            BuildModelOperation operation = await client.StartBuildModelAsync(trainingFileUri, DocumentBuildMode.Template);

            await operation.WaitForCompletionAsync();

            // List the first ten or fewer operations that have been executed in the last 24h.
            AsyncPageable <ModelOperationInfo> modelOperations = client.GetOperationsAsync();

            string operationId = string.Empty;
            int    count       = 0;
            await foreach (ModelOperationInfo modelOperationInfo in modelOperations)
            {
                Console.WriteLine($"Model operation info:");
                Console.WriteLine($"  Id: {modelOperationInfo.OperationId}");
                Console.WriteLine($"  Kind: {modelOperationInfo.Kind}");
                Console.WriteLine($"  Status: {modelOperationInfo.Status}");
                Console.WriteLine($"  Percent completed: {modelOperationInfo.PercentCompleted}");
                Console.WriteLine($"  Created on: {modelOperationInfo.CreatedOn}");
                Console.WriteLine($"  LastUpdated on: {modelOperationInfo.LastUpdatedOn}");
                Console.WriteLine($"  Resource location of successful operation: {modelOperationInfo.ResourceLocation}");

                if (count == 0)
                {
                    operationId = modelOperationInfo.OperationId;
                }

                if (++count == 10)
                {
                    break;
                }
            }

            // Get an operation by ID
            ModelOperation specificOperation = await client.GetOperationAsync(operationId);

            if (specificOperation.Status == DocumentOperationStatus.Succeeded)
            {
                Console.WriteLine($"My {specificOperation.Kind} operation is completed.");
                DocumentModel result = specificOperation.Result;
                Console.WriteLine($"Model ID: {result.ModelId}");
            }
            else if (specificOperation.Status == DocumentOperationStatus.Failed)
            {
                Console.WriteLine($"My {specificOperation.Kind} operation failed.");
                ResponseError error = specificOperation.Error;
                Console.WriteLine($"Code: {error.Code}: Message: {error.Message}");
            }
            else
            {
                Console.WriteLine($"My {specificOperation.Kind} operation status is {specificOperation.Status}");
            }
            #endregion
        }
예제 #44
0
        public FileResult CreatePDF(string CertHtml)
        {
            //using (Document document = new Document())
            //{
            //    // step 2
            //    PdfWriter.GetInstance(document, stream);
            //    // step 3
            //    document.Open();
            //    // step 4
            //    document.Add(new Paragraph("Hello World!"));
            //}

            var html = @"
                <html>
                <head>
                
                <style>
                  @page {
                    size: A5 landscape;
                    margin: 6cm 1cm 1cm;
                    mso-header-margin: 1cm;
                    mso-footer-margin: 1cm;
                    
                  }

                  body {
                    background: #FFF;
                    border: 1pt solid black;
                    padding: 20pt;
                    width: 700px;
                  }

                  br {
                    page-break-before: always;
                  }

                  p { margin: 0; }
                  header { color: #000; text-align: center; font-family: 'Tangerine', serif; font-size: 48px;}
                  main { color: #00B050; }
                  footer { color: #0070C0; text-align: right; }
                </style>
                </head>

                <body>
                  <header>
                    <img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/certificate_top.jpg' alt='Certificate Top'/>
                  </header>
                  <main>
<div style='text-align: center;'>Matthew Bowles</div>
<div style='text-align: center;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/certificate_trucking.jpg' alt='TQS llc'/>
                  </main>
                  <footer>
                    <img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/certificate_footer_logo.jpg' alt='Certificate Top'/>
                  </footer>
                </body>
                </html>";

            ComponentInfo.SetLicense("FREE-LIMITED-KEY");

            var htmlLoadOptions = new HtmlLoadOptions();

            using (var htmlStream = new MemoryStream(htmlLoadOptions.Encoding.GetBytes(html)))
            {
                // Load input HTML text as stream.
                // var document = DocumentModel.Load(htmlStream, htmlLoadOptions);
                // Save output PDF file.

                // Build Doc from Scratch
                var     document = new DocumentModel();
                Section section  = new Section(document);
                document.Sections.Add(section);

                document.Content.Start
                .LoadText("<div style='text-align: center;margin-top: 30px;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/title_one.png' alt='Certificate Top' /></div>",
                          new HtmlLoadOptions())
                .LoadText("<div style='text-align: center;font-size: 28px;font-weight: bold;padding: 20px;'>Matthew Bowles</div>", new HtmlLoadOptions())
                .LoadText("<div style='text-align: center;padding: 10px;'>In accordance with Federal Motor Carrier Safety Regulations, Part 382, the above-named company is a member and full participant in a managed drug and alcohol testing program operated by:.</div>", new HtmlLoadOptions())
                .LoadText("<div style='text-align: center;padding: 10px;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/mid_one.png' alt='Certificate Top' /></div>",
                          new HtmlLoadOptions())
                .LoadText("<div style='text-align: center;padding: 10px;'>Trucking Qualifications Services, LLC confirms to the rules set forth in 49 CFR, Part 40, Procedures for the Drug and Alcohol Testing Industry Association and all staff members are certified per the requirements of the federal regulations contained in the Code of Federal Register Part 40.33.</div>", new HtmlLoadOptions())
                .LoadText("<div style='text-align: center;padding: 10px;'>All random selections percentage of at least 50% drug and at least 10% alcohol is being maintained in accordance with these regulations.</div>", new HtmlLoadOptions())
                .LoadText("<table style='width: 100%;' cellpadding='5' cellspacing='5'><tr><td><strong>Trucking Qualifications Services LLC</strong><br>6250 Shiloh Road, Ste. 230<br>Alpharetta, Georgia 30005</td><td style='text-align: right;'>Program Start Date: January 1, 2020<br>Program End Date: December 31, 2020</td></tr></table>", new HtmlLoadOptions())
                .LoadText("<div style='text-align: center;padding-right: 30px;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/slice_bottom.png' alt='Certificate Bottom' /></div>",
                          new HtmlLoadOptions());


                //var section = document.Sections[0];

                //Run run = new Run(document, "<img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/slice_title.png' alt='Certificate Top'/>");
                //paragraph.Inlines.Add(run);

                //section.Blocks[1].Content.Start.LoadText(" Some Prefix ", new CharacterFormat() { Subscript = true });

                // Append text to second paragraph.
                //section.Blocks[1].Content.End.LoadText(" Some Suffix ", new CharacterFormat() { Superscript = true });

                // Insert HTML paragraph before third paragraph.
                //section.Blocks[2].Content.Start.LoadText();

                var pageSetup1 = document.Sections[0].PageSetup;

                // Set page orientation.
                pageSetup1.Orientation = Orientation.Landscape;

                // Set page margins.
                pageSetup1.PageMargins.Top    = 10;
                pageSetup1.PageMargins.Bottom = 0;

                // Set paper type.
                pageSetup1.PaperType = PaperType.Letter;

                document.Save(@"wwwroot/Output.pdf");
            }

            return(File(@"Output.pdf", "application/pdf", "certificate.pdf"));
        }
예제 #45
0
        public static SaveResult Save(DocumentModel document, string style)
        {
            Logger.GetInstance().Debug("Save() >>");

            try
            {
                if (!Directory.Exists(document.Metadata.FilePath + "_temp"))
                {
                    var parentFolder = Directory.CreateDirectory(document.Metadata.FilePath + "_temp").FullName;

                    var mp = new MarkdownParser();
                    // Generate HTML
                    var html = mp.Parse(document.Markdown, style);

                    var markdownFileName = document.Metadata.FileName + ".md";
                    var markdownFilePath = parentFolder + "\\" + markdownFileName;
                    var htmlFileName     = document.Metadata.FileName + ".html";
                    var htmlFilePath     = parentFolder + "\\" + htmlFileName;
                    var xmlFileName      = document.Metadata.FileName + ".xml";
                    var metadataFilePath = parentFolder + "\\" + xmlFileName;
                    // Generate MD file
                    using (var sw = new StreamWriter(markdownFilePath))
                    {
                        sw.Write(document.Markdown);
                    }
                    // Generate HTML file
                    using (var sw = new StreamWriter(htmlFilePath))
                    {
                        sw.Write(html);
                    }
                    // Generate XML file
                    document.Metadata.FilePath = document.Metadata.FilePath;
                    document.Metadata.FileName = document.Metadata.FileName;
                    document.Metadata.IsNew    = false;
                    var gxs = new GenericXmlSerializer <DocumentMetadata>();
                    gxs.Serialize(document.Metadata, metadataFilePath);

                    // Generate the package
                    if (File.Exists(document.Metadata.FilePath))
                    {
                        File.Delete(document.Metadata.FilePath);
                    }
                    ZipFile.CreateFromDirectory(parentFolder, document.Metadata.FilePath);
                    // Update the view
                    var saveResult = new SaveResult
                    {
                        FileName = document.Metadata.FileName,
                        Source   = htmlFilePath.ToUri(),
                        TempFile = document.Metadata.FilePath + "_temp"
                    };

                    Logger.GetInstance().Debug("<< Save()");
                    return(saveResult);
                }

                throw new Exception("Temporary directory already exists");
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #46
0
파일: Printer.cs 프로젝트: taler0n/Students
        public void Print(string filledHtmlTemplate)
        {
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(filledHtmlTemplate));

            DocumentModel.Load(ms, LoadOptions.HtmlDefault).Save(PathToFile + Extension);
        }
예제 #47
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = new DocumentModel();

        int heading1Count = 3;
        int heading2Count = 5;

        // Create and add Heading 1 style.
        ParagraphStyle heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, document);

        document.Styles.Add(heading1Style);

        // Create and add Heading 2 style.
        ParagraphStyle heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, document);

        document.Styles.Add(heading2Style);

        // Create and add TOC style.
        ParagraphStyle tocHeading = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, document);

        tocHeading.Name = "toc";
        tocHeading.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
        document.Styles.Add(tocHeading);

        Section section = new Section(document);

        document.Sections.Add(section);

        // Add TOC title.
        section.Blocks.Add(
            new Paragraph(document, "Contents")
        {
            ParagraphFormat =
            {
                Style = tocHeading
            }
        });

        // Create and add new TOC.
        section.Blocks.Add(
            new TableOfEntries(document, FieldType.TOC));

        section.Blocks.Add(
            new Paragraph(document,
                          new SpecialCharacter(document, SpecialCharacterType.PageBreak)));

        // Add document content.
        for (int i = 0; i < heading1Count; i++)
        {
            // Heading 1
            section.Blocks.Add(
                new Paragraph(document, "Heading 1 (" + (i + 1) + ")")
            {
                ParagraphFormat =
                {
                    Style = heading1Style
                }
            });

            for (int j = 0; j < heading2Count; j++)
            {
                // Heading 2
                section.Blocks.Add(
                    new Paragraph(document, String.Format("Heading 2 ({0}-{1})", i + 1, j + 1))
                {
                    ParagraphFormat =
                    {
                        Style = heading2Style
                    }
                });

                // Heading 2 content.
                section.Blocks.Add(
                    new Paragraph(document,
                                  "GemBox.Document is a .NET component that enables developers to read, write, convert and print document files (DOCX, DOC, PDF, HTML, XPS, RTF and TXT) from .NET applications in a simple and efficient way."));
            }
        }

        // Update TOC (TOC can be updated only after all document content is added).
        var toc = (TableOfEntries)document.GetChildElements(true, ElementType.TableOfEntries).First();

        toc.Update();

        // Update TOC's page numbers.
        // NOTE: This is not necessary when printing and saving to PDF, XPS or an image format.
        // Page numbers are automatically updated in that case.
        document.GetPaginator(new PaginatorOptions()
        {
            UpdateFields = true
        });

        document.Save("TOC.docx");
    }
예제 #48
0
        public override void CreatePackage(string fileName)
        {
            // Загружаем документ
            var document = DocumentModel.Load(DocumentTemplate.ExtractDoc("EnrollmentOrderStatement"));

            // Подготовка стилей
            var underlinedText = new CharacterFormat
            {
                UnderlineColor = Color.Black,
                UnderlineStyle = UnderlineType.Single
            };

            var ec = _claim.EnrollmentClaims.Where(e => e.EnrollmentExceptionOrder == null).FirstOrDefault();

            if (ec == null)
            {
                throw new Exception("Нет приказа о зачислении из которого этот чувак не был бы исключен.");
            }

            // Вставляем текст на закладки
            document.InsertToBookmark("OrderDate",
                                      ((DateTime)ec.EnrollmentProtocol.EnrollmentOrder.Date).ToString("«dd» MMMM yyyy г."));
            document.InsertToBookmark("OrderNumber",
                                      ec.EnrollmentProtocol.EnrollmentOrder.Number,
                                      underlinedText);
            document.InsertToBookmark("TrainingBeginDate",
                                      ((DateTime)ec.EnrollmentProtocol.TrainingBeginDate).ToString("d MMMM yyyy"));
            document.InsertToBookmark("TrainingEndDate",
                                      ((DateTime)ec.EnrollmentProtocol.TrainingEndDate).ToString("d MMMM yyyy г."));
            document.InsertToBookmark("EducationFormName",
                                      ChangeToAccusative(_claim.EnrollmentClaims.First().EnrollmentProtocol.CompetitiveGroup.EducationForm.Name));
            document.InsertToBookmark("FacultyName",
                                      ec.EnrollmentProtocol.Faculty.Name);
            document.InsertToBookmark("DirectionString",
                                      string.Format("Направление подготовки ({0}): {1} {2}",
                                                    ec.EnrollmentProtocol.CompetitiveGroup.EducationProgramType.Name,
                                                    ec.EnrollmentProtocol.CompetitiveGroup.Direction.Code,
                                                    ec.EnrollmentProtocol.CompetitiveGroup.Direction.Name));
            document.InsertToBookmark("TableStringNumber",
                                      ec.StringNumber.ToString());
            document.InsertToBookmark("StudentName",
                                      _claim.Person.FullName);
            document.InsertToBookmark("EnrollmentReason",
                                      ec.EnrollmentProtocol.CompetitiveGroup.FinanceSource.EnrollmentReason);
            document.InsertToBookmark("ClaimNumber",
                                      _claim.Number);
            string totalScore;

            if (_claim.TotalScore > 0)
            {
                totalScore = _claim.TotalScore.ToString();
            }
            else
            {
                totalScore = _claim.MiddleMark.ToString();
            }
            document.InsertToBookmark("TotalScore",
                                      totalScore);
            document.InsertToBookmark("ProtocolInfo",
                                      string.Format("№ {0} от {1}",
                                                    ec.EnrollmentProtocol.Number,
                                                    ((DateTime)ec.EnrollmentProtocol.Date).ToString("dd.MM.yyyy г.")));
            document.InsertToBookmark("StatementDate",
                                      ((DateTime)ec.EnrollmentProtocol.EnrollmentOrder.Date).ToString("dd.MM.yyyy г."));

            document.InsertToBookmark("TrainingPeriod",
                                      _claim.EnrollmentClaims.First().EnrollmentProtocol.TrainingTime.AsPeriod());

            document.Save(fileName, SaveOptions.DocxDefault);
        }
예제 #49
0
        private static DocumentModel GetDocumentHashDictionart(IEnumerable<Detail> data)
        {
            DocumentModel documentModel = new DocumentModel();

            var _docNums = data.Select(doc => new {doc.docNum, doc.hash}).Distinct();
            int i = 1;
            foreach (var detail in _docNums)
            {

                documentModel.DictDoc.Add(detail.docNum,i);
                documentModel.DocList.Add(detail.docNum);
                i++;
            }
            return documentModel;
        }
예제 #50
0
        public static SaveResult SaveAs(DocumentModel document, string style)
        {
            Logger.GetInstance().Debug("SaveAs() >>");

            try
            {
                var saveDialog = new SaveFileDialog
                {
                    CreatePrompt    = true,
                    OverwritePrompt = true,
                    Title           = "Save a PMD file",
                    Filter          = "Project Markdown File | *.pmd"
                };

                var result = saveDialog.ShowDialog();

                if (result != null)
                {
                    if (result == true)
                    {
                        var tempFolder = FolderPaths.TempFolderPath + "\\" + saveDialog.SafeFileName + "_temp";

                        if (Directory.Exists(tempFolder))
                        {
                            Directory.Delete(tempFolder, true);
                        }

                        var parentFolder = Directory.CreateDirectory(tempFolder).FullName;

                        var mp = new MarkdownParser();
                        // Generate HTML
                        var html = mp.Parse(document.Markdown, style);

                        var markdownFileName = saveDialog.SafeFileName + ".md";
                        var markdownFilePath = parentFolder + "\\" + markdownFileName;
                        var htmlFileName     = saveDialog.SafeFileName + ".html";
                        var htmlFilePath     = parentFolder + "\\" + htmlFileName;
                        var xmlFileName      = saveDialog.SafeFileName + ".xml";
                        var metadataFilePath = parentFolder + "\\" + xmlFileName;
                        // Generate MD file
                        using (var sw = new StreamWriter(markdownFilePath))
                        {
                            sw.Write(document.Markdown);
                        }
                        // Generate HTML file
                        using (var sw = new StreamWriter(htmlFilePath))
                        {
                            sw.Write(html);
                        }

                        document.FilePath = saveDialog.FileName;

                        // Generate XML file
                        document.Metadata.FileName = saveDialog.SafeFileName;
                        document.Metadata.IsNew    = false;
                        var gxs = new GenericXmlSerializer <DocumentMetadata>();
                        gxs.Serialize(document.Metadata, metadataFilePath);
                        // Generate the package
                        if (File.Exists(document.FilePath))
                        {
                            File.Delete(document.FilePath);
                        }
                        ZipFile.CreateFromDirectory(parentFolder, saveDialog.FileName);
                        // Update the view
                        var saveResult = new SaveResult
                        {
                            FileName = saveDialog.SafeFileName,
                            Source   = htmlFilePath.ToUri(),
                            TempFile = tempFolder
                        };

                        Logger.GetInstance().Debug("<< SaveAs()");
                        return(saveResult);
                    }
                }

                Logger.GetInstance().Debug("<< SaveAs()");
                return(null);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
 /// <summary>
 /// Récupère les Models en relation avec le model en cours (CPART, CINT, CCOURT, CCOMP)
 /// </summary>
 /// <param name="db"></param>
 /// <param name="documentsModel"></param>
 /// <returns></returns>
 private static List<DocumentModel> GetRelatedModels(UpsilabEntities db, DocumentModel documentsModel) 
 {
     var allDocumentsModel = db.DocumentModel.Include("Fields").Where(x => x.IdFirmInstitution == documentsModel.IdFirmInstitution && x.IdDocumentModel != documentsModel.IdDocumentModel && AllowedDocumentTypes.Contains(x.DocumentType)).ToList();
     return allDocumentsModel;
 }
 private void SetDocumentModel()
 {
     DocumentModel = new DocumentModel();
     DocumentModel.Text = ModelsComposite.DocumentModel.Text;
 }
예제 #53
0
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = new DocumentModel();

        document.DefaultCharacterFormat.Size = 48;

        var section = new Section(document,
                                  new Paragraph(document, "First page"),
                                  new Paragraph(document, new SpecialCharacter(document, SpecialCharacterType.PageBreak)),
                                  new Paragraph(document, "Even page"),
                                  new Paragraph(document, new SpecialCharacter(document, SpecialCharacterType.PageBreak)),
                                  new Paragraph(document, "Odd page"),
                                  new Paragraph(document, new SpecialCharacter(document, SpecialCharacterType.PageBreak)),
                                  new Paragraph(document, "Even page"));

        document.Sections.Add(section);

        // Add default (odd) header.
        section.HeadersFooters.Add(
            new HeaderFooter(document, HeaderFooterType.HeaderDefault,
                             new Paragraph(document, "Default Header")));

        // Add default (odd) footer with page number.
        section.HeadersFooters.Add(
            new HeaderFooter(document, HeaderFooterType.FooterDefault,
                             new Paragraph(document, "Default Footer")));

        // Add first header.
        section.HeadersFooters.Add(
            new HeaderFooter(document, HeaderFooterType.HeaderFirst,
                             new Paragraph(document, "First Header")));

        // Add first footer.
        section.HeadersFooters.Add(
            new HeaderFooter(document, HeaderFooterType.FooterFirst,
                             new Paragraph(document, "First Footer"),
                             new Paragraph(document,
                                           new Field(document, FieldType.Page),
                                           new Run(document, " of "),
                                           new Field(document, FieldType.NumPages))
        {
            ParagraphFormat = new ParagraphFormat()
            {
                Alignment = HorizontalAlignment.Right
            }
        }));

        // Add even header.
        section.HeadersFooters.Add(
            new HeaderFooter(document, HeaderFooterType.HeaderEven,
                             new Paragraph(document, "Even Header")));

        // Add even footer with page number.
        section.HeadersFooters.Add(
            new HeaderFooter(document, HeaderFooterType.FooterEven,
                             new Paragraph(document, "Even Footer"),
                             new Paragraph(document,
                                           new Field(document, FieldType.Page),
                                           new Run(document, " of "),
                                           new Field(document, FieldType.NumPages))
        {
            ParagraphFormat = new ParagraphFormat()
            {
                Alignment = HorizontalAlignment.Right
            }
        }));

        document.Save("Header and Footer.docx");
    }
 public CaseStudyView(DocumentModel model)
 {
     InitializeComponent();
     BindingContext = new CaseStudyViewModel(model, Navigation);
 }
 public DocumentModel RenameDocuemnt(DocumentModel objDocumentModel)
 {
     return(objBusUserLogin.RenameDocuemnt(objDocumentModel));
 }
 /// <summary>
 /// Récupère tous les champs en relation avec le model (inclus les Shared)
 /// </summary>
 /// <param name="db"></param>
 /// <param name="documentsModel"></param>
 /// <returns></returns>
 private static List<Fields> GetAllFields(UpsilabEntities db, DocumentModel documentsModel)
 {
     var resultFields = new List<Fields>();
     var docFields = db.Fields.Where(x => x.IdDocumentModel == documentsModel.IdDocumentModel).ToList();
     resultFields.AddRange(docFields);
     var allDocumentsModel = GetRelatedModels(db, documentsModel); 
     if (allDocumentsModel != null)
     {
         foreach (var dc in allDocumentsModel)
         {
             if (dc.Fields != null)
             {
                 resultFields.AddRange(
                     from item in dc.Fields 
                     where item.IsShared == true && (resultFields.Count(x => x.NameKey == item.NameKey) == 0)
                     select item
                 );
             }
         }
     }
     return resultFields;
 }
예제 #57
0
        private static List<List<string>> PeformConvert(StatusesModel statusesModel,DocumentModel documentModel ,IEnumerable<Detail> details)
        {
            List<List<string>> sheet = new List<List<string>>();
            int statusCount = statusesModel.StatsList.Count;
            // header
            List<string> statuses = new List<string>();
            statuses.Add("");
            statuses.AddRange(statusesModel.StatsList);
            sheet.Add(statuses);
            // инициализация столбца документов
            for (int i = 1; i < documentModel.DictDoc.Count+1; i++)
            {
                List<string> row = new List<string>(new string[statusCount+1]);// +1 так как статусы должны быть смещены вправо на одну клетку.
                row[0] = documentModel.DocList[i-1];
                sheet.Add(row);
            }
            // пошла жара

            foreach (var detail in details)
            {
                try
                {
                int row = documentModel.DictDoc[detail.docNum];
                int column = statusesModel.DictStat[detail.StatusId];
                sheet[row][column] = detail.statDate.ToString();
                }
                catch (Exception)
                {
                    // не придумал чего делать
                    throw;
                }
            }
            return sheet;
        }