Related
Is it possible to save HTML page as PDF using JavaScript or jquery?
In Detail:
I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file.
Is it possible using JavaScript or jquery?
This might be a late answer but this is the best around:
https://github.com/eKoopmans/html2pdf
Pure javascript implementation.
Allows you to specify just a single element by ID and convert it.
Yes, Use jspdf To create a pdf file.
You can then turn it into a data URI and inject a download link into the DOM
You will however need to write the HTML to pdf conversion yourself.
Just use printer friendly versions of your page and let the user choose how he wants to print the page.
Edit: Apparently it has minimal support
So the answer is write your own PDF writer or get a existing PDF writer to do it for you (on the server).
Ya its very easy to do with javascript. Hope this code is useful to you.
You'll need the JSpdf library.
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
// This code is collected but useful, click below to jsfiddle link.
</script>
jsfiddle link here
I used jsPDF and dom-to-image library to export HTML to PDF.
I post here as reference to whom concern.
$('#downloadPDF').click(function () {
domtoimage.toPng(document.getElementById('content2'))
.then(function (blob) {
var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
pdf.save("test.pdf");
});
});
Demo: https://jsfiddle.net/viethien/md03wb21/27/
You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
Example code:
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
Here is how I would do it, its an idea not bulletproof design, you need to modify it
The user clicks the save as PDF button
The server is sent a call using ajax
The server responds with a URL for PDF generated using HTML, I have used Apache FOP very succssfully
The js handling the ajax response does a location.href to point the URL send by JS and as soon as that URL loads, it sends the file using content disposition header as attachment forcing user to download the file.
It is much easier and reliable to convert html to pdf server side. We are using Google Puppeteer. It is well maintained with wrappers for any server side language of your choosing. Puppeteer uses headless Chrome to generate screenshots and/or PDF files. It will save you a LOT of headache especially if you need to generate complex PDF files with tables, images, graphs, multiple pages and so
https://developers.google.com/web/tools/puppeteer/
There is another very obvious way to convert HTML to PDf using JavaScript: use an online API for that. This will work fine if you don't need to do the conversion when the user is offline.
PdfMage is one option that has a nice API and offers free accounts. I'm sure you can find many alternatives (for example, here)
For PdfMage API you'd have something like this:
$.ajax({
url: "https://pdfmage.org/pdf-api/v1/process",
type: "POST",
crossDomain: true,
data: { Html:"<html><body>Hi there!</body></html>" },
dataType: "json",
headers: {
"X-Api-Key": "your-key-here" // not very secure, but a valid option for non-public domains/intranet
},
success: function (response) {
window.location = response.Data.DownloadUrl;
},
error: function (xhr, status) {
alert("error");
}
});
I know this is an old question, but depending on the readers use case an easy way is to call window.print() and tell the user to choose the save as PDF option. In CSS you can use media queries to hide or show content specifically for printing so you can control what is shown on the PDF. For example I use these .no-print and .only-print for this purpose.
.only-print {
display: none
}
#media print {
.no-print {
display: none
}
.only-print {
display: block
}
}
In my use case I hide all the navigation and buttons stuff, I also hide some collapsed blocks and instead show all the uncollapsed blocks.
In short: no.
The first problem is access to the filesystem, which in most browsers is set to no by default due to security reasons. Modern browsers sometimes support minimalistic storage in the form of a database, or you can ask the user to enable file access.
If you have access to the filesystem then saving as HTML is not that hard (see the file object in the JS documentation) - but PDF is not so easy. PDF is a quite advanced file-format that really is ill suited for Javascript. It requires you to write information in datatypes not directly supported by Javascript, such as words and quads. You also need to pre-define a dictionary lookup system that must be saved to the file. Im sure someone could make it work, but the effort and time involved would be better spent learning C++ or Delphi.
HTML export however should be possible if the user gives you non restricted access
Yes. For example you can use the solution by https://grabz.it.
It's got a Javascript API which can be used in different ways to grab and manipulate the screenshot. In order to use it in your app you will need to first get an app key and secret and download the free Javascript SDK.
So, let's see a simple example for using it:
//first include the grabzit.min.js library in the web page
<script src="grabzit.min.js"></script>
//include the code below to add the screenshot to the body tag
<script>
//use secret key to sign in. replace the url.
GrabzIt("Sign in to view your Application Key").ConvertURL("http://www.google.com").Create();
</script>
Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.
That's the simplest one. For more examples with image manipulation, attaching screenshots to elements and etc check the documentation.
$('#cmd2').click(function() {
var options = {
//'width': 800,
};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#content2"), -1, 220, options, function() {
pdf.save('admit_card.pdf');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">
<div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">
<div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">
<h2>Entrance Exam Hall Ticket</h2>
</div>
<div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">
<div class="innerdiv" style="width: 80%;float: left;">
<div class="restDet">
<div class="div">
<div class="label" style="width: 30%;float: left;">
<strong>Name</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>Santanu Patra</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>D.O.B.</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>17th April, 1995</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Address</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Contact Number</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>9874563210</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Email Id</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>santanu#macallied.com</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Parent(s) Name</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>S. Patra</span><br /><span>7896541230</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Exam Center</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>Institute of Engineering & Management</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Hall Number</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>COM-32</span>
</div>
</div>
</div>
</div>
<div class="sideDiv" style="width: 20%;float: left;">
<div class="atts" style="float: left;width: 100%;">
<div class="photo" style="width: 115px;height: 150px;float: right;">
<img src="images/candidateImg.gif" style="width: 100%;"/>
</div>
<div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">
<small>Self Attested</small>
</div>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-info" id="cmd2">Download Token</button>
Had similar issue, could not use jspdf since my legacy code contained multiple tables with several colspan inside. In Jspdf thead > th's must match tbody > tr > td
I ended up using html2pdf package which worked for me
on your file add the library
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js" integrity="sha512-vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Get the content you want to save as pdf
var pdf_content = document.getElementById("pdf_body");
Add option or configuration to your file
var options = {
margin: 1,
filename: 'isolates.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
Save the file
html2pdf(pdf_content, options);
I'm using angular file upload (https://github.com/nervgh/angular-file-upload/wiki/Module-API) and currently trying to access the uploaded file url before saving (so I can use it as a background image). I realize that you can easily create a thumbnail of the file, but I'm having issues accessing the url so I can use it as a background image (since I want to position the image and not scale it and show the whole image as thumbnail would do).
So I can access the image for a thumbnail:
<div ng-repeat="item in uploader.queue">
<div ng-thumb="{ file: item._file, height: 202, width: 376 }"></div>
</div>
But this does not work (I'm assuming because item._file is the actual image and background-image requires a url)
<div ng-repeat="item in uploader.queue">
<div class="row" ng-style="{'background-image':'url({{item._file}})'}">
</div>
Syntax wise, I know the ng-style is fine since I tried replaced the item._file above with a public url and the styling worked as expected. I also tried replacing item._file with item.url since url is a property of it and url is apparently null so that didn't work. Any ideas on how I can achieve this or alternate solutions?
My asp.net application contains img with another aspx file in src attribute,
with a picture,
<img src="/picture.aspx?Param=3" alt="picture"/>
I have to change the img to div with backgroung-image.
<div style="background-image:url('/picture.aspx?Param=3')" />
Any way to do it?
Thanks!
The way I would handle this is creating a method that returns a base64 png in a similar manner as you return an image resource from picture.aspx?param=3.
Convert.ToBase64String(File.ReadAllBytes(Server.MapPath(#"image_file.png")));
Then you can assign it to the background:
<div style='background-image: url(data:image/png;base64," + base64String + ")'></div>
Html:
<div id="dv" />
JQuery
$('#dv').load('picture.aspx?Param=3');
In a view, I have the following fieldset which displays images, in thumbnail type form, associated with a particular item:
<fieldset style="position:absolute; top:113px; left: 1050px; width: 300px;">
<legend>Photos</legend>
<div>
<img src="#Url.Action("GetImage1")" alt="" />
<img src="#Url.Action("GetImage2")" alt="" />
<img src="#Url.Action("GetImage2")" alt="" />
</div>
</fieldset>
In my controller, I have the following code:
public void GetImage1()
{
BicycleSellerListing bicyclesellerlisting = db.BicycleSellerListing.Find(1023);
WebImage wbImage = new WebImage(bicyclesellerlisting.ImageList.First().Image);
wbImage.Resize(100, 100);
wbImage.FileName = "Item.jpg";
wbImage.Write();
}
All of this works fine. I am fairly new to MVC, HTML and JavaScript, and don't know how to do the following. What I would like to do is to allow the user to click on an image and have another View load where I display the full size of the image in that view.
It depends what you want to get from this. Do you want it to display the image alone on a new page or show the full image on the same page using AJAX?
If it's the latter, you might want to look into using partial views.
Is it possible to save HTML page as PDF using JavaScript or jquery?
In Detail:
I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file.
Is it possible using JavaScript or jquery?
This might be a late answer but this is the best around:
https://github.com/eKoopmans/html2pdf
Pure javascript implementation.
Allows you to specify just a single element by ID and convert it.
Yes, Use jspdf To create a pdf file.
You can then turn it into a data URI and inject a download link into the DOM
You will however need to write the HTML to pdf conversion yourself.
Just use printer friendly versions of your page and let the user choose how he wants to print the page.
Edit: Apparently it has minimal support
So the answer is write your own PDF writer or get a existing PDF writer to do it for you (on the server).
Ya its very easy to do with javascript. Hope this code is useful to you.
You'll need the JSpdf library.
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
// This code is collected but useful, click below to jsfiddle link.
</script>
jsfiddle link here
I used jsPDF and dom-to-image library to export HTML to PDF.
I post here as reference to whom concern.
$('#downloadPDF').click(function () {
domtoimage.toPng(document.getElementById('content2'))
.then(function (blob) {
var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
pdf.save("test.pdf");
});
});
Demo: https://jsfiddle.net/viethien/md03wb21/27/
You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
Example code:
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
Here is how I would do it, its an idea not bulletproof design, you need to modify it
The user clicks the save as PDF button
The server is sent a call using ajax
The server responds with a URL for PDF generated using HTML, I have used Apache FOP very succssfully
The js handling the ajax response does a location.href to point the URL send by JS and as soon as that URL loads, it sends the file using content disposition header as attachment forcing user to download the file.
It is much easier and reliable to convert html to pdf server side. We are using Google Puppeteer. It is well maintained with wrappers for any server side language of your choosing. Puppeteer uses headless Chrome to generate screenshots and/or PDF files. It will save you a LOT of headache especially if you need to generate complex PDF files with tables, images, graphs, multiple pages and so
https://developers.google.com/web/tools/puppeteer/
There is another very obvious way to convert HTML to PDf using JavaScript: use an online API for that. This will work fine if you don't need to do the conversion when the user is offline.
PdfMage is one option that has a nice API and offers free accounts. I'm sure you can find many alternatives (for example, here)
For PdfMage API you'd have something like this:
$.ajax({
url: "https://pdfmage.org/pdf-api/v1/process",
type: "POST",
crossDomain: true,
data: { Html:"<html><body>Hi there!</body></html>" },
dataType: "json",
headers: {
"X-Api-Key": "your-key-here" // not very secure, but a valid option for non-public domains/intranet
},
success: function (response) {
window.location = response.Data.DownloadUrl;
},
error: function (xhr, status) {
alert("error");
}
});
I know this is an old question, but depending on the readers use case an easy way is to call window.print() and tell the user to choose the save as PDF option. In CSS you can use media queries to hide or show content specifically for printing so you can control what is shown on the PDF. For example I use these .no-print and .only-print for this purpose.
.only-print {
display: none
}
#media print {
.no-print {
display: none
}
.only-print {
display: block
}
}
In my use case I hide all the navigation and buttons stuff, I also hide some collapsed blocks and instead show all the uncollapsed blocks.
In short: no.
The first problem is access to the filesystem, which in most browsers is set to no by default due to security reasons. Modern browsers sometimes support minimalistic storage in the form of a database, or you can ask the user to enable file access.
If you have access to the filesystem then saving as HTML is not that hard (see the file object in the JS documentation) - but PDF is not so easy. PDF is a quite advanced file-format that really is ill suited for Javascript. It requires you to write information in datatypes not directly supported by Javascript, such as words and quads. You also need to pre-define a dictionary lookup system that must be saved to the file. Im sure someone could make it work, but the effort and time involved would be better spent learning C++ or Delphi.
HTML export however should be possible if the user gives you non restricted access
Yes. For example you can use the solution by https://grabz.it.
It's got a Javascript API which can be used in different ways to grab and manipulate the screenshot. In order to use it in your app you will need to first get an app key and secret and download the free Javascript SDK.
So, let's see a simple example for using it:
//first include the grabzit.min.js library in the web page
<script src="grabzit.min.js"></script>
//include the code below to add the screenshot to the body tag
<script>
//use secret key to sign in. replace the url.
GrabzIt("Sign in to view your Application Key").ConvertURL("http://www.google.com").Create();
</script>
Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.
That's the simplest one. For more examples with image manipulation, attaching screenshots to elements and etc check the documentation.
$('#cmd2').click(function() {
var options = {
//'width': 800,
};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#content2"), -1, 220, options, function() {
pdf.save('admit_card.pdf');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">
<div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">
<div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">
<h2>Entrance Exam Hall Ticket</h2>
</div>
<div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">
<div class="innerdiv" style="width: 80%;float: left;">
<div class="restDet">
<div class="div">
<div class="label" style="width: 30%;float: left;">
<strong>Name</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>Santanu Patra</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>D.O.B.</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>17th April, 1995</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Address</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Contact Number</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>9874563210</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Email Id</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>santanu#macallied.com</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Parent(s) Name</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>S. Patra</span><br /><span>7896541230</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Exam Center</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>Institute of Engineering & Management</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Hall Number</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>COM-32</span>
</div>
</div>
</div>
</div>
<div class="sideDiv" style="width: 20%;float: left;">
<div class="atts" style="float: left;width: 100%;">
<div class="photo" style="width: 115px;height: 150px;float: right;">
<img src="images/candidateImg.gif" style="width: 100%;"/>
</div>
<div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">
<small>Self Attested</small>
</div>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-info" id="cmd2">Download Token</button>
Had similar issue, could not use jspdf since my legacy code contained multiple tables with several colspan inside. In Jspdf thead > th's must match tbody > tr > td
I ended up using html2pdf package which worked for me
on your file add the library
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js" integrity="sha512-vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Get the content you want to save as pdf
var pdf_content = document.getElementById("pdf_body");
Add option or configuration to your file
var options = {
margin: 1,
filename: 'isolates.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
Save the file
html2pdf(pdf_content, options);