React PDF Image组件图片无法显示 求问题排查方案
解决@react-pdf/renderer Image组件不显示图片的问题
核心问题分析
@react-pdf/renderer的Image组件和浏览器原生<img>的资源处理逻辑完全不同:浏览器能直接识别webpack打包后的模块路径,但@react-pdf需要资源能被它的PDF渲染引擎直接读取,同时必须明确设置图片尺寸。
分步解决方案
- 给Image组件设置明确的宽高样式
你当前的styles.image是空对象,@react-pdf的Image没有默认尺寸,会导致渲染后不可见。必须添加width和height:
const styles = StyleSheet.create({ // ...其他样式 image: { width: 200, height: 200 } // 按需调整数值 })
- 使用public目录下的绝对路径
把图片放到项目根目录的public/images文件夹下,然后用process.env.PUBLIC_URL拼接路径,确保PDF引擎能通过HTTP访问到资源:
const imgPath = `${process.env.PUBLIC_URL}/images/Drawer.png` // 在组件中使用 <Image style={styles.image} src={imgPath} />
- 正确转换为Base64格式
你之前的Base64写法错误(直接把路径拼进去了),需要先把图片转成纯Base64字符串:
- 用在线Base64转换工具把图片转成字符串,保存为
.txt文件 - 导入该文件后直接使用:
import imgBase64 from '../../images/Drawer.base64.txt' // 组件中 <Image style={styles.image} src={`data:image/png;base64,${imgBase64}`} />
- 排除其他干扰项
暂时移除Konva相关的导入和代码,确保是@react-pdf本身的问题,而不是其他库冲突。
修改后的完整示例代码
import { Document, Page, StyleSheet, Text, Image, View } from '@react-pdf/renderer' import React from 'react' // 方式1:使用public目录的绝对路径 const imgPublicPath = `${process.env.PUBLIC_URL}/images/Drawer.png` // 方式2:使用Base64(需提前转换) // import imgBase64 from '../../images/Drawer.base64.txt' function PdfFile(props) { const styles = StyleSheet.create({ body: { padding: 20 }, title: { fontSize: 24, marginBottom: 20 }, image: { width: 200, height: 200, marginBottom: 15 } }) return ( <div> <Document> <Page style={styles.body}> <Text style={styles.title}>Hello world</Text> <View> <Image style={styles.image} src={imgPublicPath} /> {/* <Image style={styles.image} src={`data:image/png;base64,${imgBase64}`} /> */} </View> </Page> </Document> {/* 对比验证用的原生img */} <img src={imgPublicPath} style={{ width: 200, height: 200 }} /> </div> ) } export default PdfFile
额外注意事项
- 不要使用相对路径(比如
../../images/Drawer.png)直接传给@react-pdf的Image,webpack打包后的路径对PDF引擎不可用 - 如果是在Node.js环境生成PDF,可直接用本地文件的绝对路径(比如
path.resolve(__dirname, '../../images/Drawer.png'))
内容的提问来源于stack exchange,提问作者Петя Герман
相关产品推荐
相关产品推荐

