HTML2CANVAS image to be sent via email - html

This is what i am trying to achieve
When a button is pressed on a specific div in a HTML page, it goes to the HTML2CANVAS function and creates a canvas img. Now i need to attach this image to the body and open an outlook compose box.
1) How to send mail with image embeded in the body from within a web page?
2) How to convert canvas as a displayable image?

This function is the answer to your second question. This function converts a div into a base64 image and on complete render it displays the image to a div or you can do accordingly as you want.
function getImage(){
html2canvas($("#divID"), {
onrendered: function(canvas) {
// For image
var ctx=canvas.getContext("2d");
// ctx.webkitImageSmoothingEnabled = false;
// ctx.mozImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
var convertedImage;
$.when(convertedImage = canvas.toDataURL('image/jpg')).promise().done(function(){
$('#finalImg').prop('src', convertedImage)
});
}
});
}
And the answer to your first question is also the same this converted image can be sent as a image in mail.
But you cannot send a MIME type in mailto body it can only contains plain text as body..
for further reference here is a link
Sending mail from HTML page with image in the body

Related

Qt: Set background image on QTextDocument using HTML to generate pdf file

i am wrapping my head in this problem for a few time.
I need to create a report by creating a pdf file with some data on it.
So my plan was to instead of using the QTextCursor, i use HTML + CSS to create the content in my pdf file.
Unfortunately I can't go with the QWebEngine widgets solution because I am compiling into MinGW and setting the MVSC 2017 environment is a huge mess.
Sadly i have to go with the QTextDocument and his HTML subset support.
My problem is I can't put a background image in my pdf file.
I want to put this image as a background image:
What make me crazy is that I use the css property to display a background image in my pdf file.
background-image: url(:/images/blue-gradient-background.jpg);
And it seems that Qt is taking this into account but it still don't display the background.
Have a look:
The first pdf file don't contain the css property background image on the html content but the second does and you can see that the size of the file is bigger so it has considered the css property.
But it hasn't displayed the background:
On the left is the first file and on the right is the second file with the css property.
I use a html file in the ressource to generate the report :
<!DOCTYPE html>
<html>
<style>
body {
background-image: url(:/images/blue-gradient-background.jpg);
}
h1 {
color: blue;
}
#table-content {
}
#table-content table {
margin: 1em
}
</style>
<body>
<div align="center"><h1>[title-template]</h1></div>
<div align="center" id="table-content">[table-template]</div>
</body>
</html>
This html file is open and read in the constructor of the class:
FileEditor::FileEditor()
{
QFile htmlTemplate(":/html/report.html");
if (htmlTemplate.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream in(&htmlTemplate);
m_reportPageHTMLTemplate = in.readAll();
}
}
Then i use a custom class with this function that use QPrinter and QPainter to write the data:
void FileEditor::writeReportPdfFile(const QString &i_path, const S12xConf &i_s12xConf, const S12xData &i_s12xData, const BenchTestData &i_benchTestData)
{
QDir directory(i_path); // we create a QDir with the path
if (!directory.exists()) // if the directory does not exist then
{
directory.mkpath("."); // we create the path
}
QString fileName = getCurrentHourDate() + "_S12xNG_Test_Report.pdf";
QPrinter pdfPrinter(QPrinter::HighResolution);
pdfPrinter.setOutputFormat(QPrinter::PdfFormat);
pdfPrinter.setPageSize(QPageSize(QPageSize::A4));
pdfPrinter.setOutputFileName(i_path + "/" + fileName);
pdfPrinter.setFullPage(true);
QPainter painter(&pdfPrinter);
painter.setBackgroundMode(Qt::OpaqueMode);
QTextDocument measuresDoc;
QTextDocument averagesDoc;
QTextDocument inOutDoc;
measuresDoc.documentLayout()->setPaintDevice(&pdfPrinter);
measuresDoc.setPageSize(pdfPrinter.pageRect().size());
averagesDoc.documentLayout()->setPaintDevice(&pdfPrinter);
averagesDoc.setPageSize(pdfPrinter.pageRect().size());
inOutDoc.documentLayout()->setPaintDevice(&pdfPrinter);
inOutDoc.setPageSize(pdfPrinter.pageRect().size());
setMeasuresTextDocument(&measuresDoc);
setAveragesTextDocument(&averagesDoc);
setInputsOutputsTextDocument(&inOutDoc);
measuresDoc.drawContents(&painter); // We print TextDocument of the Measures into the document
pdfPrinter.newPage(); // We inject the current page and continue printing on new page
averagesDoc.drawContents(&painter); // We print the TextDocument of the Averages into the document
pdfPrinter.newPage(); // We inject the current page and continue printing on new page
inOutDoc.drawContents(&painter); // We print the TextDocument of the Inputs/Outputs into the document
measuresDoc.undo();
averagesDoc.undo();
inOutDoc.undo();
}
Here is the function to add the html data into the measures QTextDocument:
void FileEditor::setMeasuresTextDocument(QTextDocument *o_measuresDoc)
{
QString htmlContent = m_reportPageHTMLTemplate;
htmlContent.replace("[title-template]","I. Measures Data");
o_measuresDoc->setHtml(htmlContent);
}
So what i am doing wrong?
Thanks in advance for your responses.
I have found the answer!
it is about the drawContents method of QTextDocument.
There is a second parameter that you need to add in order to see the background image in your document.
It's the a QRectF object that represend the size of the rect that the background image will be clipped into.
void QTextDocument::drawContents(QPainter *p, const QRectF &rect = QRectF())
Draws the content of the document with painter p, clipped to rect. If rect is a null rectangle (default) then the document is painted unclipped.
So what I did is:
easuresDoc.drawContents(&painter, pdfPrinter.paperRect()); // We print TextDocument of the Measures into the document
pdfPrinter.newPage(); // We inject the current page and continue printing on new page
averagesDoc.drawContents(&painter, pdfPrinter.paperRect()); // We print the TextDocument of the Averages into the document
pdfPrinter.newPage(); // We inject the current page and continue printing on new page
inOutDoc.drawContents(&painter, pdfPrinter.paperRect()); // We print the TextDocument of the Inputs/Outputs into the document
pdfPrinter.paperRect is the rectangle of the page without the margin.
Also if you want the background image to be printed scaled with no repeat than you need to put the printer into QPrinter::PrinterResolution
QPrinter pdfPrinter(QPrinter::PrinterResolution);

chrome extension: Parse JSON data and get image

i have a json data like that
{ "ikealogo": "https://xxx.blob.core.windows.net/logo/24536.jpg?v=20120912144845" }
how can i convert it in image view?
Things i have tried but need alternate solution. it works fine in popup window but **i need to convert it for my content script in a specific webpage, when user will hover mouse on a text and should appear this image ** but applying same process is not working at all.
//popup.js
var image = document.getElementById('img');
image.src = jsonData.ikea.ikealogo;
//popup.html
<img id="img" />
SOLUTION:
To appear any image from external server on DOM :
I parse data from API response and create div with jquery and append the image data inside it.
There's NO need for CROSS DOMAIN COMPLICITY.
var image= data["company"].ikealogo;
var div=jQuery('<div/>',
{
"class": "divC",
});
var i = jQuery('<img />').error(function()
{
this.src = default_image;
}).attr('src', image)
.css({ "width":"50px", "height": "50px","margin": "0px 10px 10px 10px"});
div.append(i)

How to download image object on page as a file in html?

I am creating an image dynamically on the page using dataURL,
var aImg = document.createElement('img');
aImg.setAttribute('src', dataURL);
aImg.setAttribute('alt', 'pic');
aImg.setAttribute('width', '438px');
aImg.setAttribute('height', '267px');
aImg.onclick = (function() {
//download the image object
})();
I am not sure what to do to download this image object that is a PNG image.
Can someone give hints?
If you want the image to be displayed the follwing should be fine :
aImg.src = YOUR_URL
if you want to save it on to the file , you shoud redirect and let the browser take care of the rest. JS redirect can be done as follows :
window.location.replace(dataURL)
If you want the browser to give a pop-up saying "Save File" check out this link : http://muaz-khan.blogspot.in/2012/10/save-files-on-disk-using-javascript-or.html

Unable to autofocus input element in Firefox add-on tab

I used .open() to create a tab displaying the HTML in data/search.html and attached data/search.js as a content script file.
var tabs = require("sdk/tabs");
var data = require("sdk/self").data;
function executeSearch () {
/* set up search tab */
tabs.open({
url: data.url("search.html"),
onReady: function (tab) {
var worker = tab.attach({
contentScriptFile: data.url("search.js")
});
worker.port.on("searchtext", function (wordsJson) {
worker.port.emit("matchingPages", JSON.stringify(hlutils.matchingPages(wordsJson)));
});
}
});
}
The HTML displays correctly and the content script runs properly, but in the HTML file (which is in valid HTML5) the autofocus property of an input element is not honored. Basically there is no cursor in the page as displayed, and no input can be made without clicking into the input element. I tried doing it the old-fashioned way by using
document.getElementById("search").focus();
in the content script file, and also in a script element in the HTML file (below the referenced element), all to no avail.
Finally figured it out. Had to add the following to the content script file:
window.addEventListener("load", function (event) {
document.getElementById("search").focus();
});

printing just canvas element on a page

im a little stuck using the canvas element in html5, have scoured the net looking for a workable solution but to no avail!
the main issue is that I want to click a button and send just the canvas element on the page to the printer.
i have tried using toDataUrl() - but this just seems to be resulting in a blank white image which has none of the canvas content!
the other issue i am experiencing is that attempting to initiate any javascript functions using "onClick" attached to a form button seems to be being tempermental at best!
here is my current attempt - this works in the sense that it does open a new window and attempt to send it to printer and it does create a base64 string (tested this using the "dataUrl" output on the second lowest document.write line) but as previously mentioned the image appears to be completely blank! (the canvas itself is definitely filled, both with an imported image and some text)
function printCanv()
{
var dataUrl = document.getElementById('copy').toDataURL(); //attempt to save base64 string to server using this var
document.getElementById('testBox').value = dataUrl; //load data into textarea
//attempt open window and add canvas etc
win = window.open();
self.focus();
win.document.open();
win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
((image code is here but site will not let me post it for some reason?))
win.document.write(dataUrl);
win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
win.document.close();
win.print();
win.close();
}
note: the code from "win = window.open()" onwards is currently taken from a tutorial and not my own work!
it is currently being called using <body onload="printCanv";"> - for some reason I could not get this to work at all using a button (little chunk of code below is my attempt which seemed to fail)
<input type="button" id="test" value="click me" onClick="printCanv();"> </input>
apologies is this help request is all over the place! i haven't posted to a site like this before and it didn't like me posting some html/script!
thanks in advance for any help you may be able to offer :)
Edit: draw function:
function copydraw() { //function called "copydraw" (could be anything)
var testimage3 = document.getElementById('copy').getContext('2d'); //declare variable for canvas overall (inc paths)
var img3 = new Image(); //declare image variable called "img3"
var testVar = document.getElementById('userIn').value; //take value from userin box. only updating on browser refresh?
img3.onload = function(){ //when image has loaded (img.onload) run this function
testimage3.drawImage(img3,0,0); //draw "img" to testimage
testimage3.font = "30pt 'Arial'"; //font method varies font attrib (weight, size, face)
testimage3.fillStyle = "#000000"; //sets fill color
testimage3.fillText(testVar, 310, 360); //filltext method draws text (xup ydown)
}
img3.src = 'images/liecakeA4.jpg'; //source of image
}
This function works perfectly, it draws the object and adds text from the variable, but for some reason it seems to be preventing me from outputting it as an image. I'm really confused!
I'm not sure exactly what's wrong with your code, I suspect in your current version calling printCanv in the body load event will mean you're trying to print the canvas before it's drawn. Running it off the button should work better, I'm not sure why that wasn't working for you as there's no reason in principle why it shouldn't work.
To arrive at a working version I've modified your code slightly:
function printCanvas(el) {
var dataUrl = document.getElementById(el).toDataURL(); //attempt to save base64 string to server using this var
var windowContent = '<!DOCTYPE html>';
windowContent += '<html>'
windowContent += '<head><title>Print canvas</title></head>';
windowContent += '<body>'
windowContent += '<img src="' + dataUrl + '">';
windowContent += '</body>';
windowContent += '</html>';
var printWin = window.open('','','width=340,height=260');
printWin.document.open();
printWin.document.write(windowContent);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
}
This works for me in the Firefox 4.0 nightly.
One addition to the accepted-best-answer: It doesnt work here with Chrome 17.0.942.0 winvista, because the print-preview-dlg is shown within the website itself and printWin.close() will close the dlg too.
So printWin.close() must be delayed or initiated by the user, but those are no good solutions.
It would be best, if chrome printdlg could have a callback, sth. one knows, printing is done, and can close the window. If this is possible is another question.