react-native-print:如何修改纸张尺寸与打印方向默认选项?
Absolutely! You can definitely tweak the print orientation and paper size using react-native-print—let me walk you through the proper way to do this, including platform-specific details and troubleshooting tips.
Basic Usage: Passing Orientation and Paper Size Options
The core print() method from the library accepts direct options to override default settings. Here’s a straightforward example to set landscape mode and a specific paper size:
import RNPrint from 'react-native-print'; const printLandscapeDocument = async () => { try { await RNPrint.print({ html: '<div style="text-align:center;"><h1>My Landscape-First Document</h1></div>', orientation: 'landscape', // Valid values: 'portrait' (default) or 'landscape' paperSize: 'A4', // Common options: 'Letter', 'Legal', 'A3', 'A5', 'Tabloid', etc. }); console.log('Print job initiated successfully'); } catch (error) { console.error('Print failed:', error); } };
Platform-Specific Customizations
Android: Custom Paper Sizes
If you need a non-standard paper size (not just pre-defined options like A4), use the customPaperWidth and customPaperHeight parameters (values are in millimeters):
await RNPrint.print({ html: '<h1>Custom Size Landscape Document</h1>', orientation: 'landscape', customPaperWidth: 297, // Landscape width of A4 in mm customPaperHeight: 210, // Landscape height of A4 in mm });
iOS: Fallback CSS Enforcement
For iOS, standard paper sizes work as expected, but you can add CSS to your HTML content to reinforce the orientation as a backup:
<style> @page { size: landscape; } </style>
Troubleshooting Common Issues
- Options not applying? Double-check spelling—
orientationandpaperSizemust be lowercase (e.g.,'landscape'not'Landscape'). - Printer ignoring settings? Some older printers restrict orientation/paper size changes. Test with a different printer to rule out hardware limitations.
- Outdated package? Ensure you’re on the latest version of react-native-print. Run
npm update react-native-printoryarn upgrade react-native-printto fix potential bugs. - Linking problems? For React Native versions below 0.60, confirm the package is linked correctly. For newer versions, re-run
npx pod-installfor iOS if auto-linking seems to have failed.
Final Notes
In most cases, passing the correct orientation and paperSize options directly to the print() method will fix your issue. If you still see default settings, combining the JS options with the CSS @page rule ensures the orientation is enforced at both the library and content levels.
内容的提问来源于stack exchange,提问作者KOTIOS

