No styling appear when render PDF from HTML with jsPDF - javascript

I'm developing a page and I need to export my page to PDF. Here 's an overview of my page
http://i.imgur.com/4QmY3fp.jpg
Library jsPdf:
<script type="text/javascript" src="scripts/jspdf/jspdf.js"></script>
<script type="text/javascript" src="scripts/jspdf/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="scripts/jspdf/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="scripts/jspdf/jspdf.plugin.from_html.js"></script>
<script type="text/javascript" src="scripts/jspdf/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="scripts/jspdf/jspdf.plugin.cell.js"></script>
<script type="text/javascript" src="scripts/jspdf/libs/Deflate/deflate.js"></script>
<script type="text/javascript" src="scripts/jspdf/libs/Blob.js/Blob.js"></script>
<script type="text/javascript" src="scripts/jspdf/libs/FileSaver.js/FileSaver.js"></script>
Here 's the js code for jspdf:
function demoFromHTML() {
var doc = new jsPDF('p', 'in', 'letter');
var source = window.document.getElementsByTagName("body")[0];
var specialElementHandlers = {
'#bypassme': function(element, renderer) {
return true;
}
};
doc.fromHTML(
source, // HTML string or DOM elem ref.
0.5, // x coord
0.5, // y coord
{
'width': 100, // max width of content on PDF
'elementHandlers': specialElementHandlers
});
doc.output('dataurl');
}
When I click the button, it returns a pdf like this and I'm a total newbie in this jsPDF so I don't know what I did wrong
http://i.imgur.com/5cMgNR6.jpg

Related

Using jsPDF to create a PDF from an iframe

Ok, I have scoured the internet for a solution to this but I can't find anything. I am trying to find a way to save the contents of an iframe as a PDF. I am always running into an issue where the PDF is just blank. It seems that jsPDF is the only way. I'm kind of wondering if the reason this isn't working is because of the fromHTML() function. I'm not sure. If any of you have figured out a solution I would be very appreciative!!
Here is some sample code you can try in an HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
source = $('#frame')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
pdf.fromHTML(
source,
margins.left,
margins.top, {
'width': margins.width,
'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('Test.pdf');
}, margins);
}
</script>
<button onclick="javascript:demoFromHTML();">PDF</button>
<iframe id="frame" src='https://wikipedia.org/wiki/Main_Page' style="width: 75%;height: 75%;"></iframe>
Go through this article : Convert HTML/CSS Content to a Sleek Multiple Page PDF File Using jsPDF JavaScript library. The provided script allows you to convert any HTML element to PDF. I modified the generate() function slightly so that it takes any HTML element id name and export it as PDF file:
generate = function(doc)
{
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.setFontSize(18);
pdf.fromHTML(document.getElementById(doc),
margins.left, // x coord
margins.top,
{
// y coord
width: margins.width// max width of content on PDF
},function(dispose) {
headerFooterFormatting(pdf, pdf.internal.getNumberOfPages());
},
margins);
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
};
It works 100% on Chrome but Im not sure about other browsers.
Try this solution.
<button id="generatePDF">Generate PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$( '#generatePDF' ).click( function()
{
var pdf = new jsPDF('a4');
pdf.text("Some text inside PDF", 10, 10);
$( '#docpdf' ).attr('src', pdf.output('datauristring'));
});
</script>
<iframe id="docpdf" style="background-color:#EEE; height:400px;">
PDF goes here
</iframe>
A wild guess here but I think this has to do with the fact that Iframes from other domains are protected.
Read into 'cross-domain policy', if it's the cause I'm quite sure you can't work around it very easy.
try
var source = window.document.getElementsByTagName(tagName)[0];
instead of
source = $('#frame')[0];

how to download the div tag description in image format using js

