live text, fonts in pdf in node-canvas - javascript

I am using node-canvas to create images from canvas elements.
I've got canvas with few elements and i want to make pdf file from them.
I've been able to create the pdf from the canvas but i don't get the live text and fonts in the pdf.
this is my code:
var filename = uuid.v4() + '.pdf';
var path = '/' + site + '/' + filename;
var out = fs.createWriteStream(__dirname + path);
var canvas = fabric.createCanvasForNode(designWidth, designHeight,'pdf');
canvas.loadFromJSON(jsonStr, function () {
canvas.renderAll.bind(canvas);
canvas.backgroundColor = backgroundColor;
out.write(canvas.nodeCanvas.toBuffer(), function (err) {
if (err) throw err
});
});
my node version:
node-canvas v5.3.2
node v4.2.6
thanks

Related

How to convert as pdf while dealing with xml nodes in mxGraph?

I am implementing the graph editor using mxGraph javascript library and able to display the diagram and save the diagram.
Now,I have to export the diagram in to PDF file.
Primary question is,
Is there any other builtin feature is available on mxGraph library itself?
I used mxImageExport() class to exporting PNG image then its is redirecting to null url page.redirect page image
Here is the code:
function convertPDF() {
var graph = universalGraph; // get xml form the graph stored in graph variable
var xmlDoc = mxUtils.createXmlDocument();
var root = xmlDoc.createElement('output');
xmlDoc.appendChild(root);
var xmlCanvas = new mxXmlCanvas2D(root);
var imgExport = new mxImageExport();
imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
var bounds = graph.getGraphBounds();
var w = Math.ceil(bounds.x + bounds.width);
var h = Math.ceil(bounds.y + bounds.height);
var xml = mxUtils.getXml(root);
new mxXmlRequest('export', 'format=png&w=' + w +
'&h=' + h + '&bg=#F9F7ED&xml=' + encodeURIComponent(xml))
.simulate(document, '_self');
}
(or) else I have to use regular JS PDF library?(I cannot convert the HTML content inside tag in to PDF, While converting it is showing
graph's background only no single shapes are in it. Since it is from XML nodes, I referred the internet and asked me to convert from XML in to SVG then PDF
but this method also not work because I have received the blank PDF file.)
Here is the code:
function savePDF() {
var imgData;
html2canvas($(".svgClass"), {
useCORS: true,
onrendered: function(canvas) {
imgData = canvas.toDataURL(
'image/png');
console.log(imgData);
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
window.open(imgData);
}
});
}

html2canvas - IndexSizeError

I am trying to take an image that is loaded into a div on my page and try and either pass in the raw data fro the image, or try and copy the image to a location.
The best method i could find was using html2canvas
I am getting the following error when trying to open my image into a window to preview:
JavaScript runtime error: IndexSizeError
I have read a few posts advising that i could render the div using the following method:
html2canvas($("#mapDiv"), {
onrendered: function (canvas) {
// canvas is the final rendered <canvas> element
var imgData = canvas.GetContext("2d").getImageData(bounds.left, bounds.top, bounds.width, bounds.height);
var myImage = imgData.toDataURL("image/png");
window.open(myImage);
}
});
The problem is occuring on the following line in the html2canvas js file
ctx.drawImage(canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height);
Is it possible to render an image that is dynamically loaded into a div in this way, as i cant pass in the pixel parameters due to users having different resolutions
and if it is possible, what am i doing wrong?
function capture(id) {
html2canvas([document.getElementById(id)], {
logging: true,
onrendered: function(canvas) {
document.body.appendChild(canvas);
var dataUrl = canvas.toDataURL("image/png")
//console.log(dataUrl)
$('#img-out').attr("src", canvas.toDataURL("image/png"));
$.post("/upload-img", {img: dataUrl, name: id}, function (res) {
console.log(res)
location.href = $("#" + id).attr("shareUrl") + "&picture=" + (window.location.protocol + "//" +window.location.host + "/" + res.filePath)
} )
}
});
}
pass id of element you want snapshot.

How to download an image object from webgl/javascript

