使用 react-pdf 制作pdf or 简历生成的流程及遇见的中文乱码问题
安装插件
yarn add @react-pdf/renderer
1、创建基本文档
// 个人简历页面开发
import React,{memo,useState} from 'react'
import {PdfGeneratorWrapper} from "./style";
import {PDFViewer} from '@react-pdf/renderer'
import PdfView from '../../../../components/pdf-view/pdf-view'
const PdfGenerator = memo(function () {
const [profile, setProfile] = useState({
name: "嘿哈",
about: "are you ok",
email: "maqi1520@qq.com",
avatar:"https://p6-passport.byteacctimg.com/img/user-avatar/585e1491713363bc8f67d06c485e8260~300x300.image",
})
return (
<PdfGeneratorWrapper>
<div style={{ flexGrow: 1 ,height:'900px'}} className={'right-pdf'}>
<PDFViewer
showToolbar={false}
style={{
width: '80%',
height: '95%',
}}
>
<PdfView profile={profile} />
</PDFViewer>
</div>
</PdfGeneratorWrapper>
)
})
export default PdfGenerator
// 个人简历页面开发
import React,{memo} from 'react'
import {styles} from "./style";
import { Document, Page,Text ,Image,View} from '@react-pdf/renderer'
const PdfView = memo(function (props) {
const {profile} = props
console.log(profile)
return (
<Document>
<Page size='A4' style={styles.page}>
<View style={styles.section}>
<Image src={profile.avatar} />
<View style={styles.section}>
<Text style={styles} >{profile.name}</Text>
</View>
<Text style={styles}>{profile.about}</Text>
<Text style={styles}>{profile.email}</Text>
</View>
</Page>
</Document>
)
})
export default PdfView
// 样式表
import {Font, StyleSheet} from "@react-pdf/renderer";
const aa = require('./mini.ttf')
Font.register({
family: 'ariblk',
src:aa
})
export const styles = StyleSheet.create({
// 一个页面
page:{
fontFamily:'ariblk',
flexDirection: 'column',
backgroundColor: '#E4E4E4'
},
// 页面中的一个区域
section:{
flexDirection: 'column',
backgroundColor: '#E4E4E4',
justifyContent: 'center'
}
});
这样最基本的一个展示就出来了,可以看官方文档 https://www.npmjs.com/package/@react-pdf/renderer
但是这时候其实会有一个中文乱码的问题
issue 中大家的解决办法 : https://github.com/diegomura/react-pdf/issues/267
解决办法就是通过 设置字体 来解决中文乱码的问题
import {Font, StyleSheet} from "@react-pdf/renderer";
const aa = require('./mini.ttf')
// 注册本地下载的字体文件并使用它就可以解决中文乱码的问题
Font.register({
family: 'ariblk',
src:aa
})
export const styles = StyleSheet.create({
// 一个页面
page:{
// 使用自己本地下载的字体文件
fontFamily:'ariblk',
flexDirection: 'column',
backgroundColor: '#E4E4E4'
},
// 页面中的一个区域
section:{
flexDirection: 'column',
backgroundColor: '#E4E4E4',
justifyContent: 'center'
}
});
使用
import {styles} from "./style";
const PdfView = memo(function (props) {
const {profile} = props
console.log(profile)
return (
<Document>
<Page size='A4' style={styles.page}>
<View style={styles.section}>
<Image src={profile.avatar} />
<View style={styles.section}>
<Text style={styles} >{profile.name}</Text>
</View>
<Text style={styles}>{profile.about}</Text>
<Text style={styles}>{profile.email}</Text>
</View>
</Page>
</Document>
)
})
最终中文乱码解决,这时候就可以开心的按照编写 html 格式的方式来编写自己的代码啦