public IActionResult DownloadDeal([FromRoute] int id) { var result = new LogisTicketItem(); try { //result = _profileService.GetTicket(UserId, id); } catch { //return Error("No found deal"); } var templateName = $"deal_{Enum.GetName(typeof(WarrantyType), result.warranty_id)}_template_qr.docx"; var templatePath = Path.Combine(_hostingEnvironment.WebRootPath, "reports", templateName); var savePath = Path.Combine(_hostingEnvironment.WebRootPath, "tmp", $"{Guid.NewGuid()}_{templateName}"); try { var tokenUrl = "test-url"; result.DownloadDeal(templatePath, savePath, tokenUrl, _hostingEnvironment); var bytes = System.IO.File.ReadAllBytes(savePath); return(File(bytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Path.GetFileName(savePath))); } catch (Exception ex) { ///return Error(ex.Message); } finally { try { System.IO.File.Delete(savePath); } catch { } } }
public static void DownloadDeal(this LogisTicketItem item, string templatePath, string savePath, string tokenUrl, IHostingEnvironment environment) { File.Copy(templatePath, savePath, true); var fields = typeof(LogisTicketItem).GetProperties().ToDictionary(a => a.Name.Replace("_", ""), a => { var obj = a.GetValue(item, null); var result = ""; switch (Type.GetTypeCode(a.PropertyType)) { case TypeCode.DateTime: result = Convert.ToDateTime(obj).ToString("dd.MM.yyyy", CultureInfo.InvariantCulture); break; case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Single: result = AsFormat((decimal?)obj); break; default: result = EscapeXml($"{obj}"); break; } return(result); }); using (var wordDoc = WordprocessingDocument.Open(savePath, true)) { var mainPart = wordDoc.MainDocumentPart; //replacer var docText = ""; using (var sr = new StreamReader(mainPart.GetStream())) { docText = sr.ReadToEnd(); } foreach (var field in fields.OrderByDescending(a => a.Key)) { docText = Regex.Replace(docText, field.Key, field.Value, RegexOptions.IgnoreCase); } //save using (var sw = new StreamWriter(mainPart.GetStream(FileMode.Create))) { sw.Write(docText); } //image var pictureElem = mainPart.Document.Body.Descendants <Text>().Where(x => x.Text == "qrcode").FirstOrDefault(); var imagePart = mainPart.AddImagePart(ImagePartType.Png); using (var stream = new MemoryStream()) { //qr generator var qrGenerator = new QRCodeGenerator(); var qrCodeData = qrGenerator.CreateQrCode(tokenUrl, QRCodeGenerator.ECCLevel.Q); var qrCode = new QRCode(qrCodeData); var logoPath = Path.Combine(environment.WebRootPath, "logo.png"); var qrCodeImage = qrCode.GetGraphic(20, System.Drawing.Color.Black, System.Drawing.Color.White, (System.Drawing.Bitmap)System.Drawing.Image.FromFile(logoPath), 25); //save to stream qrCodeImage.Save(stream, ImageFormat.Png); //back to start position stream.Position = 0; //pass to doc imagePart.FeedData(stream); } AddImage(pictureElem, mainPart.GetIdOfPart(imagePart)); pictureElem.Remove(); wordDoc.Save(); } }