import{ useState }from'react';import{View,StyleSheet,Button,Platform,Text}from'react-native';import*asPrintfrom'expo-print';import{ shareAsync }from'expo-sharing';const html =`
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
</head>
<body style="text-align: center;">
<h1 style="font-size: 50px; font-family: Helvetica Neue; font-weight: normal;">
Hello Expo!
</h1>
<img
src="https://expo.nodejs.cn/static/images/expo-logo.svg"
style="width: 90vw;" />
</body>
</html>
`;exportdefaultfunctionApp(){const[selectedPrinter, setSelectedPrinter]=useState();constprint=async()=>{// On iOS/android prints the given html. On web prints the HTML from the current page.awaitPrint.printAsync({
html,printerUrl: selectedPrinter?.url,// iOS only});};constprintToFile=async()=>{// On iOS/android prints the given html. On web prints the HTML from the current page.const{ uri }=awaitPrint.printToFileAsync({ html });console.log('File has been saved to:', uri);awaitshareAsync(uri,{UTI:'.pdf',mimeType:'application/pdf'});};constselectPrinter=async()=>{const printer =awaitPrint.selectPrinterAsync();// iOS onlysetSelectedPrinter(printer);};return(<Viewstyle={styles.container}><Buttontitle="打印"onPress={print}/><Viewstyle={styles.spacer}/><Buttontitle="打印为 PDF 文件"onPress={printToFile}/>{Platform.OS==='ios'&&(<><Viewstyle={styles.spacer}/><Buttontitle="选择打印机"onPress={selectPrinter}/><Viewstyle={styles.spacer}/>{selectedPrinter ?(<Textstyle={styles.printer}>{`Selected printer: ${selectedPrinter.name}`}</Text>):undefined}</>)}</View>);}const styles =StyleSheet.create({container:{flex:1,justifyContent:'center',backgroundColor:'#ecf0f1',flexDirection:'column',padding:8,},spacer:{height:8,},printer:{textAlign:'center',},});
应用接口
🌐 API
import*asPrintfrom'expo-print';
No API data file found, sorry!
本地图片
🌐 Local images
在 iOS 上,从 HTML 源打印不支持本地资源 URL(由于 WKWebView 限制)。相反,图片需要转换为 base64 并内嵌到 HTML 中。
🌐 On iOS, printing from HTML source doesn't support local asset URLs (due to WKWebView limitations). Instead, images need to be converted to base64 and inlined into the HTML.
const{ uri }=awaitPrint.printToFileAsync({html:'This page is printed with margins',margins:{left:20,top:50,right:20,bottom:100,},});
如果将 useMarkupFormatter 设置为 true,设置页边距可能会导致打印输出的末尾出现空白页。为避免这种情况,请确保你的 HTML 字符串是一个格式良好的文档,包括在字符串开头添加 <!DOCTYPE html>。
🌐 If useMarkupFormatter is set to true, setting margins may cause a blank page to appear at the end of your printout. To prevent this, make sure your HTML string is a well-formed document, including <!DOCTYPE html> at the beginning of the string.
在 Android 上,如果你在 printAsync 或 printToFileAsync 中使用 html 选项,生成的打印可能会包含页面边距(这取决于 WebView 引擎)。
它们是由 @page 样式块设置的,你可以在 HTML 代码中覆盖它们: