I am trying to generate a pdf from an HTML string. To create an HTML string I have converted the cshtml to a string using the following code.
protected override void ExecuteCore() { }
public static string RenderViewToString(string controllerName, string viewName, object viewData)
{
using (var writer = new StringWriter())
{
var routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new HomeController());
var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);
var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
razorViewResult.View.Render(viewContext, writer);
return writer.ToString();
}
}
I am calling this method:
var str = HomeController.RenderViewToString("Home", "Pdf", name);
when there is HTML only in the cshtml this method renders the HTML properly and I am able to convert that to Pdf without any error.
But I have to generate the HTML dynamically, so I used Vue js 3 to render the HTML.
After using the vue js RenderViewToString is not able to generate the HTML (though no error), but in the output it returns the variable name as it is.
RenderViewToString returns the following html string:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel="stylesheet" type="text/css">
<title>Hello, world!</title>
<style>
body {
font-family: arial, helvetica, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: #000000;
background-color: #ffffff;
}
</style>
<script src="https://unpkg.com/vue#3"></script>
</head>
<body>
<div id="app">
<div class="container-fluid p-4">
<div id="message"></div>
{{message}}
<todo-item></todo-item>
</div>
</div>
<script type="text/javascript">
const {
createApp
} = Vue
// Create Vue application
const app = Vue.createApp({
data() {
return {
message: 'Hello Vue!'
}
}
})
// Define a new component called todo-item
app.component('todo-item', {
template: `<li>This is a todo</li>`
})
// Mount Vue application
app.mount("#app");
</script>
</body>
</html>
Can this be made workable? Or this is not a right way to do this thing?
Related
Hello I am actually generating a html file from cshtml template for reporting purpose.
The issue is when i use cdn link for bootstrap in the cshtml file the html rendered got all the css i designed but when using a local access of bootstrap it the style is not rendered at all its also the same thing when trying to render images from local file.
Here is the code for generating the html file:
var httpContex = new DefaultHttpContext
{
RequestServices=_serviceProvider
};
var actionContext = new ActionContext(httpContex, new RouteData(), new ActionDescriptor());
await using var outputWriter = new StringWriter();
var viewResutl = _viewEngine.FindView(actionContext, templateFileName, false);
var viewDictionnary = new ViewDataDictionary<TViewModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = viewModel
};
var tempDataDictionnary = new TempDataDictionary(httpContex, _tempDataProvider);
if (!viewResutl.Success)
{
throw new KeyNotFoundException($"could not render the HTML,because {templateFileName} template does not exist");
}
try
{
var viewContext = new ViewContext(actionContext, viewResutl.View, viewDictionnary, tempDataDictionnary, outputWriter, new HtmlHelperOptions());
await viewResutl.View.RenderAsync(viewContext);
return outputWriter.ToString();
}
catch(Exception ex)
{
_logger.LogError(ex, "Could not render the HTML because of an error");
return string.Empty;
}
Here is part of the cshtml file :
#model XXXXXReporter.ViewModels.XXXXXModel
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>#Model.title</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
<link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/>
</head>
<body style="min-height:100vh">
<div class="container-fluid" >
<div class="row">
<div class="col">
<h2 class="text-center">XXXX Advanced Reporting System</h2>
</div>
<div class="col">
<img src="~/XXXXlogo.png" alt="ANY IMAGE" />
</div>
</div >
<div class="row border border-info border-2 rounded bg-info" style="margin-top: 200px;">
<h3 class="text-center text-white">General Availabilty And Sensor Status[PRTG]</h3>
</div>
<div class="row " style="margin-top: 200px;">
<p>Period Time:<span>All Period</span></p>
<p>Report By:<span>XXXX</span></p>
<p>Creation Date:<span>#DateTime.Now</span></p>
</div>
<div class="row" style="margin-top: 430px;">
#foreach (var elem in Model.panelList)
{
#Html.Raw(elem)
}
</div>
</body>
</html>
This line of code <link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/> is never generated when the html is rendered (by commenting the cdn link above it)
The project is a .net Core Web API i have overiden the use of static file using this code in startup.cs:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, #"StaticFiles")),
RequestPath = "/StaticFiles"
});
As stated in my previous question bootstrap and css not working with .net core api i think the problem is with the way razor render the html.
Is there a way to make it render the static file I pass in the cshtml file?or is there a correct way to generate html from a template using .net core API?
Regards,
Thanks for all your answer.
It was caused by puppeteersharp who was unable to serve the static file.
For the CSS i am using await page.AddStyleTagAsync(new AddTagOptions { Path = "StaticFiles/bootstrap.min.css" }); to inject the css to the page.
For the static image I am encoding it to base64 to make it displayable from there.
I have the following HTML code that is being displayed in a WebBrowser control:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Welcome</title>
<style type="text/css">
/*<![CDATA[*/
body {
font: 8pt Verdana;
background: ThreeDFace;
}
#appname {
line-height: 1;
}
#appname h1 {
margin: 0;
font: bold 10pt Verdana;
}
#appname p {
margin: 0;
}
#actions_list {
list-style-type: none;
padding: 0;
}
/*]]>*/
</style>
<script type="text/javascript">
//<![CDATA[
var ACTION_NEWPROJECT = 0x0001;
var ACTION_NEWFILE = 0x0002;
var ACTION_OPENPROJECT = 0x0003;
var ACTION_OPENFILE = 0x0004;
//]]>
</script>
</head>
<body>
<div id="appname">
<h1>Application</h1>
<p>Slogan</p>
</div>
<div id="actions">
<ul id="actions_list">
<li>New project</li>
<li>New file</li>
<li>Open project</li>
<li>Open file</li>
</ul>
</div>
<div id="recentfiles">
<p>Recent files:</p>
<ul id="recentfiles_list"></ul>
</div>
<script type="text/javascript">
//<![CDATA[
window.onload = function() {
var recentFiles = window.external.GetRecentFiles();
var recentFilesDOMContainer = document.getElementById("recentfiles_list");
for (var i = 0; i < recentFiles.length; i++) {
var index = 0+i;
var fileDOMParent = window.document.createElement("li");
var fileDOMElement = window.document.createElement("a");
fileDOMElement.href = "#";
fileDOMElement.onclick = function() {
window.external.OpenRecentFile(index);
return false;
};
fileDOMElement.innerText = recentFiles[i];
fileDOMParent.appendChild(fileDOMElement);
recentFilesDOMContainer.appendChild(fileDOMParent);
}
};
//]]>
</script>
</body>
</html>
To communicate with the application I am using the WebBrowser.ObjectForScripting property so I can access a class with functions via window.external. That is also working perfectly.
But when I try to open the page below I get the following error:
Script Error
Line: 61
Char: 25
Error: Function expected
Code 0
Why is this happening? It seems to occur at the for loop.
the only thing I can think of is that recentFiles does not have an array in it. Did you try opening the developer console and typing in recentFiles to see what it contains? :)
I was searching some examples and articles related to saving and loading a route into a bing map but i couldn't find anything, so currently i am asking if this is possible.
Please let me know if this is supported by the bing maps for windows phone.
I used to use bing map api on my web
I`m not sure if it will work well
initialize the map using the following code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">`<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
function GetMap()
{
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road });
}
</script>
</head>
<body onload="GetMap();">
<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>
</body>
</html>`
add code to make the route request when the button is clicked, and add code to the RouteCallback function to set the map view and draw the route.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
function GetMap()
{
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road });
}
function ClickRoute(credentials)
{
map.getCredentials(MakeRouteRequest);
}
function MakeRouteRequest(credentials)
{
var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + document.getElementById('txtStart').value + "&wp.1=" + document.getElementById('txtEnd').value + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
CallRestService(routeRequest);
}
function RouteCallback(result) {
if (result &&
result.resourceSets &&
result.resourceSets.length > 0 &&
result.resourceSets[0].resources &&
result.resourceSets[0].resources.length > 0) {
// Set the map view
var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
map.setView({ bounds: viewBoundaries});
// Draw the route
var routeline = result.resourceSets[0].resources[0].routePath.line;
var routepoints = new Array();
for (var i = 0; i < routeline.coordinates.length; i++) {
routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
}
// Draw the route on the map
var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});
map.entities.push(routeshape);
}
}
function CallRestService(request)
{
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
</script>
</head>
<body onload="GetMap();">
<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>
<input id="txtStart" type="text" value="Seattle"/>
<input id="txtEnd" type="text" value="Portland"/>
<input type="button" value="Calculate Route" onclick="ClickRoute()"/>
</body>
</html>
I want to capture an image from webcam and save on server or send through ajax. And which would be better option from both and why ? Any available information is welcome. Thanks in advance
You can easily do this by following these steps
Step #1
Download Javascript Webcam project from Here
Step #2
Extract solution and add this complete solution with your existing asp.net mvc application using
Add Exiting Project
Step #3
Open basic.html from demo folder replace with this
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<!-- A button for taking snaps -->
<form>
<input type=button id="takeshot" value="Take Snapshot" onClick="take_snapshot()">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
window.onload = function () {
setInterval(function () { take_snapshot() }, 5000);
}
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img id="base64image" src="' + data_uri + '"/>';
});
var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "http://localhost:26792/home/SaveImage",
type: "POST",
data: formdata,
processData: false,
contentType: false
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1 /jquery.min.js"></script>
</body>
</html>
Step #4
Replace Home controller with
public class HomeController : Controller
{
public ActionResult Index()
{
string[] allimage = System.IO.Directory.GetFiles(Server.MapPath("~/Content/Images/"));
if (allimage.Length>0)
{
List<string> base64text = new List<string>();
foreach (var item in allimage)
{
base64text.Add(System.IO.File.ReadAllText(item.ToString()));
}
ViewBag.Images = base64text;
}
return View();
}
[HttpPost]
public void SaveImage(string base64image)
{
System.IO.File.WriteAllText(Server.MapPath("~/Content/Images/" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".txt"), base64image);
}
}
Finally replace Index.html with
<h2>Capture images</h2>
#foreach (var item in ViewBag.Images)
{
<img src="#item" />
}
Note
This code
will capture photo from webcam after every 5 second and save it to server as text file consist of base64 encode then Index action read them and and display as img src.
WebRTC standard + using WebSockets / AJAX.
How to load kml file in Google Map using code?
(C#, javascript, .Net)
I successfully integrated kml files in JavaScript
In code below replace your kml name
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title> Google Maps JavaScript API v3 Example: KmlLayer KML Features</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize () {
var myLatlng = new google.maps.LatLng(40.65, -73.95);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions);
var nyLayer = new google.maps.KmlLayer(
'https://sites.google.com/site/test/test/test.kml',
{ suppressInfoWindows: true,
map: map
});
google.maps.event.addListener(nyLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.description;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content_window');
sidediv.innerHTML = text;
}
}
</script>
</head>
In body add these lines
<body onload="initialize()">
<div id="map_canvas" style="width:79%; height:100%; float:left"></div>
<div id="content_window" style="width:19%; height:100%; float:left"></div>
</body>
</html>