Skip to content

Instantly share code, notes, and snippets.

@sriramrudraraju
Created December 31, 2019 17:37
Show Gist options
  • Save sriramrudraraju/f9f9a22bb9c10a3f63661299ea21668d to your computer and use it in GitHub Desktop.
Save sriramrudraraju/f9f9a22bb9c10a3f63661299ea21668d to your computer and use it in GitHub Desktop.
// using jspdf, htmlcanvas
import React, { FC, useCallback, RefObject } from 'react';
import { Button } from '@material-ui/core';
import CloudDownloadIcon from '@material-ui/icons/CloudDownload';
import html2canvas from 'html2canvas';
import { useStyles } from './pdf-download.styles';
interface PdfDownloadProps {
filename: string;
eleRef: RefObject<HTMLDivElement> | null;
quality?: number;
width?: number;
height?: number;
}
export const PdfDownload: FC<PdfDownloadProps> = ({
filename,
eleRef,
quality = 1
}) => {
const classes = useStyles();
const print = useCallback(
() => {
const ele = eleRef ? eleRef.current : null;
if(ele) {
// add padding to the container
ele.style.padding = '2px';
html2canvas(ele, {scale: quality}).then(function(canvas) {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 295;
const imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
const jsPDF = (window as any).jsPDF;
const doc = new jsPDF('p', 'mm');
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save(`${filename}.pdf`);
});
// remove added padding
ele.style.padding = '0px';
} else {
throw new Error('No element ref found for building canvas');
}
},
[filename, eleRef, quality]
);
return (
<div className={classes.root}>
<Button
variant="contained"
onClick={print}
>
<CloudDownloadIcon /> &nbsp; PDF
</Button>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment