企业官网建站 小程序开发 云逸学习园地
技术文章 许愿墙
技术文章 PHP学习 Javascript学习 DIV+CSS学习 uniapp学习 HTML学习 微信小程序、公众号知识点 VUE知识学习
您所在的位置>云逸小栈>uniapp学习>正文

uniapp打开pdf、word文档方法

2025-07-02 13:16:38 浏览 362

1、webview

<template>
 <view>
   <web-view :src="webViewSrc"></web-view>
 </view>
</template>

<script>
export default {
 data() {
   return {
     // 使用Google Docs Viewer预览Word或PDF文件
     webViewSrc: 'https://docs.google.com/gview?url=https://example.com/path/to/your/file.pdf&embedded=true'
     // 修改为你的文件URL和适当的格式(PDF或Word)
   };
 }
}
</script>

2、用openDocument打开

export default {
  data() {
    return {
      pdfUrl: 'https://xxxxx.com/file.pdf' // PDF文件的URL
    };
  },
  methods: {
    previewPDF() {
      const { pdfUrl } = this;
      if (!pdfUrl) {
        uni.showToast({
          title: 'PDF文件链接不存在',
          icon: 'none'
        });
        return;
      }

      uni.downloadFile({
        url: pdfUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.openDocument({
              filePath: res.tempFilePath,
              fileType: 'pdf',
              success: () => {
                console.log('PDF预览成功');
              },
              fail: (err) => {
                console.error('PDF预览失败', err);
                uni.showToast({
                  title: 'PDF预览失败',
                  icon: 'none'
                });
              }
            });
          } else {
            uni.showToast({
              title: '文件下载失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('文件下载失败', err);
          uni.showToast({
            title: '文件下载失败',
            icon: 'none'
          });
        }
      });
    }
  }
};

3、第三方插件

npm install u-pdf-viewer

<template>
 <view>
   <u-pdf-viewer :src="pdfUrl"></u-pdf-viewer>
 </view>
</template>

<script>
import UPdfViewer from 'u-pdf-viewer';

export default {
 components: {
   UPdfViewer
 },
 data() {
   return {
     pdfUrl: 'https://example.com/path/to/your/pdf/file.pdf' // PDF文件的URL
   };
 }
}
</script>


网站开发者电话

18066742510

个人微信号
个人公众号
个人小程序
个人抖音