user capture div as image and save to computer - javascript

I have a Div on my site, I want to place a button/link (or other things of the sort) that when clicked will save the div and all its contents to the users computer, much like the printing code which is used to print divs. I'm a coding novice so all help will be apreciated.

There is a browser support limit doing this. HTML2Canvas can render your HTML content into a canvas element. Then you can use canvas.toDataURL("image/png"); (docs in MDN) method to export the canvas element to an jpeg or png image.
It's not widely supported but it's still possible.

Easy way
var MyDiv1 = document.getElementById('DIV1');
var MyDiv3 = document.getElementById('DIV2');
MyDiv3.innerHTML = MyDiv1.innerHTML;
html2canvas(MyDiv3, {
useCORS: true,
onrendered: function (canvas) {
var dataUrl = canvas.toDataURL("image/png");
document.getElementById("HiddenField1").value = dataUrl;
}
});
use a button and call ur hidden field value
ButtonClick1()
{
string imgval = HiddenField1.Value;
imgval = imgval.Replace("data:image/png;base64,", "");
byte[] imgData = Convert.FromBase64String(imgval);
using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(imgData)))
{
String path = Server.MapPath("~/imgFolder");
image.Save(path + "\\output.jpg", ImageFormat.Jpeg); // Or Png
}
}

Assuming you want a text or HTML file, not an image file like a screen shot, JavaScript by itself can't initiate a "Save" dialog on a web browser, only a response from a web request to a server will do so.
To start with, you'll need a form with your button and a hidden field:
<div id="saveme">stuff to save</div>
<form action="saveme.aspx" method="POST">
<input type="submit" onclick="prepsave()">
<input type="hidden" id="savemepost">
</form>
And you need some Javascript to save the DIV contents to the hidden field before submittal:
<script>
function prepsave() {
document.getElementById("savemepost").value =
document.getElementById("saveme").innerHTML;
return true;
}
</script>
On the server, you'll need some code to accept the text and spit it back out in the form of a file attachment:
<script runat="server">
Response.Clear()
Response.AddHeader("content-disposition","attachment; filename=saved.html")
Response.Write(Request.Form("savemepost"))
</script>
Caveat #1: There are probably some minor bugs in there and plenty of room for improvement, this is just a proof of concept.
Caveat #2: The server-side code above is potentially insecure, as it allows any web page to control content going to the user's web browser from your domain. You'll need to add some measures to protect this from being abused.

Related

can javascript select a user's image to insert on a webpage without uploading to a server?

I have an X3D page with some solid primitives. I want the user to be able to select her own image to be used as a texture, but I want the page to be all client side.
Can JavaScript insert an image into the HTML without uploading the image to a server? I have a vague memory of seeing this option somewhere. The image was changed to a PNM and inserted as text and then reconverted to an image for display/processing. I cannot find a reference anywhere and I may be using the wrong search terms. There are webpages (i think) that ask for an image to be selected for display without ever uploading. What is this function/script called?
Has some other js function been developed that does this more efficiently?
Have I gone mad?
JavaScript does this all the time with text. fill out a form and see the text right there.
My example X3D is below.
enter code here
enter code here
enter code here
enter code here <shape>
<appearance>
<material diffuseColor='0.5 0.2 1.0'> </material>
<ImageTexture url=' "THE_CLIENT_IMAGE.png" '></ImageTexture>
</appearance>
<sphere radius="3" > </sphere>
</shape>
</Transform>
Working snippet:
const img = document.querySelector('#img')
document.querySelector('#file').addEventListener('input', event => {
if (event.target.files.length === 0) {
console.error('No file provided')
return
}
const reader = new FileReader()
reader.addEventListener('loadend', () => {
img.src = reader.result
})
reader.readAsDataURL(event.target.files[0])
})
<input type="file" id="file">
<img id="img">
Change <img> to ImageTexture and done

Button not showing in Plone, onclick also not working

I am editing a plone page to open an Excel document on a specific sheet. I created two buttons to see if either would appear as actual buttons and use the JS function I reference. With this code the exact part of the page looks like the image below.
Why is only text showing instead of the button and why is the onclick attribute not working?
Note: I have changed to links to the spreadsheet for posting it on here but the link has been tested on other webpages
<script type="text/javascript">
function Open_Excel_File(path,sheet)
{
fso = new ActiveXObject("Scripting.FileSystemObject");
if (!fso.FileExists(path))
alert("Cannot open file.\nFile '" + path + "' doesn't exist.");
else
{
var myApp = new ActiveXObject("Excel.Application");
if (myApp != null)
{
myApp.visible = true;
Book = myApp.workbooks.open(path);
var excel_sheet = Book.Worksheets(sheet).Activate;
myApp.range(f_range).Select;
}
else {
alert ("Cannot open Excel application");
}
}
}
</script>
<div>
<button onclick='Open_Excel_File("file://///fs-01\Departments\Underwriting\Statistical%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%\Cancer%20Statistics%.xlsx", "Vulvar Ca");'>Open File</button>
<input type="button" onclick="Open_Excel_File('file://///fs-01\deps\uw\stat%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%202018\Cancer%20Statistics%.xlsx', 'VCA');'>OPEN FILE</input>
</div>
your onclick value is not a function, it is the result of a function call. Try to change that to onclick="Open_Excel_File"; You'll have to provide the file path at some point
Accessing file system from browser is super restricted for security matters, the only way I see fit is to have a file input and using what user provides
Also Plone filter out a bounce of potential "nasty" tags through a specific configurable tool.
It seems to me that you have injected the in the source HTML of a Page (document) type.
If so, you will see in your browser that in, the page source code, the script tag has been totally stripped away.
So,
a correct way to inject some js in your page, is to load it as portal_javascript resource (plone<=4) or in resource_registry (plone>=5).
tha nasty way is to access, in the ZMI, at https://yourseite:8080/Plone/portal_transforms/safe_html/ and configure it to accept script tags inside a document (all document in your site actually).
If this answer does not satisfy you try to ask in the official community:
http://community.plone.org
hth,
alessandro