update with my error
$(function() {
var specialElementHandlers = {
'#editor': function(element, renderer) {
return true;
}
};
$('#cmd').click(function() {
var doc = new jsPDF();
doc.fromHTML($('#target').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.1.135/jspdf.min.js"></script>
<script type="text/javascript" src="http://cdn.uriit.ru/jsPDF/libs/adler32cs.js/adler32cs.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script type="text/javascript" src="library/BlobBuilder.js"></script>
<script type="text/javascript" src="pdf.js"></script>
<div id="target">
<div id="content">
<h3>Hello, this is mathit app</h3>
<a class="upload">Upload to Formulas</a>
<h2>
This is <b>10th Std Notes</b> <span style="color: red"></span>
</h2>
<p>Study about The polynomial of degree two is called quadratic polynomial and equation corresponding to a quadratic polynomial P(x) is called a quadratic equation in variable x. Thus, P(x) = ax2 + bx + c =0, R is known as the standard form of quadratic
equation. There are two types of quadratic equation. (i) Complete quadratic equation : The equation ax2 + bx + c =0 where a,b,c is not equal to 0. (ii) Pure quadratic equation : An equation in the form of ax2 = 0, a is not equal to 0, b,c is equal
to 0.
</p>
</div>
</div>
<button id="cmd">generate PDF</button>
How to download the div tag details and save have png image. I have some code in download the double time download in pdf i want to download the one in pdf and another one in png image how to change the code please help me for example user click the button to down load the pdf and png image.
You can actually do this with the help of HTML2Canvas jquery file and HTML5 download attribute.
$(document).ready(function() {
var element = $("#html-content-holder"); // global variable
var getCanvas; // global variable
html2canvas(element, {
onrendered: function(canvas) {
getCanvas = canvas;
}
});
var specialElementHandlers = {
'#editor': function(element, renderer) {
return true;
}
};
$("#cmd").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");
$("#cmd").attr("download", "Sample_Pic.png").attr("href", newData);
var doc = new jsPDF();
doc.fromHTML($('#target').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
});
jsfiddle

error:Incomplete or corrupt PNG file in using jspdf

I want to add 2 images in my pdf when i click "create-pdf" icon.
First image is a canvas that convert to image and it correctly work.
var canvas = document.getElementsByClassName("jade-schematic-diagram");
img = canvas[0].toDataURL("image/png");
img.id="pic2";
doc = new jsPDF({
unit:'px',
format:'a4'
});
doc.addImage(img, 'JPEG', 20, 20,400,150);
This section of my code got this error:
Error: Incomplete or corrupt PNG file
var srcpath;
var element = $(".plot-waveforms"); // global variable
var imgageData = new Image();
imgageData.id = "pic";
html2canvas(element, {
onrendered: function (canvas) {
srcpath = canvas.toDataURL("image/png");
}
});
imgageData.src=srcpath;
doc.addImage(imgageData , 'PNG', 20, 20,400,150);
I was added these script in my html head tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/niklasvh/html2canvas/0.5.0-alpha2/dist/html2canvas.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/MrRio/jsPDF/master/dist/jspdf.min.js"></script>
<script type="text/javascript" src="zlib.js"></script>
<script type="text/javascript" src="png.js"></script>
<script type="text/javascript" src="addimage.js"></script>
<script type="text/javascript" src="png_support.js"></script>
Please help me. I searched a lot but i don't find anything.
onrendered is an async function, isn't it? https://github.com/niklasvh/html2canvas/issues/470
So you have to place srcpath inside onrendered
html2canvas(element, {
onrendered: function (canvas) {
srcpath = canvas.toDataURL("image/png");
imgageData.src=srcpath;
doc.addImage(imgageData , 'PNG', 20, 20,400,150);
}
});
The image has not finished loading when you send it to jsPDF. So in order to ensure that the image has finished loading before adding it to the document, Add this to your code :
var myImage = new Image();
myImage .src = 'https://www.myserver.com/somepath/myImage.png';
myImage .onload = function(){
doc.addImage(myImage , 'png', 5, 5, 40, 10);
doc.save('myPDF.pdf');
};

Jspdf Alignment/ layout not working

I am doing an HTML to pdf conversion with jspdf
Here is my running code...
http://codepen.io/anon/pen/dPZaYN
You can see the output (below) is different from the PDF..There are no borders and alignment.
I am not able to achieve simple layout / alignment , padding/float etc..
This is how it should look (you can also see here my Html code)
http://screencast.com/t/xE6fbJKrA9m
But when i Get the pdf of this from jspdf it looks like this
http://screencast.com/t/z8cizeY9
This is my jspdf Code ..
var doc = $wnd.jsPDF('p', 'pt', 'a4', true);
var source = $('#content').first();
var specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true;
}
};
doc.fromHTML(
htmltest,
{
'elementHandlers': specialElementHandlers
});
doc.save('Test.pdf');
This is my head
<script type="text/javascript" src="jspdf/jspdf.js"></script>
<script type="text/javascript" src="jspdf/FileSaver.js"></script>
<script type="text/javascript" src="jspdf/jspdf.min.js"></script>
<script type="text/javascript" src="jspdf/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jspdf/libs/adler32cs.js"></script>
<script type="text/javascript" src="jspdf/BlobBuilder.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script>
jsPDF's html plugin does not support most css. But despair not, here is a work around.
Try it out:
$( 'a' ).hide();
html2canvas( document.body, { onrendered : function( canvas ) { 'use strict';
var pdf = new jsPDF(), border = 10, width = 210-border*2;
pdf.addImage( canvas.toDataURL( 'image/jpeg' , 0.98 ), 'JPEG',
border, border, width, canvas.height*width/canvas.width );
// pdf.save() does not work on StackOverflow because of cross origin restriction
$('a').show()[0].href = pdf.output( 'dataurlstring' );
// IE 11 does not allow datauri pdf, use save() instead
} } );
body{font:12px "Times New Roman",serif;}h1{font-size:24px;line-height:24px;font-weight:bold;margin-top:0;text-align:right;margin-bottom:5px;}#render_me > div > div{float:right}#render_me > div > div > div{border-bottom:1px solid black;border-right:1px solid black;padding:3px; text-align:center}.b_top{border-top:1px solid black;}.f_c_b_left:last-child{border-left:1px solid black;}
PDF<br>(Ctrl+Click me or open me in new window)
<div id="render_me"><div>
<h1>Invoice</h1>
<div><div class="b_top">Invoice #</div><div>00001-2</div></div>
<div class="f_c_b_left"><div class="b_top">Date</div><div>2015-02-05</div></div>
</div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src='http://parall.ax/parallax/js/jspdf.js'></script>
The idea is, renders the HTML onto a canvas using html2canvas, then put the screenshot into PDF.
This is not perfect, but at least the elements will be in correct positions and alignments.
Drawbacks:
Like jsPDF's HTML renderer, html2canvas understand few CSS. The major difference is that html2canvas can access the layout did by the browser.
The image only have 96dpi, causing low quality.
Result PDF will be relatively big.
For now, this is my best HTML to PDF solution.
To get better result, I will manually build the PDF (without HTML).
I cannot get the pdf link in this example to open in new window or download, as long as it is ran in StackOverflow's Code snippet. If you put the code elsewhere you can call pdf.save like this fiddle: http://jsfiddle.net/xwksc4ku/1

How to add header in pdf generated from HTML

I am working on codeigniter. I want to add save to pdf functionality to one of the div. I am using html2canvas to print it. My problem is I want to add a logo & some other information at the header of the pdf, which is not visible on the webpage. I dont know how to do this. Below is my code.
<script type='text/javascript' src="<?php echo site_url('assets/js/html2canvas.js'); ?>"></script>
<script type='text/javascript' src="<?php echo site_url('assets/js/jspdf.debug.js'); ?>"></script>
<script type='text/javascript'>//<![CDATA[
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML($('#content')[0], function () {
pdf.save('test.pdf');
});
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 30,
bottom: 30,
left: 30,
width: '100%'
//color: '#000'
};
pdf.addHTML()(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('test.pdf');
}, margins);
}
</script>
<div id="content">
Save this to PDF
</div>
Pls help.
Before calling to addHTML, you can add images or text to your jsPDF object:
var pdf = new jsPDF('p','pt','a4');
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAXwBfAAD/2wBDAAoHBwkHBgoJCAkLCwoMDxkQDw4ODx4WFxIZJCAmJSMgIyIoLTkwKCo2KyIjMkQyNjs9QEBAJjBGS0U+Sjk/QD3/2wBDAQsLCw8NDx0QEB09KSMpPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT3/wgARCAAaABQDAREAAhEBAxEB/8QAGQAAAgMBAAAAAAAAAAAAAAAABQYAAwQB/8QAGAEBAQEBAQAAAAAAAAAAAAAAAwEAAgT/2gAMAwEAAhADEAAAAXKbOK1c92KOHzuQcxaHNjdidpy5yl//xAAfEAACAQMFAQAAAAAAAAAAAAABAgADEhMEEBEhIjH/2gAIAQEAAQUC+QuVq6duEqnoephWKDia/FLjLjt//8QAHREAAgIBBQAAAAAAAAAAAAAAAAIBEQMSEyAiMf/aAAgBAwEBPwEhIZLj2DOttcCkNp7G8xZfH//EAB4RAAIDAAEFAAAAAAAAAAAAAAABAgMREiAhIjFR/9oACAECAQE/AR2ONmS9MolkcZZ8aHDl4b2FTEaEun//xAAhEAABAwMEAwAAAAAAAAAAAAABAAIRAxAxEjJBQiFhYv/aAAgBAQAGPwJQ7acIg8FQWFzfS0B0t+shcpkNqHx1KqahU29rZKybf//EAB0QAQADAQACAwAAAAAAAAAAAAEAESExQVFhgZH/2gAIAQEAAT8hUFrUE1U6+ZZvXITcrvpNdp4xEO+l1b7Gv7BQdYMALdXDkpwD7ipT+kOT/9oADAMBAAIAAwAAABBnmCSOz//EABsRAQACAwEBAAAAAAAAAAAAAAEAESExYSBx/9oACAEDAQE/EAXUQdz5KIsIMuNjTLWFPNMVwaOQoRsVXn//xAAcEQEAAgIDAQAAAAAAAAAAAAABABEhMSBhcVH/2gAIAQIBAT8QUMsIdQ9/JZNpSUTIImK3bZ5AbtfZa3cpbvj/AP/EABwQAQACAwEBAQAAAAAAAAAAAAEAESExQXFRwf/aAAgBAQABPxCsIatahd4Y+dDAb93fjD4HtO4qLlXU0ej2pdETsO11xEdV8cP2hExkSA2d3NHkA0Q0CIxSEyKmjyf/2Q==';
pdf.addImage(imgData, 'JPEG', 20, 20, 20, 26);
pdf.text(50, 40, "Header");
pdf.addHTML(document.body,40,100,function() {
pdf.save('web.pdf');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<body>
<p id="to-pdf">HTML content...</p>
</body>
Images must be encoded with base64. You can use this tool for that: http://dataurl.net/#dataurlmaker

Categories

Resources