使用React PDF Renderer下载PDF时图片不显示的问题求助
React PDF Renderer下载PDF时图片消失的解决方案
核心原因
PDFViewer在浏览器环境中可直接加载图片资源,但PDFDownloadLink生成PDF时处于离线渲染环境,对资源路径解析、加载同步性要求更高,导致浏览器能正常访问的资源在PDF生成流程中无法被正确读取。
可行解决方案
1. 预加载图片为Base64格式
在组件中提前将public文件夹内的图片转换为Base64,确保PDF生成时能直接读取同步资源:
import { useState, useEffect } from 'react'; import { View, Image, Text } from '@react-pdf/renderer'; const OFPdf = ({ of }) => { const [logoBase64, setLogoBase64] = useState(null); useEffect(() => { const loadLogo = async () => { const res = await fetch('/images/Logo.jpeg'); const blob = await res.blob(); const reader = new FileReader(); reader.onload = () => setLogoBase64(reader.result); reader.readAsDataURL(blob); }; loadLogo(); }, []); if (!logoBase64) return null; return ( <View style={styles.header}> <Image src={logoBase64} style={styles.headerImage} /> <Text style={styles.headerTitle}>ORDRE DE FABRICATION</Text> </View> ); };
2. 使用项目PUBLIC_URL确保路径正确
React项目中通过process.env.PUBLIC_URL获取public文件夹的绝对路径,避免路径解析偏差:
// 替换图片src路径 <Image src={`${process.env.PUBLIC_URL}/images/Logo.jpeg`} style={styles.headerImage} />
3. 等待资源加载完成后再生成PDF
通过状态控制PDFDownloadLink的渲染时机,确保所有图片资源加载完成后再显示下载按钮:
import { useState, useEffect } from 'react'; import { PDFDownloadLink } from '@react-pdf/renderer'; const OFDownloadButton = ({ of }) => { const [isResourcesReady, setIsResourcesReady] = useState(false); useEffect(() => { const checkResources = async () => { const logoRes = await fetch('/images/Logo.jpeg'); if (logoRes.ok) setIsResourcesReady(true); }; checkResources(); }, []); if (!isResourcesReady) return <Button>准备中...</Button>; return ( <PDFDownloadLink document={<OFPdf of={of} />} fileName={`${of.fp.formule.ref}_${of?.lot}_${of.ref}`} style={{ textDecoration: 'none' }} > {({ loading, error }) => ( <Button> {loading ? 'Chargement du document...' : 'Générer l\'OF'} </Button> )} </PDFDownloadLink> ); };
4. 移除fixed属性尝试
部分场景下fixed属性会干扰PDF生成时的布局渲染,可尝试移除图片的fixed属性后测试:
<Image src="/images/Logo.jpeg" style={styles.headerImage} />
内容的提问来源于stack exchange,提问作者Yggor
相关产品推荐
相关产品推荐