anyway to check that a img tag is broken or 404'd; without add'l network request

I am using CasperJS to scrape some items, so I can't get on the page early enough to add load and error events on img tags. I would also prefer to not have to do a new XHR request for each image to determine it's validity.
Is there any way to select an image tag and determine if there is an image actually there or if it is not in which the alt text is displayed? JS only, after the page is fully loaded.
This is NOT A DUPLICATE. I am specifically asking if there is a way to do this without another network request. Other questions only have answers that require creating a new image with a new source and thus another network request.
/ Edit
Specifically looking for asserting if am image is loaded after it is complete (document.querySelector('#myImage').complete // returns true:
No new network request (includes creating a new image with a new source)
No onload/onerror events (requires doing so before page is loaded)
Assert that #myImage is broken without the above
I don't know how exactly you would use it , but here is the code snippet from w3schools.
<!DOCTYPE html>
<html>
<body>
<p>This example uses the HTML DOM to assign an "onerror" event to an img element.</p>
<img id="myImg" src="image.gif">
<p id="demo"></p>
<script>
document.getElementById("myImg").onerror = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "The image could not be loaded.";
}
</script>
</body>
</html>
With a bit of working, I was able to find two methods that seem to work:
HTML
<img id="imageA" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
<img id="imageB" src="https://www.google.com/broken.png">
Setup
var imageA = document.querySelector('#imageA');
var imageB = document.querySelector('#imageB');
console.log(imageIsValid(imageA)); // returns true
console.log(imageIsValid(imageB)); // returns false
JavaScript Method 1
function imageIsValid(img) {
return !!img.naturalHeight && !!img.naturalWidth;
}
The natural height and width of broken images will always be 0.
https://jsfiddle.net/2xLsenpp/
JavaScript Method 2
function imageIsValid(img) {
if (img.complete) {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
try {
context.drawImage(img, 0, 0);
return true;
} catch(e) {
return false;
}
}
return false;
}
https://jsfiddle.net/8gdp8nzw/

How to show multiple page `.tif` file on Internet Explorer?

My requirement is to show .tiff image on browser. So currently I'm showing tiff file on Internet Explore using img tag like below.
<img src="myTiff.tif" type="image/tiff" alt="My Tiff">
And it works perfect with the tif file having only single page. In case there would an multiple pages in .tif then the img tag only shows 1st image. User can not get option to view other image.
Sample tiff image
I already tried all the option suggested here
I'm using C# on server side & on front end using AngularJS. Any help would appreciated. Thanks :)
Edit
Would it be better way to go with AltraTiff plugin? I looks like working on Internet Explorer.
Content rendering is always browser's responsibility so you rely in its capabilities.
Maybe there is some plugin for some browser that supports multiple-page tiffs, but, if you can't control software installed in your clients, I think your best option would be to implement some pagination by separating pages server side.
You can achieve that easily with imagemagick.
The only drawback is that, if user try to download it, it will download only the single page he were currently viewing.
But yo can mitigate it by providing separate download link or, simply, linking full version to the displayed image. Example using jQuery:
<div id="tiffPager">
<a href="myTiff.tif">
<img width=200 height=200 data-pageCount=5 src="myTiff_page0.tif" alt="My Tiff">
</a>
<button class="pageBack"><<</button>
<button class="pageForward">>glt;</button>
</div>
<script>
$(function(){
var container = $("div#tiffPager");
var img = $("img", container);
var backBtn = $("button.pageBack", container);
var fwBtn = $("button.pageForward", container);
var pgCount = img.data("pageCount");
var currPage = 0;
backBtn.on("click", function(){
currPage = (currPage + 1) % pgCount; // Cycle though pages.
img.attr("src", "myTiff_page" + currPage + ".tif");
});
fwBtn.on("click", function(){
currPage = (currPage - 1) % pgCount; // Cycle though pages.
img.attr("src", "myTiff_page" + currPage + ".tif");
});
});
</script>

How can I let users customize background images?

Many sites these days have 'theming' functionality, when user is able to customize the pages' look. Sometimes it's only a fixed set of themes, but sometimes people are free to choose any style they want - for example, they can set up any color of the pages' background.
I want to go a step further - and let them choose the background image as well. The flow is very simple: user uploads a file (via <input type="file" />), then this file becomes a background image - but only for this user.
I can't find anything about this functionality online, though, and I have no clue about what to do.
Something else I was thinking was that, if a user selects a background, maybe I could use HTML5 localstorage to make that background come up every-time that visitor visits the page.
Here's a proof of concept (mostly based on the code given at MDN FileReader doc page + this answer):
HTML:
<input id="test" type="file" onchange="loadImageFile(this)" />
JS: no wrap (head) mode
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('body').css('background-image', 'url(' + backgroundImage + ')');
}
}
function loadImageFile(testEl) {
if (! testEl.files.length) { return; }
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
oFReader.readAsDataURL(oFile);
}
And here's a working demo, checked in latest Firefox and Chrome versions. Looks to work OK, at least. )
here's a quick solution to this problem.
custom-background.js is a lightweight jQuery plugin to allow users change the website’s default background and saves the background selected to local storage. This plugin can easily be added to any website or web app without any compromise on website's performance.
you can download it from here and check the code
https://github.com/CybrSys/custom-background.js

Categories