Ejemplo n.º 1
0
        public void WikiExample01()
        {
            // Read a Word template with content controls.
            // var templateBytes = File.ReadAllBytes("./template.docx");
            // ... or uncomment the following lines to read a ready sample template
            var templateUrl = "https://github.com/pkokki/DocumentCreator/blob/0.2.0-alpha/DocumentCreator.Tests/Resources/CreateDocument.docx?raw=true";

            using var webClient = new System.Net.WebClient();
            var templateBytes = webClient.DownloadData(templateUrl);

            // Create a stream containing the Word template
            var template = new MemoryStream(templateBytes);

            // Optionally read an Excel that contains the mappings (transformations)
            //var mappingBytes = File.ReadAllBytes("./mappings.xslm");
            // ... or uncomment the following lines to read a ready sample
            var mappingsUrl  = "https://github.com/pkokki/DocumentCreator/blob/0.2.0-alpha/DocumentCreator.Tests/Resources/CreateDocument.xlsm?raw=true";
            var mappingBytes = webClient.DownloadData(mappingsUrl);

            // Create a stream containing the mappings
            var mapping = new MemoryStream(mappingBytes);

            // Read the input source from a json file
            //var jsonText = File.ReadAllText("./payload.json");
            // ... or uncomment the following lines to read a ready json
            var jsonUrl  = "https://github.com/pkokki/DocumentCreator/blob/0.2.0-alpha/DocumentCreator.Tests/Resources/CreateDocument.json?raw=true";
            var jsonText = webClient.DownloadString(jsonUrl);

            // Create a JObject from the input source
            var json = JObject.Parse(jsonText);

            // Create the document payload
            var payload = new DocumentPayload()
            {
                Sources = new EvaluationSource[]
                {
                    new EvaluationSource()
                    {
                        // The name corresponds to the source identifier
                        // in the mappings file
                        Name    = "RQ",
                        Payload = json
                    }
                }
            };

            // Create a document processor
            var processor = new DocumentProcessor(null, null);

            // Generate the new document
            var document = processor.CreateDocument(template, mapping, payload);

            // Save the document
            using FileStream output = File.Open("./document.docx", FileMode.Create);
            document.CopyTo(output);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Helper method used from the Upload Endpoint in order to communicate with the corresponding Endpoint of the Legacy API.
        /// </summary>
        /// <param name="documentPayload">The document that should be uploaded.</param>
        /// <returns></returns>
        private async Task <ResponseMessageResult> InternalUpload(DocumentPayload documentPayload)
        {
            var          client  = new HttpClient();
            const string appJson = "application/json";

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(appJson));
            var strContent     = new StringContent(JsonConvert.SerializeObject(documentPayload), Encoding.UTF8, appJson);
            var uri            = LegacyServiceUrlFactory.Create(LegacyServiceEndpoint.Upload);
            var legacyResponse = await client.PostAsync(uri, strContent);

            Func <string, UploadFileResponse> okFuncContent = JsonConvert.DeserializeObject <UploadFileResponse>;

            return(await HandleLegacyResponse(legacyResponse, okFuncContent));
        }
        public async Task <IActionResult> CreateDocument([FromRoute] string templateName,
                                                         [FromRoute] string mappingName,
                                                         [FromBody] DocumentPayload payload)
        {
            var document = await processor.CreateDocument(templateName, mappingName, payload);

            var fileContents = document.Buffer.ToMemoryStream();
            var contentType  = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return(new FileContentResult(fileContents.ToArray(), contentType)
            {
                FileDownloadName = document.FileName
            });
        }
Ejemplo n.º 4
0
        public Stream CreateDocument(Stream templateBytes, Stream mappingBytes, DocumentPayload payload)
        {
            var         templateFields = OpenXmlWordProcessing.FindTemplateFields(templateBytes);
            MappingInfo mappingInfo;

            if (mappingBytes != null)
            {
                mappingInfo = OpenXmlSpreadsheet.GetMappingInfo(mappingBytes, payload.Sources);
            }
            else
            {
                mappingInfo = OpenXmlSpreadsheet.BuildIdentityExpressions(templateFields, payload.Sources);
            }
            var results            = CreateDocumentInternal(templateFields, mappingInfo.Expressions, mappingInfo.Sources);
            var contentControlData = BuildContentControlData(templateFields, results);

            return(OpenXmlWordProcessing.MergeTemplateWithMappings(contentControlData, templateBytes));
        }
Ejemplo n.º 5
0
        public async Task <IHttpActionResult> Upload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return(BadRequest("Not Mime Multipart Content"));
            }
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.Contents.FirstOrDefault();

            if (file == null)
            {
                return(BadRequest("The request doesn't contains any file"));
            }
            var contentType = file.Headers.ContentType.MediaType;
            var content     = await file.ReadAsByteArrayAsync();

            var documentPayload = new DocumentPayload(contentType, content);
            var uploadResponse  = await InternalUpload(documentPayload);

            if (uploadResponse.Response.StatusCode != HttpStatusCode.OK)
            {
                return(uploadResponse);
            }
            var uploadedFile = ((ObjectContent)uploadResponse.Response.Content).Value as UploadFileResponse;

            if (uploadedFile != null)
            {
                var publishMessageTpAwsTask = PublishMessageToAws(uploadedFile);
                var insertDocumentTask      = _documentRepo.InsertDocument(
                    new DocumentEntity
                {
                    Id     = new Guid(uploadedFile.Id),
                    Link   = uploadedFile.Url,
                    Name   = file.Headers.ContentDisposition.FileName,
                    UserId = 1     // Normally this would be the user id
                });
                await Task.WhenAll(publishMessageTpAwsTask, insertDocumentTask);
            }
            return(Ok("File Uploaded"));
        }
Ejemplo n.º 6
0
        public void CanCreateDocument()
        {
            var wordBytes  = new MemoryStream(Resources.create_document_docx, true);
            var excelBytes = new MemoryStream(Resources.create_document_xlsm, true);
            var payload    = new DocumentPayload()
            {
                Sources = new List <EvaluationSource>()
                {
                    new EvaluationSource()
                    {
                        Name = "RQ", Payload = JObject.Parse(Resources.create_document_json)
                    }
                }
            };

            var processor = new DocumentProcessor(null, null);
            var docStream = processor.CreateDocument(wordBytes, excelBytes, payload);


            Assert.NotEqual(0, docStream.Length);
            using FileStream output = File.Open("./Output/CreateDocumentTest.docx", FileMode.Create);
            docStream.CopyTo(output);
        }
Ejemplo n.º 7
0
        public async Task <DocumentDetails> CreateDocument(string templateName, string mappingName, DocumentPayload payload)
        {
            var template = repository.GetLatestTemplate(templateName);

            Stream mappingBytes = null;

            if (mappingName != null)
            {
                var mapping = repository.GetLatestMapping(templateName, null, mappingName);
                mappingBytes = mapping.Buffer;
            }
            var documentBytes = CreateDocument(template.Buffer, mappingBytes, payload);
            var document      = await repository.CreateDocument(templateName, mappingName, documentBytes);

            if (htmlRepository != null)
            {
                var pageTitle  = template.Name;
                var conversion = OpenXmlWordConverter.ConvertToHtml(document.Buffer, pageTitle, document.Name);
                htmlRepository.SaveHtml(document.Name, conversion.Html, conversion.Images);
            }
            return(TransformFull(document));
        }
 public async Task <IActionResult> CreateDocument([FromRoute] string templateName,
                                                  [FromBody] DocumentPayload payload)
 {
     return(await CreateDocument(templateName, null, payload));
 }