I am using the jsPDF package to create a PDF in my React app. I want to then display that PDF in the browser in a react modal. I got the PDF viewer to come up in the modal, but the actual PDF is empty. I cannot figure out why. I’ve copied the examples I have found.
Here is my entire modal component:
import React, {Dispatch, useEffect, useState} from 'react';
import Modal from 'react-modal';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import {ModalStyles} from './ModalStyles';
import CloseButton from './CloseButton';
type PriceListPDFProps = {
openPriceListPDFModal: boolean;
setOpenPriceListPDFModal: Function;
priceListToExport: boolean
setPriceListToExport: Dispatch<React.SetStateAction<boolean>>;
}
const PriceListPdf = (props: PriceListPDFProps) => {
const {
openPriceListPDFModal,
setOpenPriceListPDFModal,
priceListToExport,
setPriceListToExport
} = props;
const [PDFSrc, setPDFSrc] = useState('');
useEffect(() => {
console.log({priceListToExport});
if (priceListToExport) {
displayPDF();
}
}, [priceListToExport])
const cleanup = () => {
setPriceListToExport(false);
};
const displayPDF = () => {
const doc = new jsPDF(
{
orientation: 'p',
unit: 'in',
format: 'letter',
putOnlyUsedFonts: true,
floatPrecision: 16 // or "smart", default is 16
});
// doc.addPage('letter');
doc.setFontSize(22);
doc.setFont('times', 'normal', 'normal');
doc.setTextColor(0, 0, 0);
doc.text("This is a title", 200, 300);
doc.setFontSize(16);
doc.setFont('times', 'normal', 'normal');
doc.setTextColor(0, 0, 0);
// doc.setTextColor('#000000');
doc.text("This is some normal sized text underneath.", 20, 30);
//doc.save('pricelist.pdf');
const objectURL = doc.output('datauristring');
console.log('objectURL');
console.log({objectURL});
console.log({fonts: doc.getFontList()});
doc.setDisplayMode('fullheight');
setPDFSrc(objectURL);
}
const customStyles = {
content: {
...ModalStyles.content
},
overlay: {...ModalStyles.overlay, position: 'fixed', inset: 0, zIndex: 1000}
};
return (
<Modal
isOpen={openPriceListPDFModal}
style={customStyles}
overlayClassName={'fading-modal fast'}
className={'quotes-modal'}
closeTimeoutMS={100}
onAfterClose={() => cleanup()}
>
<div className={'price-list-pdf'}>
<h4 className={'title'}>Price List PDF</h4>
<CloseButton setOpenModal={setOpenPriceListPDFModal}/>
<div className={'pdf-embed d-block text-center mx-auto'}>
{!!PDFSrc &&
<embed src={PDFSrc} width={540} height={700}/>
}
</div>
</div>
</Modal>
)
}
export default PriceListPdf
And here is what it looks like: