UNPKG

@e-group/hooks

Version:

eGroup team react-hooks that share across projects.

59 lines (55 loc) 1.94 kB
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator"; import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; import _regeneratorRuntime from "@babel/runtime/regenerator"; import { useCallback, useRef, useState } from 'react'; import { jsPDF as JsPDF } from 'jspdf'; import pdfAddPages from '@e-group/utils/pdfAddPages'; export default function useMediaPrint(printBoxId) { const _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), loading = _useState2[0], setLoading = _useState2[1]; const itemRefs = useRef([]); const handleSavePdf = useCallback( /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(filename) { var pdf; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: pdf = new JsPDF('p', 'mm', 'a4'); setLoading(true); _context.next = 4; return pdfAddPages(printBoxId, pdf, itemRefs.current, { xPadding: 8, yPadding: 8 }); case 4: setLoading(false); pdf.save(filename); case 6: case "end": return _context.stop(); } }, _callee); })); return function (_x) { return _ref.apply(this, arguments); }; }(), [printBoxId]); const handleMediaPrint = useCallback(() => { const css = '@page { size: A4 portrait; }'; const head = document.head || document.getElementsByTagName('head')[0]; const style = document.createElement('style'); style.media = 'print'; style.appendChild(document.createTextNode(css)); head.appendChild(style); window.print(); head.removeChild(style); }, []); return { handleSavePdf, handleMediaPrint, itemRefs, loading }; }