With ASP.NET MVC, I generated an html page
Example: http://example1234.com/Persons/details/15
Changing the last digit changes the value of the fields which I imported with @HTML
helpers
I would like to automatically save this page somewhere to the server, to make it static.
Something like PersonNr15.html
with the generated content hardcoded into that page.
@model MvcApplication3.Models.Person
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>Person</legend>
<p>@Html.DisplayFor(model => model.FirstName)</p>
<p>@Html.DisplayFor(model => model.LastName)</p>
</fieldset>
What you need to do is render the view to a string, and then save the string to a file like you would any other string. The rendering of an MVC view to a string is covered in previously answered questions on here such as This question
I changed my code myself. I used my self-made template, and changed the words like #NAME# After changing the variable words from the file, save the file, make a PDF out of it. and done. (PDF wasn't part of the question, but i added it in for those interested).
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Person person)
datadir = ConfigurationManager.AppSettings["datadir"];
//datadirectory defined in Web.config
//also possible to hardcode it here, example: "c:/windows/PDFfolder"
wkhtmltopdf = ConfigurationManager.AppSettings["wkhtmltopdf"];
//directory to the file "wkhtmltopdf", downloaded it somewhere
//just like above, defined at web.config possible to hardcode it in
ViewData["IsModelValid"] = ModelState.IsValid ? "true" : "false";
//valid checker
if (ModelState.IsValid) //check if valid
{
db.People.Add(person); //add to db
db.SaveChanges();
var fileContents1 = System.IO.File.ReadAllText(datadir + "Template.html");
//get template from datadirectory
fileContents1 = fileContents1.Replace("#NAME#", person.Name);
//replace '#NAME#' by the name from the database table person.Name
System.IO.File.WriteAllText(datadir + "tmp\\Template." + person.ID + ".html", fileContents1);
//create a new html page with the replaced text
//name of the file equals the ID of the person
var pdf1 = new ProcessStartInfo(wkhtmltopdf); //start process wkhtmltopdf
pdf1.CreateNoWindow = true; //don't create a window
pdf1.UseShellExecute = false; //don't use a shell
pdf1.WorkingDirectory = datadir + "tmp\\"; //where to create the pdf
pdf1.Arguments = "-q -n --disable-smart-shrinking Overeenkomst." + person.ID + ".html Overeenkomst." + person.ID + ".pdf";
//get the html to convert and make a pdf with the same name in the same directory
}
return View(person);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.