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();
Related
I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much
On my website, I created a string replace method, but when I checked the page on my android phone web browser and I saw that doesn't working.
Here is the example:
/*Normally it's working with page onload*/
function changeclr() {
var body = document.getElementById('body').innerHTML;
var all = body.replace(/</g, '<code><').replace(/>/g, '></code>').replace(/</g, '<span style="color:blue;"><</span>').replace(/>/g, '<span style="color:blue;">></span>');
document.getElementById('body').innerHTML = all;
}
code {
color: brown;
}
<div id="body">
<p>Here is an example <li>text</li></p>
<button type="button" onclick="changeclr()">Try</button>
</div>
Do you know why is not working on mobile web browser?
Maybe javascript of your browser is disabled or not supported!
I have a page which has a lot of buttons. What I need to do is to show a div near the button. I tried this:
<style>
#noteDiv {display:none; position: absolute; background-color: white; border: 1px solid blue;}
</style>
<script>
function showNote(e) {
var x = 0, y = 0;
if (!e) e = window.event;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
document.getElementById("noteDiv").style.display = "block";
document.getElementById("noteDiv").style.left = (x)+"px";
document.getElementById("noteDiv").style.top = (y-350)+"px";
}
function hideNote() {
document.getElementById("noteDiv").style.display = "none";
}
</script>
<body>
<?php
echo "<button type ='button' id = 'noteButton'>Note</button>";
echo "<script>document.getElementById('noteButton').onclick = showNote;\n";
echo "</script>";
?>
</body>
<div id='noteDiv' >
<div ><span onclick="hideNote()">Close</span></div>
<br clear="all">
<div id='noteContent' style='max-height: 30em'></div>
</div>
It does work. But sometimes the page will show one more div on top of the page, like a warning message, and thus the noteDiv's position will be far from the buttons to which it should attach.
My thinking is to get the position of the buttons, and send the x, y values of the button position to the function showNote(), from there show the noteDiv. I don't know if this idea is reasonable and how to get and transfer the current clicked button's position to javascript?
Any suggestions and hints will be appreciated!
From the beginning.
Load javascript on top of your page is a very bad idea. I'll let the tons of web articles to explain you why. Just to say one reason, the js files are downloaded before the html is rendered (depending on the browser), resulting in a slower rendering of the page.
About your approach:
Three words: separation of concerns. Positioning dom elements is not what belongs to javascript (except some very rare occasions).
Styling the DOM, which comprehends positioning of the objects, belongs to the Cascading Style Sheet, also known as CSS.
So if something is not rendered in the right way, don't try to fix it with javascript. It will only drives you to enormous headaches.
For a better answer, please provide a code that can show us the error.
UPDATE
Here is a working example (probably not optimised) of what you are maybe trying to achieve. Please, please, please, please... read a book about html, css and js. It's totally worth it. I didn't use php, didn't need it.
Just for the records, the general structure of an html page I personally use is like this one:
html
head
title
meta
styles link
styles sections
js **LIBRARIES** which need to be loaded on **TOP**
google analytics
body
html content
js **LIBRARIES** which need to be loaded on **BOTTOM**
js scripts
And for your sanity, and of the people who helps you, indent correctly (it's also a sign of respect to the people who are reading your code).
Here is the code with the snippet:
function toggleNote(id) {
var noteParent = document.getElementById(id);
var note = noteParent.querySelector('.note');
var display = "none";
if (note.style.display == "none" || note.style.display == "" ) {
display = "block";
}
note.style.display = display;
}
.note {
display: none;
position: relative;
background-color: white;
border: 1px solid blue;
}
.noteContent {
max-height: 30em
}
<body>
<div class="buttonContainer" id="note0">
<button id='noteButton' onclick="toggleNote('note0')">Note</button>
<div class='note'>
<div>
<button onclick="toggleNote('note0')">Close</button>
</div>
<br clear="all">
<div class='noteContent'>It's something!</div>
</div>
</div>
</body>
All the HTML like <button> <div> <span> <ul><li> <table> etc MUST be inside the <body> </body> tag:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<!-- you can include css and javascript here -->
<!-- but best place to include javascript ist at the bottom -->
<!-- see last comment -->
</head>
<body>
<?php echo '<button type="button" id="noteButton">Note</button>'; ?>
<!-- best place to include javascript or echo them with PHP what ever
right before the closing body tag -->
</body>
</html>
You are echoing a <button> via PHP before the opening <body> tag which is wrong. Try use something like firebug and https://validator.w3.org/
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'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();">