Vue移动端预览(浙江-浙里办可用)

我的效果就是会将文件名在移动端展示。点击文件名就会在下方展示附件pdf预览.该方式支持word,pdf,和excel.至于换成点击跳转预览还是下方预览,自行把握。本人测试浙里办可用。

vue代码块

<span class="fontElder18" v-for="(item, i) in fileList" :key="i" style="color: #309FFF"><span @click="showClick(item.id)">{{ item.name }}</span>
        <pdf-page-view :id="item.id" v-show="pdfShow"></pdf-page-view>
      </span>

这是整体代码块(部分代码删除,只要看附件有关的就行):

<template>
  <div class="content content1">
    <p>
      <span>附件:</span>
      <span class="fontElder18" v-for="(item, i) in fileList" :key="i" style="color: #309FFF"><span @click="showClick(item.id)">{{ item.name }}</span>
        <pdf-page-view :id="item.id" v-show="pdfShow"></pdf-page-view>
      </span>
    </p>
  </div>
</template>
<script>

import PdfPageView from '@/views/nextPage/PDFPageView.vue'
export default {
    name: 'zczxinfo',
    data() {
        return {
          list: {},
          fileList: [],
          pdfShow: false
        }
    },
    components: {
      PdfPageView
    },
    computed: {},
    methods: {
      getList(id) {
        let _this = this
        if (id) {
          selectByZczxInfo({ id: id }).then((res) => {
            _this.list = res.data[0]
            let filesId = _this.list.filesId
            console.log(res)
            if (filesId) {
              getFiles({filesId: filesId}).then((red) => {
                console.log(red);
                _this.fileList = red.data
                if (_this.fileList.length  == 0){
                  _this.fileList= [{name: '无'}]
                }
              });
            }else{
              _this.fileList= [{name: '无'}]
            }
          })
        } else {
          this.$toast('数据错误,请重新刷新!')
        }
      },
      showClick(id){
        let _this = this
        if (id) {
          _this.pdfShow = true
        }
      }
    },
    created() {
      let id = this.$route.params.id
      this.getList(id);
    },
    mounted() { },
}
</script>
<style>
.content1 {
  padding: 0 10px;
}

.content1 h4 {
  margin: 15px 0;
  line-height: 18px;
  font-size: 20px;
  color: #000;
  letter-spacing: 0;
  font-weight: 500;
  text-align: center;
}

.content1 p {
  line-height: 20px;
  font-size: 20px;
  margin: 10px 0;
}

.content1 .type {
  line-height: 30px;
  font-size: 20px;
  /* color: #afb0b1; */
  color: rgb(20, 117, 235);

}
</style>

PDFPageView.vue

'http://localhost:8089/appApi/downloadOrViewFile?id='+this.id  获取后端地址自行修改

<template>
  <div class="PDFPageView">
    <div class="pdf_down">
<!--      <div class="pdf_set_left" @click="scaleD()">放大</div>
      <div class="pdf_set_middle" @click="scaleX()">缩小</div>-->
    </div>

    <div :style="{width:pdf_div_width,margin:'0 auto'}">
      <canvas v-for="page in pdf_pages" :id="'the_canvas'+page" :key="page" style="width: 100%"></canvas>
    </div>
  </div>
</template>

<script>
//以es5形式引入,解决低端浏览器兼容性问题
const PDFJS = require("pdfjs-dist/es5/build/pdf");
//pdfjs-dist的版本也是2.5.207
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.entry.js");

