Retrieving the absolute URL of a temporary canvas element on page - javascript

I created a coupon-creator system that uses HTML 5 canvas to spit out a jpg version of the coupon you create and since I'm not hosting the finalized jpg on a server, I am having trouble retrieving the URL. On some browsers when I drag the image into the address bar all I get is "data:" in the address bar. But on windows, if I drag it into an input field, sometimes it spits out the huge (>200 char) local-temp url. How can I use javascript(?) to find that exact temporary URL of the image generated by my coupon creator and be able to post it on an input form on the same page? Also, it'd be very helpful if you guys know the answer to this as well, as I assume it is correlated with the retrieval of the URL: When I click the link that says "Save it" after it's generated, how can I have it save the created image to the user's computer? Thanks a lot!
This is what I'm using in JS right now to generate the image:
function letsDo() {
html2canvas([document.getElementById('coupon')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/jpeg');
// AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
var mycustomcoupon = new Image();
mycustomcoupon.src = data;
//Display the final product under this ID
document.getElementById('your_coupon').appendChild(mycustomcoupon);
document.getElementById('your_coupon_txt').style.display="block";
}
});
}
Here is the live URL of the creator: http://isleybear.com/coupon/

I ended up dumping this code into the js stated above. It was a pretty simple fix. Then to test it, I set an onclick html element to show the source.
var mycustomcoupon = document.getElementById('your_coupon');
mycustomcoupon.src = data;
}
});
}
function showSource(){
var source = document.getElementById('your_coupon').src;
alert(source);
}

Related

Download pdf with filled data in acroform - PDFJS

I am integrating PDF JS in my web application with enabled renderIntrectiveForm property. So I am able to edit the form input in PDF, I am able to fill inputs. But the problem is I am not able to download the PDF with filled data.
I searched as much as I can. And I tried so hard to achieve the functionality. I also tried to update annotation manually as in below code in download function. But still, it is downloading the original PDF.
var pdf = PDFViewerApplication.pdfDocument;
var downloadManager = PDFViewerApplication.downloadManager;
pdf.loadingTask.then(function(data){
data.getPage(1).then(function(page){
page.getAnnotations().then(function(annotations){
annotations[1].fieldValue= "New Text"
pdf.getData().then(function(blobData){
var blob = (0, PDFJS.createBlob)(blobData, 'application/pdf');
downloadManager.download(blob, "a.pdf", "a.pdf");
})
})
})
});
I know i can send json to server and then create a new pdf with json(as in https://www.smartformsondemand.org). But I want to do it with client side only.

Saving file with JavaScript File API results wrong encoding

I have a problem (or may be two) with saving files using HTML5 File API.
A files comes from the server as a byte array and I need to save it. I tried several ways described on SO:
creating blob and opening it in a new tab
creating a hidden anchor tag with "data:" in href attribute
using FileSaver.js
All approaches allow to save the file but with breaking it by changing the encoding to UTF-8, while the file (in current test case) is in ANSI. And it seems that I have to problems: at the server side and at the client side.
Server side:
Server side is ASP.NET Web API 2 app, which controller sends the file using HttpResponseMessage with StreamContent. The ContentType is correct and corresponds with actual file type.
But as can be seen on the screenshot below server's answer (data.length) is less then actual file size calculated at upload (file.size). Also here could be seen that HTML5 File object has yet another size (f.size).
If I add CharSet with value "ANSI" to server's response message's ContentType property, file data will be the same as it was uploaded, but on saving result file still has wrong size and become broken:
Client side:
I tried to set charset using the JS File options, but it didn't help. As could be found here and here Eli Grey, the author of FileUplaod.js says that
The encoding/charset in the type is just metadata for the browser, not an encoding directive.
which means, if I understood it right, that it is impossible to change the encoding of the file.
Issue result: at the end I can successfully download broken files which are unable to open.
So I have two questions:
How can I save file "as is" using File API. At present time I cannot use simple way with direct link and 'download' attribute because of serverside check for access_token in request header. May be this is the "bottle neck" of the problem?
How can I avoid setting CharSet at server side and also send byte array "as is"? While this problem could be hacked in some way I guess it's more critical. For example, while "ANSI" charset solves the problem with the current file, WinMerge shows that it's encoding is Cyrillic 'Windows-1251' and also can any other.
P.S. the issue is related to all file types (extensions) except *.txt.
Update
Server side code:
public HttpResponseMessage DownloadAttachment(Guid fileId)
{
var stream = GetFileStream(fileId);
var message = new HttpResponseMessage(HttpStatusCode.OK);
message.Content = new StreamContent(stream);
message.Content.Headers.ContentLength = file.Size;
message.Content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType)
{
// without this charset files sent with bigger size
// than they are as shown on image 1
CharSet = "ANSI"
};
message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = file.FileName + file.Extension,
Size = file.Size
};
return message;
}
Client side code (TypeScript):
/*
* Handler for click event on download <a> tag
*/
private downloadFile(file: Models.File) {
var self = this;
this.$service.downloadAttachment(this.entityId, file.fileId).then(
// on success
function (data, status, headers, config) {
var fileName = file.fileName + file.extension;
var clientFile = new File([data], fileName);
// here's the issue ---^
saveAs(clientFile, fileName);
},
// on fail
function (error) {
self.alertError(error);
});
}
My code is almost the same as in answers on related questions on SO: instead of setting direct link in 'a' tag, I handle click on it and download file content via XHR (in my case using Angularjs $http service). Getting the file content I create a Blob object (in my case I use File class that derives from Blob) and then try to save it using FileSaver.js. I also tried approach with encoded URL to Blob in href attribute, but it only opens a new tab with a file broken the same way. I found that the problem is in Blob class - calling it's constructor with 'normal' file data I get an instance with 'wrong' size as could be seen on first two screenshots. So, as I understand, my problem not in the way I try to save my file, but in the way I create it - File API

