Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import { render, hydrate } from 'react-dom';
  3. import { PDFDownloadLink } from '@react-pdf/renderer';
  4. import { ModelCertificate } from './ModelCertificate';
  5.  
  6. export default class PDFLink extends Component {
  7. state = {
  8. loading: false,
  9. };
  10.  
  11. download = (filename, url) => {
  12. const element = document.createElement('a');
  13. element.setAttribute('href', `${url}`);
  14. element.setAttribute('download', filename);
  15.  
  16. element.style.display = 'none';
  17. document.body.appendChild(element);
  18.  
  19. element.click();
  20.  
  21. document.body.removeChild(element);
  22. };
  23.  
  24. createAndDownloadPDF = (pdfContent, filename, divId, callback) => {
  25. setTimeout(() => {
  26. const link = (
  27. <div id={divId}>
  28. <PDFDownloadLink document={pdfContent} fileName={filename}>
  29. {({ blob, url, loading, error }) => {
  30. if (!loading) {
  31. this.download(filename, URL.createObjectURL(blob));
  32. callback();
  33. }
  34. }}
  35. </PDFDownloadLink>
  36. </div>
  37. );
  38. const elem = document.createElement('div');
  39. document.getElementById('pdfButton').appendChild(elem);
  40. hydrate(link, elem);
  41. }, 50);
  42. };
  43.  
  44. buildPDF = () => {
  45. const { loading } = this.state;
  46. if (!loading) {
  47. this.setState({ loading: true }, () => {
  48. this.createAndDownloadPDF(this.generatePDF(), `file.pdf`, `file`, () =>
  49. this.setState({ loading: false })
  50. );
  51. });
  52. }
  53. };
  54.  
  55. generatePDF = () => {
  56. // CertificatePDF is a component that returns a PDF <Document />
  57. return <ModelCertificate {...this.props} />;
  58. };
  59.  
  60. render() {
  61. const { loading } = this.state;
  62. return loading ? (
  63. <div id="pdfButton">Loading...</div>
  64. ) : (
  65. <button onClick={this.buildPDF}>
  66. Click here to download a certificate
  67. </button>
  68. );
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement