Xx, our PDF document needs a preview function, please work overtime today to do it…

Environment: File server: FDFS Front-end: VUE back-end: Springboot

Simply using PDF.js for previewing presents cross-domain problems, so the back end needs to pass the file to the front end, and then the front end displays it.

1.Download the PDF. JsIf it cannot be opened, download the modified one I have savedpdf.js

2. Copy the build and Web files in the downloaded file to the public folder of the vUE project

3. The code

3.1 the vue front-end
 <template>
  <div>
    <el-button @click="pdf"</el-button> <el-button@click="downloadPdf()"</el-button> </div> </template> <script> exportdefault {
  name: "pdf",
  data(){
    return {
      fileUrl: 'http://file.clzn.sunline.cn:8283/group1/M00/00/00/ChZVMmBZm8CANMbbAE4a0Em_r80670.pdf',
      newUserId: null
    }
  },
  mounted() {
  },
  methods: {
    downloadClick(){
      var link = document.createElement('a');
      link.setAttribute("download"."");
      link.href = "./batchCaseUpdate.xlsx";
      link.click();
    },


    pdf() {
      console.log('preview PDF')
      this.axios({
        methods: 'get',
        url: '/api/readPdfFile',
        params: {
          fileUrl: this.fileUrl
        },
        responseType: 'blob',
        headers:{
          'Content-Type': 'application/json'
        }
      }).then(res => {
        let blob = new Blob([res.data], {type: 'application/pdf'}) let href = URL.createObjectURL(blob) console.warn(href) window.open(`./pdf/web/viewer.html? file=${encodeURIComponent(href)}`); }) }, downloadPdf() { console.log('to download the PDF)
      this.axios({
        methods: 'get',
        url: '/api/readPdfFile',
        params: {
          fileUrl: this.fileUrl
        },
        responseType: 'blob',
        headers:{
          'Content-Type': 'application/json'
        }
      }).then(res => {
        const link = document.createElement('a')
        let blob = new Blob([res.data], {type: 'application/pdf'})
        link.href = URL.createObjectURL(blob)
        link.style.display = 'none'
        link.style.target = '_blank'
        link.href = URL.createObjectURL(blob)
        console.warn(link.href)
        link.download = new Date().getTime() // The file name of the download
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    }
  }
}
</script>

<style scoped>

</style>


Copy the code
3.2 Java backend

3.2.1 controller layer

    /** * PDF preview function **@param response
     * @param fileUrl
     */
    @GetMapping("/readPdfFile")
    public void previewPdf(HttpServletResponse response , String fileUrl){
        ExportFileUtil.preview(response, fileUrl);
    }
Copy the code

3.2.2 the service layer

		/** * File preview *@param response
     * @param filePath
     */
    public static void preview(HttpServletResponse response, String filePath) {
        ServletOutputStream out;
        BufferedInputStream buf;
        try {
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition"."inline; fileName=" + filePath.substring(filePath.lastIndexOf("/") + 1));
            URL url = new URL(filePath);
            Read a file input stream using the input read buffer stream
            buf = new BufferedInputStream(url.openStream());
            // Get a byte stream output object using response
            out = response.getOutputStream();
            // Define an array for reading the contents of the buffer stream
            byte[] buffer = new byte[1024];
            int n;
            // The while loop keeps reading the contents of the buffer stream into the output object
            while((n = buf.read(buffer)) ! = -1) {
                out.write(buffer, 0, n);
            }
            // Write to the requested location
            out.flush();
            buf.close();
            out.close();
        } catch (IOException e) {
            StaticLog.error("ExportFileUtil.download() IOException", e);
        } catch (Exception e) {
            StaticLog.error("Exception", e); }}Copy the code

4. See the effect

5. Success ~ ~ ~ Demo address -github Demo address -gitee