Copy canvas from one page to another without crossing max character limit

I want to play a video in HTML video element and take snapshot on pause. The snapshot is displayed on the page inside a canvas. Now I want the same snap to appear on another page and for this I am trying to encode the snapshot in base 64 using toDataUrl() method & pass it through URL.
But the maximum length of URL can be 2048 char while the output of toDataUrl is much bigger. How to proceed?
Working fine:
video.addEventListener('pause', function(){
$(this).hide();
$("#canvas1").show();
draw( video, thecanvas, img);
}, false);
function draw(video,thecanvas,img){
var context = thecanvas.getContext('2d');
context.drawImage(video,0,0,thecanvas.width,thecanvas.height);
var dataURL = thecanvas.toDataURL('image/jpeg',.1);
img.setAttribute('src',dataURL);
}
Not working: The function to direct to another page
function toskuentry(){
var imgsrc = $('#thumbnail_img').attr('src');
window.location.href = "sku_entry.php?imgsrc="+imgsrc;
}
Don't pass it through the URL, use HTML5 Web Storage. You can use either sessionStorage or localStorage:
function toskuentry(){
localStorage.setItem("img", $('#thumbnail_img').attr('src'));
}
On the next page you can access it by localStorage.getItem("img");.
One good option would be to use Firebase. They have an example of doing that.
https://www.firebase.com/tutorial/#session/n24v8lvnltc
Firebase uses local storage when offline, so that means you could also use local storage if you didn't want to use Firebase.
something like
localStorage["data"] = dataURL;
//...other page
var dataURL = JSON.parse(localStorage["data"]);

How to create a base64 file from nothing?

I want to be able to create base64 files (images, sounds, video) without any previous models. For example, if I want to create a base64 64px*64px red image, how can I do this without creating first a canvas?
I would also like to create a sound (note) with no model.
I've searched on Google for some documentation on base64 encoding but I did not seem to find specific things for my need.
I am going to use Javascript, but I guess this should be the same for every language.
Try
function createFile(_data) {
var _data = ["<!doctype html>",
"<img style=width:64px;height:64px;"
+ "background-color:red;display:block; />"];
var data = window.btoa(_data.join("").toString());
var file = "data:text/html;base64," + data;
return file
};
createFile();
jsfiddle http://jsfiddle.net/guest271314/6GPju/
see also http://www.w3.org/TR/FileAPI/ , https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa

HTML5 - Attach image to mail using Java EE

I am developing an a drawing application using Javascript.
Users will be able to draw on a canvas. Once they are done with drawing, they will be able to convert it into an image (Convert to image button).
This is the code:
function putImage()
{
var canvas1 = document.getElementById("canvas");
if (canvas1.getContext)
{
var ctx = canvas1.getContext("2d");
var myImage = canvas1.toDataURL("image/png");
}
var imageElement = document.getElementById("MyPix");
imageElement.src = myImage;
$('#submit_btn').closest('.ui-btn').show();
}
There's a submit button and when the users click on it, the application will redirect to another page whereby the user will be able to send an email (using java mail) with the image attached to it.
The page allows user to type in the email address that they wanna send to, and the body of the email.
May i know how to make the image auto-attach to the email so that the after the user type in the email address and the body, they will be able to send the mail?
Thanks in advance!
To send the image as an attachment with javamail, you need the bytes from say a jpg or bmp. What you'll need to do is send the model, eg the coordinates, to the server and recreate the image server side. Perhaps a html5 canvas has direct support for outputting the images as bytes, I don't know, but that would help. In that case you'd simply transfer those bytes to the server for attaching to the mail.
HTML5 Canvas has a cool api trick to do this:
var encodedImage = canvas1.toDataURL(); //this generates base64 encoded image in png
//for jpeg
var encodedImage = canvas1.toDataURL("image/jpeg");
Now you can store that encodedImage in back-end in a table or file. If you want to show it on a page, just assign it back to html img tag to source property

Categories