use-react-print
v1.0.0
Published
A simple and powerful React hook for printing HTML elements and URLs with advanced features
Maintainers
Readme
Use React Print
A simple and powerful React hook for printing HTML elements and URLs with advanced features including support for images, PDFs, and custom styling.
Features
- 🖨️ Print React components/elements via refs
- 🌐 Print images and PDFs from URLs
- 🎨 Custom print styles
- 📱 Support for cloud storage URLs (Google Drive, Dropbox, OneDrive, AWS S3, etc.)
- ⚡ TypeScript support
- 🔄 Retry mechanism for failed loads
- 🎯 Lightweight and dependency-free (except React)
Installation
npm install use-react-printor
yarn add use-react-printUsage
Basic Usage
import { useRef } from 'react';
import { usePrint } from 'use-react-print';
function MyComponent() {
const printRef = useRef<HTMLDivElement>(null);
const { handlePrint, isPrinting } = usePrint(printRef);
return (
<div>
<div ref={printRef}>
<h1>Content to Print</h1>
<p>This content will be printed.</p>
</div>
<button onClick={handlePrint} disabled={isPrinting}>
{isPrinting ? 'Printing...' : 'Print'}
</button>
</div>
);
}Print from URL
import { usePrint } from 'use-react-print';
function PrintFromUrl() {
const { handlePrint, isPrinting } = usePrint('https://example.com/image.jpg');
return (
<button onClick={handlePrint} disabled={isPrinting}>
{isPrinting ? 'Printing...' : 'Print Image'}
</button>
);
}Advanced Usage with Options
import { useRef } from 'react';
import { usePrint } from 'use-react-print';
function AdvancedPrint() {
const printRef = useRef<HTMLDivElement>(null);
const { handlePrint, isPrinting } = usePrint(printRef, {
documentTitle: 'My Custom Document',
printStyles: `
@media print {
body { font-family: Arial, sans-serif; }
.no-print { display: none !important; }
}
`,
onBeforePrint: async () => {
console.log('About to print...');
// Perform any async operations before printing
},
onAfterPrint: () => {
console.log('Print completed!');
},
copyStyles: true,
bodyClass: 'print-mode',
loadTimeout: 10000,
retryAttempts: 3
});
return (
<div>
<div ref={printRef}>
<h1>Print Content</h1>
<p>This will be printed with custom styles.</p>
<div className="no-print">This won't be printed</div>
</div>
<button onClick={handlePrint} disabled={isPrinting}>
Print with Custom Options
</button>
</div>
);
}Using with Print Provider
import { PrintProvider, usePrint } from 'use-react-print';
function App() {
return (
<PrintProvider
defaultOptions={{
documentTitle: 'My App Print',
copyStyles: true,
printStyles: `
@media print {
body { margin: 0; }
}
`
}}
>
<MyPrintComponent />
</PrintProvider>
);
}
function MyPrintComponent() {
const printRef = useRef<HTMLDivElement>(null);
const { handlePrint, isPrinting } = usePrint(printRef);
// Default options from provider will be applied
return (
// Your component JSX
);
}API Reference
usePrint(source, options?)
Parameters
source:RefObject<HTMLElement> | string- Either a React ref to an HTML element or a URL stringoptions:PrintOptions(optional) - Configuration options
Returns
handlePrint:() => Promise<void>- Function to trigger printingisPrinting:boolean- Whether printing is currently in progress
PrintOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| printStyles | string | undefined | Custom CSS styles to apply only during printing |
| documentTitle | string | undefined | Document title for the print window |
| onBeforePrint | () => void \| Promise<void> | undefined | Callback fired before printing starts |
| onAfterPrint | () => void | undefined | Callback fired after printing completes |
| removeAfterPrint | boolean | true | Remove the iframe after printing |
| copyStyles | boolean | true | Copy all styles from parent document |
| bodyClass | string | undefined | Additional class names to add to the print container |
| loadTimeout | number | 5000 | Timeout for loading external URLs in milliseconds |
| retryAttempts | number | 2 | Number of retry attempts for failed URL loads |
PrintProvider
A context provider component for setting default print options across your application.
Props
children:ReactNode- Child componentsdefaultOptions:PrintOptions(optional) - Default options to apply to all print operations
usePrintContext()
Hook to access the default options from the nearest PrintProvider.
Returns
PrintOptions- The default options from the provider
Supported URL Types
The library automatically detects and handles various URL types:
- Images:
.jpg,.jpeg,.png,.gif,.bmp,.webp,.svg,.ico,.tiff,.tif - PDFs:
.pdf - Cloud Storage: Google Drive, Dropbox, OneDrive, AWS S3, Cloudinary, imgix
Browser Support
- Chrome/Chromium-based browsers
- Firefox
- Safari
- Edge
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT © Vishal Meena
Author
Vishal Meena
- GitHub: @vishalmeena2211
Made with ❤️ for the React community
