最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How create PDF in React native Expo using react-native-html-to-pdf? - Stack Overflow

programmeradmin1浏览0评论

I'm trying to run a 'Hello World' code using the react-native-html-to-pdf library and create PDF, but I can't set it up at Expo. Could you help me? I tried using the and react-native link.

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "^35.0.0",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": ".0.0.tar.gz",
    "react-native-html-to-pdf": "^0.8.0",
    "react-native-pdf-lib": "^0.2.1",
    "react-native-web": "^0.11.7"
  },
  "devDependencies": {
    "babel-preset-expo": "^7.1.0"
  },
  "private": true
}

App.js

import React, { Component } from 'react';

import {
  Text,
  TouchableHighlight,
  View,
  StyleSheet,
} from 'react-native';

import RNHTMLtoPDF from 'react-native-html-to-pdf';

export default class App extends Component {
  async createPDF() {
    let options = {
      html: '<h1>PDF TEST</h1>',
      fileName: 'test',
      directory: 'Documents',
    };

    let file = await RNHTMLtoPDF.convert(options)
    // console.log(file.filePath);
    alert(file.filePath);
  }

  render() {
    return(
      <View style={styles.container}>
        <TouchableHighlight onPress={this.createPDF}>
          <Text>Create PDF</Text>
        </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },

});```

I'm trying to run a 'Hello World' code using the react-native-html-to-pdf library and create PDF, but I can't set it up at Expo. Could you help me? I tried using the and react-native link.

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "^35.0.0",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": "https://github./expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-html-to-pdf": "^0.8.0",
    "react-native-pdf-lib": "^0.2.1",
    "react-native-web": "^0.11.7"
  },
  "devDependencies": {
    "babel-preset-expo": "^7.1.0"
  },
  "private": true
}

App.js

import React, { Component } from 'react';

import {
  Text,
  TouchableHighlight,
  View,
  StyleSheet,
} from 'react-native';

import RNHTMLtoPDF from 'react-native-html-to-pdf';

export default class App extends Component {
  async createPDF() {
    let options = {
      html: '<h1>PDF TEST</h1>',
      fileName: 'test',
      directory: 'Documents',
    };

    let file = await RNHTMLtoPDF.convert(options)
    // console.log(file.filePath);
    alert(file.filePath);
  }

  render() {
    return(
      <View style={styles.container}>
        <TouchableHighlight onPress={this.createPDF}>
          <Text>Create PDF</Text>
        </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },

});```
Share Improve this question edited Dec 6, 2019 at 14:39 user10216583 asked Dec 6, 2019 at 13:52 Giancarlo HortaGiancarlo Horta 111 gold badge1 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You cannot link any libraries if you are using expo. That's the limitation of expo. If you want to have such functionality, its better you switch to bare react native application by either ejecting from expo , because linking doesnt work in expo. That's a major limitation of expo.

Or you can check the docs of Expo Print ,

expo link

Where they have defined a print function to save html to pdf

Print.printToFileAsync(options)
Prints HTML to PDF file and saves it to app's cache directory.
Arguments
options (object) -- A map of options:
html (string) -- HTML string to print into PDF file.
width (number) -- Width of the single page in pixels. Defaults to 612 which is a width of US Letter paper format with 72 PPI.
height (number) -- Height of the single page in pixels. Defaults to 792 which is a height of US Letter paper format with 72 PPI.
base64 (boolean) -- Whether to include base64 encoded string of the file in the returned object.
Returns
Resolves to an object with following keys:
uri (string) -- A URI to the printed PDF file.
numberOfPages (number) -- Number of pages that were needed to render given content.
base64 (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,.

Hope it helps. feel free for doubts

You need to import these two libraries from Expo:

import * as Print from 'expo-print';
import { shareAsync } from 'expo-sharing';

Then you can use a function like this to export pdf:

const printToFile = async () => {
    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/static/guides/sdk.png"
      style="width: 90vw;" />
  </body>
</html>
`;
    // 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' });
  };
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>