React Native WebView加载Base64 PDF无法翻页求助
解决React Native WebView加载Base64 PDF仅显示第一页的问题
方案1:调整embed标签样式与WebView布局配置
问题核心在于WebView内部的PDF容器未自适应内容高度,导致仅展示第一页。修改HTML内容并调整WebView属性,确保容器能完整容纳PDF:
<View style={{ flex: 1, paddingVertical: 40 }}> <WebView style={{ flex: 1 }} source={{ html: ` <!DOCTYPE html> <html> <body style="margin:0; padding:0;"> <embed width="100%" height="100%" src="data:application/pdf;base64, ${dataInBase64}" type="application/pdf" /> </body> </html> ` }} scrollEnabled={false} // 禁用WebView自身滚动,交由PDF内部滚动 scalesPageToFit={true} /> </View>
关键调整点:
- 给WebView和父View设置
flex:1,确保组件占满可用空间 - 禁用WebView的
scrollEnabled,避免与PDF内部滚动逻辑冲突 - 给embed添加
height="100%"和type属性,强制容器高度匹配WebView空间 - 重置html/body的margin和padding,消除不必要的留白
方案2:用iframe替代embed提升兼容性
部分移动端WebView环境下,iframe对PDF的渲染兼容性优于embed,替换后可解决滚动问题:
<View style={{ flex: 1, paddingVertical: 40 }}> <WebView style={{ flex: 1 }} source={{ html: ` <!DOCTYPE html> <html> <body style="margin:0; padding:0;"> <iframe width="100%" height="100%" src="data:application/pdf;base64, ${dataInBase64}" frameBorder="0" ></iframe> </body> </html> ` }} scrollEnabled={false} scalesPageToFit={true} /> </View>
方案3:动态计算PDF内容高度
如果前两种方案仍无效,可通过JS动态获取PDF实际高度并设置容器尺寸:
<View style={{ flex: 1, paddingVertical: 40 }}> <WebView style={{ flex: 1 }} source={{ html: ` <!DOCTYPE html> <html> <body style="margin:0; padding:0;"> <embed id="pdfEmbed" width="100%" src="data:application/pdf;base64, ${dataInBase64}" type="application/pdf" /> <script> const embed = document.getElementById('pdfEmbed'); // 等待PDF加载完成后调整高度 embed.onload = function() { setTimeout(() => { embed.style.height = embed.contentWindow.document.body.scrollHeight + 'px'; }, 500); }; </script> </body> </html> ` }} scalesPageToFit={true} /> </View>
内容的提问来源于stack exchange,提问作者Sergio
相关产品推荐
相关产品推荐

