I'm using html2canvas and jsPdf to generate Pdf from HTML for one react application.
onClick of my download button I call this function :
printDocument() {
const input = document.getElementById('divToOfferInfo');
const pdf = new jsPDF();
if (pdf) {
html2canvas(input, {
useCORS: true
})
.then(canvas => {
const imgData = canvas.toDataURL('image/png');
console.log(imgData); //Maybe blank, maybe full image, maybe half of image
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save('download.pdf');
});
}
}
The result is totally random. The result of canvas is full, half or blank but not right.
I think that issue is about rendering of React.
Thank you for your help.
I found an alternative solution. Instead to use html2canvas lib, we can use dom-to-image lib. It's working with it.
import domtoimage from 'dom-to-image';
...
printDocument() {
const input = document.getElementById('divToOfferInfo');
const pdf = new jsPDF();
if (pdf) {
domtoimage.toPng(input)
.then(imgData => {
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save('download.pdf');
});
}
}
You can use like this. I am using this code and it is working well.
savePDF() {
const printArea = document.getElementById("printWrapper");
html2canvas(printArea).then(canvas => {
const dataURL = canvas.toDataURL();
const pdf = new jsPDF();
pdf.addImage(dataURL, 'JPEG', 20, 20, 180, 160);
pdf.save('saved.pdf')
})
}
Related
I am trying to use html2canvas and jsPDF to get a PDF of the content of the page,
The idea is that someone could fill data and then print the CV created, but i want to be able to create a A4 pdf from any device, i tried to read the documentation of both libraries but i can't seem to make it work:
This is the output i am getting in the mobile and desktop versions:
Link to screenshots
EDIT:
I tried to configure both html2canvas and jsPDF in PT size:
const printDocument = () => {
setPrintable(true)
const input = document.getElementById('final-section');
html2canvas(input, {
height: 2970,
width: 2100,
scale: 1,
onclone: (cloned) => {
let toPrint = cloned.querySelector("#final-section");
toPrint.style.height = '841.88pt';
toPrint.style.width = '595.27pt';
toPrint.style.position = 'absolute';
toPrint.style.top = 0;
toPrint.style.left = 0;
}
})
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
unit: 'pt',
format: 'a4'
});
pdf.addImage(imgData, 'JPEG', 0, 0, 841.88, 595.27);
// pdf.output('dataurlnewwindow');
pdf.save("download.pdf");
})
;
}
The markup of the html is a content div that contains a modifiable section and the final section that is the printable, in desktop the modifiable section has 45vw and the final section 55 vw,
In mobile each section occupy 100vh and 100vw,
I need to create nicely formatted PDFs from website pages that vary greatly in layout and content. The closest I've come to success is with extensive #media print {} CSS on a page-by-page basis, using the browser's print dialog, then choosing 'Save As PDF' in the print dialog.
I'd like to do all that natively in the app without relying on the print dialog, and I've spent hours trying to beat jsPDF into submission with no luck. Most of my pages include jpgs and svgs as well as text and I have tried html2canvas, dompurify & canvg in conjunction with jsPDF.
I don't mind having to use lots of custom CSS to get it looking good in the PDF, but I can't even get all the elements to appear in the downloaded PDF. Most of the time it's just blank, or one random element.
Doesn't work:
downloadPDF() {
const doc = new jsPDF();
const contentHtml = this.html;
doc.fromHTML(contentHtml, 15, 15, { // error: fromHTML is not a function
width: 170,
});
doc.save("sample.pdf");
},
Also doesn't work:
downloadPDF() {
const doc = new jsPDF();
/** WITH CSS */
var canvasElement = document.createElement("canvas");
html2canvas(this.$refs.printArea, { canvas: canvasElement }).then(function (canvas) {
const img = canvas.toDataURL("image/jpeg", 0.8);
doc.addImage(img, "JPEG", 20, 20);
doc.save("sample.pdf");
});
},
Also also doesn't work:
downloadPDF() {
const pdf = new jsPDF({
orientation: "p",
unit: "pt",
format: "letter",
putOnlyUsedFonts: true,
});
pdf.setFontSize(11);
pdf.html(this.html, {
callback: function (pdf) {
pdf.save("download.pdf");
},
});
},
This is my first post because I am stuck and I didn't find the solution neither here or the web.
I want to convert HTML to PDF using JS. I was searching and the best option seems to be HTML2canvas and JSpdf. But the think is my HTML is storage in a variable:
var test = '<html><head><script type="text/javscript">var number = 123;</script></head><body>
<h1>"the value for number is: " + number</h1></body></html>'
My variable is much more complex and it contains CSS and styles but this is just to get the idea. Then when I try to convert this into canvas it doesn't convert.
const filename = 'ThisIsYourPDFFilename.pdf';
html2canvas(test).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
Does anyone know why this happens? Maybe it is a really stupid question but I don't know how to avoid the errors.
Thank you in advance.
You use string as a parameter for html2canvas, but it takes HTML element:
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
Look at their documentation
I have modified your code:
const html2canvas = require("html2canvas");
const jsPDF = require("jspdf");
html2canvas(document.getElementById("screenshot"), { scale: 1 }).then(
(canvas) => {
document.body.appendChild(canvas);
const filename = "ThisIsYourPDFFilename.pdf";
let pdf = new jsPDF("p", "mm", "a4");
pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0);
pdf.save(filename);
document.body.removeChild(canvas);
}
);
body should contain element with id screenshot:
<div id="screenshot">
Content
</div>
UPDATE:
According to this resource jsPDF has method fromHTML, so you might not need html2canvas
var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
'#elementH': function (element, renderer) {
return true;
}
};
// note here that it uses html
doc.fromHTML(elementHTML, 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
// Save the PDF
doc.save('sample-document.pdf');
I'm looking to convert some simple HTML into a PDF. It seems the easiest way to do this and keep the css styling is to use the 'html2canvas' js library to convert the html to canvas first, and then create the PDF using jsPDF.
The issue I'm getting is that I have both a background image and inline image in my HTML but neither are showing in the PDF once converted. I've created a Codepen here: https://codepen.io/adamboother/pen/NWGeqom
Here's my js that does the conversion:
function convertToPdf()
{
html2canvas(document.querySelector('#certificate')).then(canvas => {
let pdf = new jsPDF('landscape', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
pdf.save('certificate.pdf');
});
}
Has anyone found a fix for this?
I am using useCORS: true to your code and it works, assuming your image is in the server. Besides you can follow below code:
function convertToPdf()
{
html2canvas(document.querySelector('#certificate'), {useCORS: true}).then(function(canvas) {
let img = new Image();
img.src = canvas.toDataURL('image/png');
img.onload = function () {
let pdf = new jsPDF('landscape', 'mm', 'a4');
pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
pdf.save('certificate.pdf');
};
});
}
I m using jsPdf plugin and did this
var data = google.visualization.arrayToDataTable(dataValues,true);
var chart = new google.visualization.CandlestickChart(document.getElementById(id));
google.visualization.events.addListener(chart, 'ready', function () {
var content = '<img src="' + chart.getImageURI() + '">';
$('#graph-images').append(content);
});
function generatePDF() {
var imageTags = $('#graph-images img');
var doc = new jsPDF();
doc.setFontSize(33);
doc.setFillColor(135, 124,45,0);
doc.addImage(imageTags[0], 'png', 10, 10, 150, 100);
doc.save('sample.pdf');
}
by using this i am able to download the pdf file while open that pdf file in adobe reader its saying 110 error.
Can Anybody Help in this, thanks.
You should pass image URI to addImage():
google.charts.setOnLoadCallback(function() {
var data = google.visualization.arrayToDataTable(dataValues, true)
var chart = new google.visualization.CandlestickChart(document.getElementById(id))
chart.draw(data)
imgData = chart.getImageURI()
})
function generatePDF() {
var doc = new jsPDF();
doc.setFontSize(33);
doc.setFillColor(135, 124,45,0);
doc.addImage(imgData, 'png', 10, 10, 150, 100);
doc.save('sample.pdf');
}
Please check this live demo for more details https://jsfiddle.net/p1frmxvp/1/
UPDATE
Turns out the error happens only when we use jspdf 1.3.2 and open the pdf using Adobe Reader as explained here. The only solution so far is either opening the pdf using other viewer (Chrome, Foxit Reader .etc) or downgrading jspdf to 1.2.61. I have updated the jsfiddle above to use the downgraded jspdf.