export default {
  name:"PDFPageView",
  props: {
    id: null,
  },
  data() {
    return {
      pdf_scale: 1.0,//pdf放大系数
      pdf_pages: [],
      pdf_div_width: '',
      pdf_src: null,
    }
  },
  mounted() {
    this.get_pdfurl()
  },
  methods: {
    scaleD() {  //放大
      let max = 0
      if (window.screen.width > 1440) {
        max = 1.4
      } else {
        max = 1.2
      }
      if (this.pdf_scale >= max) {
        return
      }
      this.pdf_scale = this.pdf_scale + 0.1
      this._loadFile(this.pdf_src)
    },
    scaleX() {  //缩小
      let min = 1.0
      if (this.pdf_scale <= min) {
        return
      }
      this.pdf_scale = this.pdf_scale - 0.1
      this._loadFile(this.pdf_src)
    },
    get_pdfurl() {  //获得pdf教案
      //加载本地
      
       this.pdf_src = 'http://localhost:8089/appApi/downloadOrViewFile?id='+this.id
      
      this._loadFile(this.pdf_src)
      return
      //线上请求
      //  this.$axios.get('')
      //  .then((res)=>{
      //  	this.pdf_src = res.url
      //  	this._loadFile(this.pdf_src)
      //  })
    },
    _loadFile(url) {  //初始化pdf

      let loadingTask = PDFJS.getDocument(url)
      loadingTask.promise.then((pdf) => {
            this.pdfDoc = pdf
            this.pdf_pages = this.pdfDoc.numPages
            //debugger
            this.$nextTick(() => {
              this._renderPage(1)
            })
          })
    },
    _renderPage(num) {  //渲染pdf页
      const that = this
      this.pdfDoc.getPage(num)
          .then((page) => {
            let canvas = document.getElementById('the_canvas' + num)
            let ctx = canvas.getContext('2d')
            let dpr = window.devicePixelRatio || 1
            let bsr = ctx.webkitBackingStorePixelRatio ||
                ctx.mozBackingStorePixelRatio ||
                ctx.msBackingStorePixelRatio ||
                ctx.oBackingStorePixelRatio ||
                ctx.backingStorePixelRatio || 1
            let ratio = dpr / bsr
            let viewport = page.getViewport({scale: this.pdf_scale})

            canvas.width = viewport.width * ratio
            canvas.height = viewport.height * ratio

            // canvas.style.width = viewport.width + 'px'
            canvas.style.width = '100%'

            // that.pdf_div_width = viewport.width + 'px'
            that.pdf_div_width = '100%'

            canvas.style.height = viewport.height + 'px'

            ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
            let renderContext = {
              canvasContext: ctx,
              viewport: viewport
            }
            page.render(renderContext)
            if (this.pdf_pages > num) {
              this._renderPage(num + 1)
            }
          })
    },
  }
}
</script>
<style lang="scss" scoped>
.home_wrap {
  width: 100%;
  height: 100%;

  .pdf_down {
    position: fixed;
    display: flex;
    z-index: 20;
    right: 26px;
    bottom: 7%;

    .pdf_set_left {
      width: 30px;
      height: 40px;
      color: #408FFF;
      font-size: 11px;
      padding-top: 25px;
      text-align: center;
      margin-right: 5px;
      cursor: pointer;
    }

    .pdf_set_middle {
      width: 30px;
      height: 40px;
      color: #408FFF;
      font-size: 11px;
      padding-top: 25px;
      text-align: center;
      margin-right: 5px;
      cursor: pointer;
    }
  }
}
</style>

后端代码:

KeywordsFiles实体:

package com.epsoft.xc_ygxf.entity;

import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("key_words_files")
public class KeyWordsFiles implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    @TableId(value="id", type= IdType.UUID)
    private String id;
    /**
     * 文件类型
     */
    private String type;
    /**
     * 文件名
     */
    private String originalFileName;
    /**
     * 存放的文件名
     */
    private String fileName;
    /**
     * 文件地址
     */
    private String filePath;
    /**
     * 文件访问路径
     */
    private String fileAccessPath;
    /**
     * 创建时间
     */
    @ApiModelProperty(value = "创建时间")
    @TableField(value = "create_time",fill = FieldFill.INSERT)
    private Date createTime;
}
PdfViewUtil工具类:
package com.epsoft.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


public class PdfViewUtil {
    private static PdfViewUtil pdfViewUtil;
    /** * 获取Doc2HtmlUtil实例 */
    public static synchronized PdfViewUtil getPdfViewUtilInstance() {
        if (pdfViewUtil == null) {
            pdfViewUtil = new PdfViewUtil();
        }
        return pdfViewUtil;
    }

    /*** 转换文件成pdf */
    public void fileToPdf(String filePath) throws IOException {
        String type= filePath.substring(filePath.lastIndexOf("."));
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setHeader("content-type", "text/html;charset=utf-8");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String pdfPath = null;
        File file = null;
        response.setContentType("application/pdf; charset=UTF-8");

        if(".pdf".equals(type)||".PDF".equals(type)){
            pdfPath = filePath;
        }else{
            String pdfPath1 = filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf";
            File file1 = new File(pdfPath1);
            if(!file1.exists()){
                OfficeConvertPdf officeConvertPdf = new OfficeConvertPdf();
                if(".doc".equals(type)||".docx".equals(type)){
                    pdfPath = officeConvertPdf.docConvertPdf(filePath);
                }else if(".xls".equals(type)||".xlsx".equals(type)){
                    pdfPath = officeConvertPdf.excelConvertPdf(filePath);
                }else if(".ppt".equals(type)||".pptx".equals(type)){
                    pdfPath = officeConvertPdf.pptConvertPdf(filePath);
                }else if(".txt".equals(type)){
                    pdfPath = officeConvertPdf.docConvertPdf(filePath);
                }
            }else{
                pdfPath = pdfPath1;
            }
        }
        try {
            file = new File(pdfPath);
            InputStream i = new FileInputStream(file);
            inputStream = new BufferedInputStream(i);
            OutputStream o = response.getOutputStream();
            outputStream = new BufferedOutputStream(o);

            //一次性读取2048个字节
            byte[] bs = new byte[2048];
            int l;
            while ((l=inputStream.read(bs)) != -1) {
                outputStream.write(bs,0,l);
            }

        } catch (IOException e) {
            if (file.exists()){
                //file.delete();
            }
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                if (file.exists()){
                    //file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


}

OfficeConvertPdf:

这个文件注意:有可能由于这个文件路径不对导致解析水印失败预览无效。路径自己把握

本人路径如下:

 license.xml

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  </Data>
  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
package com.epsoft.xc_ygxf.util;


import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;

import java.io.InputStream;

/**
 * @author admin
 */
@SuppressWarnings("ALL")
public class OfficeConvertPdf {
    /**
     * 转换文件类型
     */
    @SuppressWarnings("AlibabaEnumConstantsMustHaveComment")
    protected static enum FileTypeEnum {
        /**
         * WORD
         */
        WORD,
        /**
         * EXCEL
         */
        EXCEL,
        /**
         * PPT
         */
        PPT
    }

    /**
     * @param type
     * @return
     */
    private static boolean getLicense(FileTypeEnum type) {
        boolean result = false;
        try {
            // 凭证
            InputStream license = OfficeConvertPdf.class.getClassLoader().getResourceAsStream("/com/base/config/license.xml");
//            InputStream license = OfficeConvertPdf.class.getClassLoader().getResourceAsStream("license.xml");
            switch (type) {
                case WORD:
                    new com.aspose.words.License().setLicense(license);
                    break;
                case EXCEL:
                    new com.aspose.cells.License().setLicense(license);
                    break;
                case PPT:
                    new com.aspose.slides.License().setLicense(license);
                    break;
                default:
                    new com.aspose.words.License().setLicense(license);
                    break;
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * word转pdf
     *
     * @param docPath
     */
    public String  docConvertPdf(String docPath) {
        String pdfPath = docPath.substring(0, docPath.lastIndexOf(".")) + ".pdf";
        if (!getLicense(FileTypeEnum.WORD)) {
            System.out.println("doc2pdf,解析水印失败,请重试");
            return pdfPath;
        }
        try {
            long old = System.currentTimeMillis();
            Document convertDoc = new Document(docPath);
            convertDoc.save(pdfPath, com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfPath;
    }

    /**
     * excel转pdf
     *
     * @param excelPath
     */
    public  String excelConvertPdf(String excelPath) {
        String pdfPath = excelPath.substring(0, excelPath.lastIndexOf(".")) + ".pdf";
        if (!getLicense(FileTypeEnum.EXCEL)) {
            return pdfPath;
        }
        try {
            long old = System.currentTimeMillis();
            Workbook convertExcel = new Workbook(excelPath);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            convertExcel.save(pdfPath, pdfSaveOptions);
            long now = System.currentTimeMillis();
            System.out.println("转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfPath;
    }
    /**
     * ppt转pdf
     *
     * @param excelPath
     */
    public  String pptConvertPdf(String pptPath) {
        String pdfPath = pptPath.substring(0, pptPath.lastIndexOf(".")) + ".pdf";
        if (!getLicense(FileTypeEnum.PPT)) {
            return pdfPath;
        }
        try {
            long old = System.currentTimeMillis();
            Presentation convertPpt = new Presentation(pptPath);
            convertPpt.save(pdfPath, com.aspose.slides.SaveFormat.Pdf);
            long now = System.currentTimeMillis();
            System.out.println("转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfPath;
    }
    private static OfficeConvertPdf officeConvertPdf;

    /**
     * 获取Doc2HtmlUtil实例
     */
    public static void main(String[] args) {
        OfficeConvertPdf officeConvertPdf = new OfficeConvertPdf();
//        officeConvertPdf.pptConvertPdf("D:/12.docx");
        officeConvertPdf.docConvertPdf("D:/12.docx");
    }
}

controller:

@RequestMapping(value = "/downloadOrViewFile",method = RequestMethod.GET)
  public void downloadOrViewFile(String id) throws IOException {
    Assert.isTrue(org.springframework.util.StringUtils.hasText(id), "id不能为空");
    keyWordsFilesService.downloadOrViewFile(id);
  }

servicesImpl:

@Override
    public void downloadOrViewFile(String id) {
        QueryWrapper<KeyWordsFiles> queryWrapper = new QueryWrapper<KeyWordsFiles>();
        queryWrapper.eq("id",id).orderByDesc("create_time").last("limit 1");
        List<KeyWordsFiles> tAttachmentSxelist = keyWordsFilesMapper.selectList(queryWrapper);
        Assert.isTrue(tAttachmentSxelist.size()>0, "附件下载不存在!");
        String originalFileName = tAttachmentSxelist.get(0).getOriginalFileName();
        String filePath = tAttachmentSxelist.get(0).getFilePath();
        if(StringUtils.isNotEmpty(filePath)){
            PdfViewUtil pdfViewUtilInstance = PdfViewUtil.getPdfViewUtilInstance();
            try {
                pdfViewUtilInstance.fileToPdf(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值