I have a directory with 100 images. I need a copy of them in various folders along with other information that I download from webgl. Hence I want to upload them onto the browser and download them again (hope that isn't stupid)
Here is my code:
var imagefile = model.features[cIndex].imageName.substring(model.features[cIndex].imageName.lastIndexOf('/')+1);
var image = new Image();
image.src = model.imageDirectory + imagefile;
image.onload = function() {
console.info("Read \""+image.src + "\"...Done");
}
image.onerror = function() {
var message = "Unable to open \"" + image.src + "\".";
console.error(message);
alert(message);
}
var data = image.src;
zip.file('image_RH_Original' + cIndex +'.png', data , {base64: true});
Is this wrong? How to I do something similar to "toDataURL" for the image object?
toDataURL is a method of canvas, and webgl draws to a canvas. So just call canvas.toDataURL(). Probably need to set preserveDrawingBuffer to true as well.

How to load images from server into img folder in phonegap

I have developed one game, it has more images so I am thinking load images from server for every game level complete in my phonegap game.
I need to download the images from server to this location
file:///android_asset/www/img in phonegap game.
how can I achieve this?
I have gone through the tutorial Code for displaying image in phonegap
but here they have displayed images on the screen, I dont to save them in img folder..
function storeIntelligrapeLogo() {
//alert('start of file download');
var url = "http://androidexample.com/media/webservice/LazyListView_images/image0.png"; // image url
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
//alert('inside request file sysytem')
// fs.root.getDirectory(myFolderName, {create:true, exclusive:false}, function (folder){});
var imagePath = 'file:///storage/sdcard0'+fs.root.fullPath + "/logo2.png"; // full file path
// var imagePath = 'file:///android_asset/www/'+fs.root.fullPath + "logo2.png";
// alert('inside request file sysytem path fs.root==' + fs.root);
// alert('inside request file sysytem path fs.root.fullPath==' + fs.root.fullPath);
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imagePath, function(entry) {
// alert(entry.fullPath); // entry is fileEntry object
var dwnldImg = document.getElementById("dwnldImg");
dwnldImg.src = imagePath;
dwnldImg.style.visibility = "visible";
dwnldImg.style.display = "block";
}, function(error) {
alert("Some error" + JSON.stringify(error));
});
}) }
I have tried this example but its storing image in the phone memeory but I need to store images into phonegap img folder
Thanks in advance
Use this code :
/**
* Load an image from internet and save it under the default repertory of the application
*/
public void downloadImageFromInternet(String url, String name)
{
ImageLoader.getInstance().loadImage(url,
new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
OutputStream fOut;
// You need to reference your context here. Depending on the class you inherite, "this", "getContext()" or "getActivity()" could work
File file = new File(context.getFilesDir(), name + ".jpeg");
try
{
fOut = new FileOutputStream(file);
loadedImage.compress(Bitmap.CompressFormat.JPEG, 90, fOut);
fOut.flush();
fOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
Read the File documentation to understand how to set the path of the saved file. In this code, the file will be saved inside the default folder of your application.
The library you need to download images from the web is Universal Image Loader.

HTML5 Canvas Drag out from browser to desktop

I'm trying to create a little image manipulation web app as a project. I'm trying to implement a Drag canvas image out of the browser to the desktop. I have done some digging and found
http://www.thecssninja.com/javascript/gmail-dragout and http://jsfiddle.net/bgrins/xgdSC/ (courtesy of TheCssNinja & Brian Grinstead)
function dragoutImages() {
if (!document.addEventListener) {
return;
}
document.addEventListener("dragstart", function(e) {
var element = e.target;
var src;
if (element.tagName === "IMG" && element.src.indexOf("data:") === 0) {
src = element.src;
}
if (element.tagName === "CANVAS") {
try {
src = element.toDataURL();
}
catch(e) { }
}
if (src) {
var name = element.getAttribute("alt") || "download";
var mime = src.split(";")[0].split("data:")[1];
var ext = mime.split("/")[1] || "png";
var download = mime + ":" + name + "." + ext + ":" + src;
e.dataTransfer.setData("DownloadURL", download);
}
}, false);
}
function drawCanvas(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#000');
lingrad.addColorStop(0.5, '#669');
lingrad.addColorStop(1, '#fff');
ctx.fillStyle = lingrad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = canvas.toDataURL("image/png");
img.alt = 'downloaded-from-image';
$(img).appendTo("body");
}
dragoutImages();
drawCanvas();
This works for files which are elements of the HTML but I am unable to grab the canvas image and download it using the theory. Has anyone implemented such a feature?
I have used the canvas.toDataURL to get the image data, if I do an alert I see the encoded image data my canvas drag begins but when outside the browser the icon changes back to the stop symbol.
Looking for approaches and ideas on how to implement this.
This is what I've managed to implement and works pretty well,
function download(e){
downloadImageData = eCanv.getImageData(750 - (scaledWidth / 2), 250 - (scaledHeight / 2), scaledWidth, scaledHeight);
dlcanvas = document.createElement('canvas');
dlcanvas.setAttribute('width',scaledWidth);
dlcanvas.setAttribute('height',scaledHeight);
dlcontext = dlcanvas.getContext("2d");
dlcontext.putImageData(downloadImageData, 0,0);
url = dlcanvas.toDataURL('image/jpg');
//name = document.getElementById("filename").value;
var mime = url.split(";")[0].split("data:")[1];
var name = mime.split("/")[0];
var ext = mime.split("/")[1] || "jpg";
var download = mime + ":" + name + "." + ext + ":" + url;
e.dataTransfer.setData("DownloadURL", download);
}
Adapted code from cssninja and Brian Grinstead.
No.
For security reasons, Javascript cannot write to the local file system.
Javascript can read from the local file system with the filereader: http://www.html5rocks.com/en/tutorials/file/dndfiles/
It can even write to a sandboxed browser file (localstorage): http://www.w3schools.com/html/html5_webstorage.asp
You could even bounce it off your server and then ask the user if they want to download the image off the server.
For local web based applications you can use or write a local webserver or service and or utilzize for example php to add the functionality to interact with the local filesystem from javascript. Seems this is forgotten that it is not forbidden to install a webserver on the same machine like the browser :)

Categories