react 创建PDF教程 并将PDF 在浏览器打开 进行打印之类操作

#REACT 生成  PDF

>1.准备工作
>安装 @react-pdf/renderer

##URL封装函数
 
>主要功能是根据blob对象创建URL用来在浏览器打开


```
function getObjectURL(file){ //获取文件的地址 兼容写法
    var url=null
    if(window.createObjectURL!=undefined){ // basic
        url=window.createObjectURL(file)
    }else if(window.URL!=undefined){ // mozilla(firefox)
        url=window.URL.createObjectURL(file)
    } else if(window.webkitURL!=undefined){ // webkit or chrome
        url=window.webkitURL.createObjectURL(file)
    }
    return url  ;
}

```

##功能代码 步骤重现

### 一、创建一个pdf文件 import MyDocument from './reactpd'

```
import React, { Fragment, Component  } from 'react'
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';

// Create styles
const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

const Mys =()=>{
    return(
        <Document>
            <Page size="A4" style={styles.page}>
            <View style={styles.section}>
                <Text>Section #1</Text>
            </View>
            <View style={styles.section}>
                <Text>Section #2</Text>
            </View>
            </Page>
        </Document>
    )
}


export default Mys;

```
###二. 创建并导入刚才创建的组件 import MyDocument from './reactpd'

```
import React from 'react';
import {pdf,Document,Page} from '@react-pdf/renderer';
import MyDocument from './reactpd'
function getObjectURL(file){ //获取文件的地址 兼容写法
    var url=null
    if(window.createObjectURL!=undefined){ // basic
        url=window.createObjectURL(file)
    }else if(window.URL!=undefined){ // mozilla(firefox)
        url=window.URL.createObjectURL(file)
    } else if(window.webkitURL!=undefined){ // webkit or chrome
        url=window.webkitURL.createObjectURL(file)
    }
    return url  ;
}



class Test extends React.Component{
    constructor(props){
        super(props)
        this.state={
            obj:{},
        }
    }
    componentWillMount(){
        let that = this;
        const blob = pdf(<MyDocument />).toBlob().then( res =>{
            that.setState({
                obj:res
            })
        });
    }

    save=()=>{
        const { obj } = this.state;
        let ul = getObjectURL(obj)
        window.open(ul)
    }


    render(){
    
        return(
            <div onClick={ this.save }>
               点击在浏览器打开
            </div>
        )
    }
}
export default Test;

```

 

posted @ 2019-09-26 18:15  沐少白  阅读(1402)  评论(0)    收藏  举报