|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Text.RegularExpressions; |
| 3 | +using Find_and_replace_placeholders.Models; |
| 4 | +using Microsoft.AspNetCore.Mvc; |
| 5 | +using Syncfusion.DocIO.DLS; |
| 6 | +using Syncfusion.DocIO; |
| 7 | +using Syncfusion.DocIORenderer; |
| 8 | +using Syncfusion.Pdf; |
| 9 | + |
| 10 | +namespace Find_and_replace_placeholders.Controllers |
| 11 | +{ |
| 12 | + public class HomeController : Controller |
| 13 | + { |
| 14 | + private readonly ILogger<HomeController> _logger; |
| 15 | + |
| 16 | + public HomeController(ILogger<HomeController> logger) |
| 17 | + { |
| 18 | + _logger = logger; |
| 19 | + } |
| 20 | + |
| 21 | + public IActionResult Index() |
| 22 | + { |
| 23 | + return View(); |
| 24 | + } |
| 25 | + |
| 26 | + public ActionResult CreateDocument(string firstname, string lastname, string email, string phone, string address) |
| 27 | + { |
| 28 | + //Creating a new document. |
| 29 | + using (WordDocument document = new WordDocument(new FileStream("Data/Template.docx", FileMode.Open, FileAccess.Read), FormatType.Automatic)) |
| 30 | + { |
| 31 | + // Store inputs in a 1D array |
| 32 | + string[] userInputs = { firstname, lastname, email, phone, address }; |
| 33 | + // Find all placeholders like "{{Name}}" |
| 34 | + TextSelection[] selections = document.FindAll(new Regex(@"\{(.*)\}")); |
| 35 | + for (int i = 0; i < selections.Count(); i++) |
| 36 | + { |
| 37 | + TextSelection selection = selections[i]; |
| 38 | + //Replace the text with user values |
| 39 | + document.Replace(selection.SelectedText, userInputs[i], false, true); |
| 40 | + } |
| 41 | + //Instantiation of DocIORenderer for Word to PDF conversion |
| 42 | + using (DocIORenderer render = new DocIORenderer()) |
| 43 | + { |
| 44 | + //Converts Word document into PDF document |
| 45 | + PdfDocument pdfDocument = render.ConvertToPDF(document); |
| 46 | + |
| 47 | + //Saves the PDF document to MemoryStream. |
| 48 | + MemoryStream stream = new MemoryStream(); |
| 49 | + pdfDocument.Save(stream); |
| 50 | + stream.Position = 0; |
| 51 | + |
| 52 | + //Download PDF document in the browser. |
| 53 | + return File(stream, "application/pdf", "Sample.pdf"); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public IActionResult Privacy() |
| 59 | + { |
| 60 | + return View(); |
| 61 | + } |
| 62 | + |
| 63 | + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] |
| 64 | + public IActionResult Error() |
| 65 | + { |
| 66 | + return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments