I had successfully converted html to image using the below code but however font was changing and image is not displaying on image.
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"></script>
</head>
<body>
<div id="div_card" style="border-color:grey;border-style:solid;border-width:1px;width:600px; height:450px; padding:15px;margin-left:40px">
<div style="display:inline-block;height:20px;"> <div id="sp_name"> Author:John Michael Smith Junior</div></div><br>
<div style="display:inline-block;height:120px; width: 120px; float:right">
<img src="htmlimage.jpg" style="height:120px; width: 120px"> </div>
<div style="display:inline-block;height:20px;"><div> Published on March 1982 </div></div><br>
<div style="display:inline-block;height:20px;"> <div> Published by: Mark Vin book house</div></div><br>
<div style="display:inline-block;height:20px;"> <div>Last Edition Dec 1999</div></div><br>
<div style="display:inline-block;height:20px;"> <div>Sold Copies: 150000</div></div><br>
</div>
<a id="btn-Convert-Html2Image" href="#">Download</a>
<br />
<div id="previewImage" style="display: none;">
</div>
<script>
$(document).ready(function () {
var element = $("#div_card"); // global variable
var getCanvas; // global variable
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
$("#btn-Convert-Html2Image").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
});
});
</script>
</body>
</html>
I need to get image without change in font.How can I do that??????
No need canvas is image like
There are many ways to convert a canvas to an image. However why bother as the canvas is image like in its behavior. Just display the canvas as if it were an image.
Contemporary html2canvas usage example, adding captured canvas to page
html2canvas(document.body).then(canvas => document.body.appendChild(canvas));
Using your example
Note security prevents it from working in the SO snippet.
addEventListener("load",() => {
html2canvas(divCard)
.then(can => {
// show result of html2canvas
previewImage.classList.remove("hide");
previewImage.appendChild(can);
// show download link and add data url for download.
downloadLink.classList.remove("hide");
downloadLink.download = "canvasCap.png"; // name the download file
downloadLink.href = can.toDataURL("image/png").replace("data:image/png", "data:application/octet-stream");
})
.catch(error => {
previewImage.textContent = "html2canvas error: " + error.message;
previewImage.classList.remove("hide");
previewImage.classList.add("error");
});
});
* { font-family: arial }
.hide { display: none }
.error {color: red }
.titile {font-size: x-large}
#divCard {
border: 2px solid black;
padding: 4px;
}
<script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"></script>
<div id="divCard">
<div class="titile">Author:John Michael Smith Junior</div>
<div>Published on March 1982 </div>
<div>Published by: Mark Vin book house</div>
<div>Last Edition Dec 1999</div>
<div>Sold Copies: 150000</div>
</div>
<h4>HTML2CANVAS result...</h4>
<a id="downloadLink" class="hide">download</a>
<div class="hide" id="previewImage"></div>
BTW Its 2020.. jQuery is slow bloated baggage. Windows ended support for IE <11 on Jan31 this year removing the last argument for jQuery relevance.
This is the solution I came up with. It allows remote and custom fonts to be included properly in the output image. It requires the latest version of Chrome:
Open the HTML page (that you wish to convert to an image) in Chrome.
Right click anywhere in the background of the displayed page, and select "Save As".
In the Save As dialog, select the "Save as type" option for "Webpage, Single file (*.mhtml)", then select the folder and file name you want to save as. This will convert the HTML into MHTML and save it locally. The file size will be huge because it includes all the custom fonts, and potentially static images, in the file.
Go to the command line shell of your local machine and use headless Chrome to take a screenshot of the locally saved .mhtml file as a PNG file.
E.g, if your machine is Windows 10, the locally saved file is "C:\tmp\page.mhtml", and it is a 16x16 image, use:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --headless --disable-gpu --screenshot=C:\tmp\page.png --window-size="16,16" --default-background-color=0 file:///C/tmp/page.mhtml
This will save the top left 16x16 window of your rendered HTML page as a PNG file at: C:\tmp\image.png.
Related
I want to convert HTML to PDF with the click of a button and download.
My js working perfectly only need the latest JavaScript CDN link.
HTML
<div id="pageprint">
<div id="reportbox">Hello World!!</div>
</div>
<button type="button" onclick="downloadCode();">Download HTML</button>
Javascript
<script>
function generatePDF() {
const element = document.getElementById("pageprint");
document.getElementById("reportbox").style.display = "block";
document.getElementById("reportbox").style.marginTop = "0px";
document.getElementById("pageprint").style.border = "1px solid black";
html2pdf().from(element).save('download.pdf');
}
function downloadCode(){
var x = document.getElementById("reportbox");
generatePDF();
setTimeout(function() { window.location=window.location;},3000);}
</script>
If all you need is the CDN then simply add it after the </body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
function generatePDF() {
const element = document.getElementById("pageprint");
document.getElementById("reportbox").style.display = "block";
document.getElementById("reportbox").style.marginTop = "0px";
document.getElementById("pageprint").style.border = "1px solid black";
html2pdf().from(element).save('download.pdf');
}
function downloadCode(){
var x = document.getElementById("reportbox");
generatePDF();
setTimeout(function() { window.location=window.location;},3000);}
<div id="pageprint">
<div id="reportbox">Hello World!!</div>
</div>
<button type="button" onclick="downloadCode();">Download HTML</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
However seems a very odd way to ask a user to download a pdf page since the option disappears after the download is attempted, so change of mind does not keep it user visible to try differently on fail.
So for example, I say open the download on current page, I see
but if I say open in PDF Viewer I see
It's much simpler to layout the printable HTML page as text not image, and suggest the user prints or saves exactly as their browser is configured and their desire, best result for all, especially as no libraries are needed.
Nor will the page be cluttered by buttons.
You can print html just as follow.
<style type="text/css">
#media print{ button {display:none} };
</style>
<div id="pageprint">
<div id="reportbox">Hello World!!</div>
</div>
<button type="button" onclick=javascript:window.print()>Download HTML</button>
Please let me know if any issue found
There isn't an easy way to do this. The best thing you could do is to open an empty page, fill it with your html data and print it to pdf. Or look for some external libary like jsPDF.
example for print to pdf:
var wnd = window.open('about:blank', '', '_blank');
wnd.document.write("<p> Some HTML-Content </p> ");
wnd.print();
I'm attempting to set up a simple way for a non-tech-savvy person to update a marquee ticker that will appear on a website that would be published to our BrightSign display system. I was think that they could easily type what they want into a text file, save it, and "republish" the website to our display system. All the files (index.html, style.css, tickerText.txt) would be saved locally on a computer for the person in charge to edit the marquee.
Everything works well when I type in the text between my marquee tags, but when I attempt to pull in the info from a text file, it scrolls across with a large amount of "white space" and not as long text. The below script shows when it comes out correctly (shown in picture link -- wouldn't let me embed).
Long Text Marquee
<!-- Bottom Marquee Ticker -->
<div class="3-row-padding w3-center">
<div class="w3-container ocacity75"">
<div class="w3-card-4 w3-white w3-round ticker">
<marquee>This is a test and so is this</marquee>
</div>
</div>
</div>
The below script is when I try to populate the marquee from a text file and then messes up my formatting (shown in picture -- wouldn't let me embed).
Incorrect Formatting Marquee
<!-- Bottom Marquee Ticker -->
<div class="3-row-padding w3-center">
<div class="w3-container ocacity75"">
<div class="w3-card-4 w3-white w3-round ticker">
<marquee><object type="text/html" data="./TickerText.txt"></object></marquee>
</div>
</div>
</div>
I even tried adding in-line styling to the object tag to try to make the marquee not so large and to increase the text size, but nothing seems to work. I may be going about this wrong with trying to read in a text file. I tried some JavaScript, but I couldn't get it to work and though just a marquee tag would do just fine. Any help would be a appreciated.
To confirm, I did not use AJAX as the website doesn't show its changes on the display system until we hit the publish button again. So live updates to the website without refreshing would be overkill.
Well, you could try this:
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function() {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function(e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
#styleTest {
color: green;
}
<input type="file" id="myFile">
<div id="styleTest">
<div id="output"></div>
</div>
This will work for what you want, also the data in the text file would be able to be formated if needed.
As said in the comment by A Haworth,
The <marquee></marquee> tag is now deprecated.
Also, you could bypass even having a text file by doing this:
(Note: this one is better suited to your needs, for now.)
var input = document.getElementById("input");
var output = document.getElementById("output");
var txtInSub = document.getElementById("txtInSub");
function addData() {
output.innerHTML = input.value;
}
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
e = e || window.event;
var key = e.which || e.keyCode;
// key == "13" is the enter key
if (key == "13") {
txtInSub.click();
console.log({keyPressed: "Enter", functionExecution: "Submitted the Text Input Field", contentPosted: input.value});
}
}
#styleTest {
color: green;
}
#inSubFld {
text-align: center;
width: 98.22%;
position: absolute;
left: 0;
top: 60px;
}
#input {
width: 100%;
padding: 10px;
display: block;
}
#txtInSub {
display: none;
}
<div id="styleTest">
<div id="output"></div>
</div>
<div id="inSubFld">
<input id="input" type="text" autofocus> <!-- with autofocus it should force it so that you could type in the input field without needing to click it -->
<button id="txtInSub" onclick="addData()">Submit</button>
<p>Press Enter to Submit the content in the field above.</p>
</div>
I've been through a lot of tutorials and I can never get this to work:
I want to save the content of a div (with contenteditable enabled) to a .txt file with node webkit. That part looks like this:
<div id="editor" class="textbox" contenteditable></div>
And I have the input field that allows me to select the file:
<input type="file" nwsaveas="untitled.txt" style="display:none;"/>
However I can't find any resources on how to save the value of the editor div as a .txt file on the user's computer.
I tried this tuts plus tutorial that briefly explains it however it didn't seem to work when I tried it on my own project: http://code.tutsplus.com/tutorials/introduction-to-html5-desktop-apps-with-node-webkit--net-36296
Does anyone know how I can achieve this?
You have to make file dialog open with emulating click event of an input, then get innerHTML of #editor, and finally use node's fs.writeFile to save content.
Here is full working example:
<!DOCTYPE html>
<html>
<head>
<script>
var initInputFile = function() {
document.getElementById('inputFile').addEventListener('change', function() {
var path = this.value; //get fullpath of chosen file
var content = document.getElementById('editor').innerHTML; //get editor's content
content = (' ' + content).slice(1); //hack to prevent strange bug of saving just half of the content
require('fs').writeFile(path, content, function(err) {
if (err) throw err;
console.log('done');
});
var wrapper = document.getElementById('inputFileWrapper');
wrapper.innerHTML = wrapper.innerHTML; //hack to make "change" event trigger...
initInputFile(); //...when choosing the same file
});
}
window.onload = function() {
initInputFile();
document.getElementById('saveBtn').addEventListener('click', function() {
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click');
document.getElementById('inputFile').dispatchEvent(event);
});
}
</script>
</head>
<body>
<div id="editor" class="textbox" style="width:400px; height:100px;" contenteditable></div>
<div id="inputFileWrapper" style="display:none;">
<input type="file" id="inputFile" nwsaveas="untitled.txt"/>
</div>
<input type="button" id="saveBtn" value="Save" />
</body>
</html>
Hope this helps.
I've been looking around much today and spend a few hours trying to get something done. For a client I am creating a slideshow with a lightbox when clicked on an image. The slideshow and lightbox both work, but I don't get the right image in the lightbox yet.
This is the code that loads the slideshow and when clicked on an image opens the lightbox.
(The images for the slideshow get loaded by a php script and turned into a Javascript array)
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
}
</script>
<div style="width: 170px; height: 160px">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style. display='block'">
<img id="slideshow" src="" />
</a>
<div id="light" class="white_content">
<img id="lightImg" src="" />
<script>
var image = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", image);
</script>
I now try to create a variable named "image"and let this contain the src of the current image in the slideshow. So I can load this to the image in the lightbox.
Hopefully some one can give me some usefull tips. I am pretty new in the Javascript language.
The script for the slideshow came from: http://www.javascriptkit.com/javatutors/externalphp2.shtml
Regards Koen.
These days there really is no excuse for using obtrusive Javascript (Stuff inside your HTML attributes, ideally it should be in an external file. http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
I have done you the favour of cleaning up your code a bit, and changed it where you seemed to be going wrong. As DotNetter has already pointed out it would be sensible to use jQuery in this instance, as it really does simplify things. However, I'm going to assume that for some reason you want it in plain js. Below is a simplification of the code that you posted with the correct change.
<style type="text/css">
.wrapper {
width: 170px;
height: 160px;
}
</style>
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/" + galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
</script>
<div class='wrapper'>
<img id="slideshow" src="" />
<div id="light" class="white_content">
<img id="lightImg" src="" />
</div>
</div>
Before, you were getting the src of the current image when the page loaded, you need to be getting the src of the image when the user clicks on the
I'm currently upgrading a WYSIWYG Rich Text Editor that was based on the DHTML Editor Control (DEC) to use the more modern editor controls in modern browsers. I'm using an iFrame with design mode turned on and a mixture of regular javascript and jquery.
One of my requirements is to insert html content (forms etc) into the iframe so that users can edit them. I have it working in FF + Chrome, but IE is proving a pain. My current code inserts the content at the start of the parent document and not the iframes, I'm using the selection.createRange() function that when used with DEC would insert the content either at the cursor if the control was selected or at the end of the document inside the editor if not.
Currently it only works when I select some text in IE. Heres my current code (apologies if it looks unformatted the firewall at work is blocking a lot of the css + js from stackoverflow), any ideas?
<html>
<head>
<title>Text Editor Test</title>
<style type="text/css">
.toolbar {background-color:#BFC193;width:500px;padding:5px;}
#insertForm {position: absolute;height:60px;width:200px;top:50px;left:50px;border:1pt solid black;background-color:#fff;padding:10px;}
</style>
</head>
<body>
<h1>MSHTML Text Editor</h1>
<form id="frmEdit">
<div class="toolbar" id="toolbar">
<input type="button" name="insertHTML" value="insert html" onClick="showForm();"/>
</div>
<div id="insertForm" style="display:none;">
Insert Content Form
<input type="button" value="OK" style="width: 80px" onClick="insertContent();">
</div>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
// functions to execute once the DOM has loaded.
$(document).ready(function() {
pageInit();
});
function pageInit() {
// create iframe
$('.toolbar').after("<iframe id='frameEdit' style='width:500px; height:400px' ></iframe>");
//insert delay for firefox + webkit browsers before turning on designMode open + close seems to do the job
document.getElementById('frameEdit').contentWindow.document.open();
document.getElementById('frameEdit').contentWindow.document.close();
document.getElementById('frameEdit').contentWindow.document.designMode='On';
}
function showForm() {
$('#insertForm').toggle();
}
function insertContent() {
// turn off form
showForm();
// set test content
var htmlContent = "<p>Insert Test</p>";
var doc = document.getElementById('frameEdit').contentWindow.document;
if (doc.selection && doc.selection.createRange) { // IE
var range = doc.selection.createRange();
range.pasteHTML(htmlContent);
} else { // FF
doc.execCommand('insertHTML', false, htmlContent);
}
}
</script>
</form>
</body>
</html>
Make your button unselectable to stop it nicking the focus from the iframe. You can do this in IE using uneselectable="on":
<input type="button" value="OK" unselectable="on"
style="width: 80px" onclick="insertContent();">