首页指南参考教程

Expo 打印 iconExpo 打印

GitHub

npm

为 Android 和 iOS (AirPrint) 提供打印功能的库。

Android
iOS
Web

expo-print 为 Android 和 iOS (AirPrint) 打印功能提供 API。

¥expo-print provides an API for Android and iOS (AirPrint) printing functionality.

安装

¥Installation

Terminal
npx expo install expo-print

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

用法

¥Usage

Print usage
import * as React from 'react';
import { View, StyleSheet, Button, Platform, Text } from 'react-native';
import * as Print from '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://d30j33t1r58ioz.cloudfront.net/static/guides/sdk.png"
      style="width: 90vw;" />
  </body>
</html>
`;

export default function App() {
  const [selectedPrinter, setSelectedPrinter] = React.useState();

  const print = async () => {
    // On iOS/android prints the given html. On web prints the HTML from the current page.
    await Print.printAsync({
      html,
      printerUrl: selectedPrinter?.url, // iOS only
    });
  };

  const printToFile = async () => {
    // On iOS/android prints the given html. On web prints the HTML from the current page.
    const { uri } = await Print.printToFileAsync({ html });
    console.log('File has been saved to:', uri);
    await shareAsync(uri, { UTI: '.pdf', mimeType: 'application/pdf' });
  };

  const selectPrinter = async () => {
    const printer = await Print.selectPrinterAsync(); // iOS only
    setSelectedPrinter(printer);
  };

  return (
    <View style={styles.container}>
      <Button title="Print" onPress={print} />
      <View style={styles.spacer} />
      <Button title="Print to PDF file" onPress={printToFile} />
      {Platform.OS === 'ios' && (
        <>
          <View style={styles.spacer} />
          <Button title="Select printer" onPress={selectPrinter} />
          <View style={styles.spacer} />
          {selectedPrinter ? (
            <Text style={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 * as Print from 'expo-print';

Constants

Print.Orientation

Type: OrientationType


The orientation of the printed content.

Methods

Print.printAsync(options)

NameTypeDescription
optionsPrintOptions

A map defining what should be printed.


Prints a document or HTML, on web this prints the HTML from the page.

Note: On iOS, printing from HTML source doesn't support local asset URLs (due to WKWebView limitations). As a workaround you can use inlined base64-encoded strings. See this comment for more details.

Note: on iOS, when printing without providing a PrintOptions.printerUrl the Promise will be resolved once printing is started in the native print window and rejected if the window is closed without starting the print. On Android the Promise will be resolved immediately after displaying the native print window and won't be rejected if the window is closed without starting the print.

Returns

  • Promise<void>

Resolves to an empty Promise if printing started.

Print.printToFileAsync(options)

NameTypeDescription
options
(optional)
FilePrintOptions

A map of print options.

Default: {}

Prints HTML to PDF file and saves it to app's cache directory. On Web this method opens the print dialog.

Returns

  • Promise<FilePrintResult>

Only for:
iOS

Print.selectPrinterAsync()

Chooses a printer that can be later used in printAsync

Returns

  • Promise<Printer>

A promise which fulfils with an object containing name and url of the selected printer.

Interfaces

OrientationType

The possible values of orientation for the printed content.

OrientationType Properties

NameTypeDescription
landscapestring-
portraitstring-

Types

FilePrintOptions

NameTypeDescription
base64
(optional)
boolean

Whether to include base64 encoded string of the file in the returned object.

height
(optional)
number

Height of the single page in pixels. Defaults to 792 which is a height of US Letter paper format with 72 PPI.

html
(optional)
string

HTML string to print into PDF file.

margins
(optional)
PageMarginsOnly for:
iOS

Page margins for the printed document.

useMarkupFormatter
(optional)
booleanOnly for:
iOS

Alternative to default option that uses UIMarkupTextPrintFormatter instead of WebView, but it doesn't display images.

width
(optional)
number

Width of the single page in pixels. Defaults to 612 which is a width of US Letter paper format with 72 PPI.

FilePrintResult

NameTypeDescription
base64
(optional)
string

Base64 encoded string containing the data of the PDF file. Available only if base64 option is truthy. It doesn't include data URI prefix data:application/pdf;base64,.

numberOfPagesnumber

Number of pages that were needed to render given content.

uristring

A URI to the printed PDF file.

PrintOptions

NameTypeDescription
height
(optional)
number

Height of the single page in pixels. Defaults to 792 which is a height of US Letter paper format with 72 PPI. Available only with html option.

html
(optional)
stringOnly for:
Android
iOS

HTML string to print.

margins
(optional)
PageMarginsOnly for:
iOS

Page margins for the printed document.

markupFormatterIOS
(optional)
string

Deprecated. This argument is deprecated, use useMarkupFormatter instead. Might be removed in the future releases.

Only for:
iOS

orientation
(optional)
OrientationType['portrait'] | OrientationType['landscape']Only for:
iOS

The orientation of the printed content, Print.Orientation.portrait or Print.Orientation.landscape.

printerUrl
(optional)
stringOnly for:
iOS

URL of the printer to use. Returned from selectPrinterAsync.

uri
(optional)
string

URI of a PDF file to print. Remote, local (ex. selected via DocumentPicker) or base64 data URI starting with data:application/pdf;base64,. This only supports PDF, not other types of document (e.g. images).

useMarkupFormatter
(optional)
booleanOnly for:
iOS

Alternative to default option that uses UIMarkupTextPrintFormatter instead of WebView, but it doesn't display images.

width
(optional)
number

Width of the single page in pixels. Defaults to 612 which is a width of US Letter paper format with 72 PPI. Available only with html option.

Printer

NameTypeDescription
namestring

Name of the printer.

urlstring

URL of the printer.

本地图片

¥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.

import { Asset } from 'expo-asset';
import { printAsync } from 'expo-print';
import { manipulateAsync } from 'expo-image-manipulator';

async function generateHTML() {
  const asset = Asset.fromModule(require('../../assets/logo.png'));
  const image = await manipulateAsync(asset.localUri ?? asset.uri, [], { base64: true });
  return `
    <html>
      <img
        src="data:image/jpeg;base64,${image.base64}"
        style="width: 90vw;" />
    </html>
  `;
}

async function print() {
  const html = await generateHTML();
  await printAsync({ html });
}

页边距

¥Page margins

在 iOS 上,你可以使用 margins 选项设置页边距:

¥On iOS you can set the page margins using the margins option:

const { uri } = await Print.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 上,如果你在 printAsyncprintToFileAsync 中使用 html 选项,则生成的打印结果可能包含页边距(这取决于 WebView 引擎)。它们由 @page 样式块设置,你可以在 HTML 代码中覆盖它们:

¥On Android, if you're using html option in printAsync or printToFileAsync, the resulting print might contain page margins (it depends on the WebView engine). They are set by @page style block and you can override them in your HTML code:

<style>
  @page {
    margin: 20px;
  }
</style>

详细信息请参见 MDN 上的 @page 文档

¥See @page documentation on MDN for more details.

Expo 中文网 - 粤ICP备13048890号