2017-01-03 10 views
1

Я провел последние несколько дней, играя с реакцией-native-html-to-pdf (https://github.com/christopherdro/react-native-html-to-pdf), реагировать-на-на-mail (by chirag04) и реагировать -view-pdf (by cnjon)пытается создать PDF-файл и просмотреть его или отправить по электронной почте с помощью React Native

Есть еще одна версия реакции-native-mail от parkerdan, которую я еще должен попробовать, но версия chrirag04 в корне исказила все мои проекты и была больно удалять.

response-native-html-to-pdf, похоже, не создает никаких ошибок, и я не могу получить доступ к создаваемому PDF-файлу. вот фрагмент кода, который я бегу:

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

...

createPDF() { 

    var options = { 

     html: '<h1>PDF TEST</h1>', // HTML String 

     // ****************** OPTIONS BELOW WILL NOT WORK ON ANDROID **************        
     fileName: 'test',   /* Optional: Custom Filename excluded extention 
           Default: Randomly generated 
           */ 


     directory: 'docs',   /* Optional: 'docs' will save the file in the `Documents` 
           Default: Temp directory 
           */ 

     height: 800,    /* Optional: 800 sets the height of the DOCUMENT that will be produced 
           Default: 612 
           */ 
     width: 1056,    /* Optional: 1056 sets the width of the DOCUMENT that will produced 
           Default: 792 
           */ 
     padding: 24,    /* Optional: 24 is the # of pixels between the outer paper edge and 
             corresponding content edge. Example: width of 1056 - 2*padding 
             => content width of 1008 
           Default: 10 
           */ 
    }; 
    RNHTMLtoPDF.convert(options).then((filePath) => { 
     AlertIOS.alert(
      'creat pdf', 
      'filePath=' + filePath 
     ); 


     return (
       <PDFView ref={(pdf)=>{this.pdfView = pdf;}} 
        src={filePath} 
        onLoadComplete = {(pageCount)=>{ 
         this.pdfView.setNativeProps({ 
          zoom: 1.5 
         }); 
        }} 
       /> 
     ) 
    }); 
}; 

, а затем в коде я называю его:

<TouchableHighlight onPress={this.createPDF} style={styles.button}> 
       <Text>create pdf </Text> 
</TouchableHighlight> 

Я получаю AlertIOS, с что-то похожее на допустимый путь к файлу (любой намек на проверку пути правильный, дайте мне знать) Но все-таки я, кажется, не нашел документ test.pdf в любом месте. Может ли кто-нибудь сказать, что я делаю неправильно?

Большое спасибо, Cheufte

+0

Вы связываете свой метод в конструкторе? Если нет, попробуйте изменить onPress на 'onPress = {this.createPDF.bind (this)}' и посмотреть, не является ли это вашей проблемой. –

+0

Спасибо, Мэтт. это не имеет никакого значения. Предупреждение показывает, что функция RNHTMLtoPDF.convert запускается, как ожидалось. Я просто набрал путь к файлу, указанный в командной строке, и нашел документ. Поэтому, наверное, мой вопрос заключается в том, как использовать этот документ? как я могу отобразить его с помощью pdfview? – cheufte

ответ

0

Я думаю, что путь к файлу каталог документов вы можете пройти через путь к файлу, щелкнув сначала вариант окна в Xcode после этого найти вариант устройства при нажатии Параметры устройства всю информацию о ваших появится устройство, затем выберите приложение и увидите его контейнер, и вы найдете файл pdf.

var localpath= RNFS.DocumentDirectoryPath + filePath 
    <PDFView ref={(pdf)=>{this.pdfView = pdf;}} 
         path={localpath} 
         onLoadComplete = {(pageCount)=>{ 
          this.pdfView.setNativeProps({ 
           zoom: 1.5 
          }); 
         }} 
        /> 

напишите путь вместо src, потому что он устарел.

+0

спасибо CodeSingh. Как объяснялось выше, набрав файл, указанный в командной строке, я нашел документ. Поэтому, наверное, мой вопрос заключается в том, как использовать этот документ? как я могу отобразить его с помощью pdfview? – cheufte

+0

Вы не можете просмотреть pdf-файл, используя реактивный родной pdfviewer – Codesingh

+0

все еще не очень повезло. – cheufte

0
import React, { Component } from 'react'; 
import { 
    AlertIOS, 
    AppRegistry, 
    StyleSheet, 
    Text, 
    TouchableHighlight, 
    View 
} from 'react-native'; 

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

export default class testApp extends Component { 

createPDF() { 
    var options2 = { 
    html: '<h1>PDF TEST</h1>', // HTML String 

    // ****************** OPTIONS BELOW WILL NOT WORK ON ANDROID **************        
    fileName: 'test2',   /* Optional: Custom Filename excluded extension 
           Default: Randomly generated 
           */ 

    directory: 'docs',   /* Optional: 'docs' will save the file in the `Documents` 
           Default: Temp directory */ 

    base64: true ,    


    height: 800,     
    width: 1056,    /* Optional: 1056 sets the width of the DOCUMENT that will produced 
           Default: 792 
           */ 
    padding: 24,    /* Optional: 24 is the # of pixels between the outer paper edge and 
             corresponding content edge. Example: width of 1056 - 2*padding 
             => content width of 1008 
           Default: 10 
           */ 
     }; 

     RNHTMLtoPDF.convert(options2).then((data2) => { 
     console.log(data2.filePath); 
     console.log(data2.base64); 
     AlertIOS.alert(
      'options2 filename' + options2.fileName, 
      'data2 filePath=' + data2.filePath 
     ); 
    }); 
} 


render() { 
    return (
    <View style={styles.container}> 
    <Text style={styles.welcome}> 
     Welcome to testApp 
    </Text> 

    <TouchableHighlight onPress={this.createPDF}> 
    <Text>Create PDF</Text> 
    </TouchableHighlight> 

    <Text style={styles.instructions}> 
     Press Cmd+R to reload,{'\n'} 
     Cmd+D or shake for dev menu 
    </Text> 
    </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
alignItems: 'center', 
backgroundColor: '#F5FCFF', 
}, 
welcome: { 
fontSize: 20, 
textAlign: 'center', 
margin: 10, 
}, 
instructions: { 
textAlign: 'center', 
color: '#333333', 
marginBottom: 5, 
}, 
}); 


AppRegistry.registerComponent('testApp',() => testApp); 

 Смежные вопросы

  • Нет связанных вопросов^_^