Skip to content

Instantly share code, notes, and snippets.

@arangates
Created June 11, 2017 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arangates/d7d40ff4c3bf0914bd2ca9a59b3bc6f2 to your computer and use it in GitHub Desktop.
Save arangates/d7d40ff4c3bf0914bd2ca9a59b3bc6f2 to your computer and use it in GitHub Desktop.
JsPDF (PDF from HTML tool)
// JsPDF:
// creating pdf using jspdf api's
createPDF(){
const doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
doc.text(35, 25, 'Paranyan loves jsPDF');
doc.addImage(imgh, 'JPEG', 15, 40, 180, 160)
doc.save(this.name);
};
// export
export1(){
// promise method
// html2canvas(this.el.nativeElement).then(function(canvas) {
// const img = canvas.toDataURL();
// window.open(img);
// });
html2canvas(this.el.nativeElement, <Html2Canvas.Html2CanvasOptions>{
scale: 2,
onrendered: function (canvas) {
const img = canvas.toDataURL();
const doc = new jsPDF();
doc.addImage(img, 'PNG', 0, 0, img.width, img.height);
window.open(img);
doc.save('imgtest.pdf');
},
letterRendering: true
});}
// Export customized
exportTwo() {
const canvasToImage = function (canvas) {
const img = new Image();
const dataURL = canvas.toDataURL('image/png');
img.src = dataURL;
return img;
};
const canvasShiftImage = function (oldCanvas, shiftAmt) {
shiftAmt = parseInt(shiftAmt) || 0;
if (!shiftAmt) { return oldCanvas; }
const newCanvas = document.createElement('canvas');
newCanvas.height = oldCanvas.height - shiftAmt;
newCanvas.width = oldCanvas.width;
const ctx = newCanvas.getContext('2d');
const img = canvasToImage(oldCanvas);
ctx.drawImage(img, 0, shiftAmt, img.width, img.height, 0, 0, img.width, img.height);
return newCanvas;
};
const canvasToImageSuccess = function (canvas) {
const pdf = new jsPDF('l', 'px'),
pdfInternals = pdf.internal,
pdfPageSize = pdfInternals.pageSize,
pdfScaleFactor = pdfInternals.scaleFactor,
pdfPageWidth = pdfPageSize.width,
pdfPageHeight = pdfPageSize.height,
htmlPageHeight = canvas.height,
htmlScaleFactor = canvas.width / (pdfPageWidth * pdfScaleFactor);
let totalPdfHeight = 0,
safetyNet = 0;
while (totalPdfHeight < htmlPageHeight && safetyNet < 30) {
const newCanvas = canvasShiftImage(canvas, totalPdfHeight);
pdf.addImage(newCanvas, 'png', 0, 0, pdfPageWidth, 0, null, 'NONE');
totalPdfHeight += (pdfPageHeight * pdfScaleFactor * htmlScaleFactor);
if (totalPdfHeight < htmlPageHeight) {
pdf.addPage();
}
safetyNet++;
}
pdf.save('besttest.pdf');
};
html2canvas(this.el.nativeElement, <Html2Canvas.Html2CanvasOptions>{
onrendered: function (canvas: HTMLCanvasElement) {
canvasToImageSuccess(canvas);
const pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML(canvas, function() {
pdf.save('web.pdf');
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment