The front end implements online preview of Word files

insert image description here

Introduction

I encountered a requirement in the project, the general requirement is this: before uploading a file, the user needs to preview the content first, confirm whether the content is correct, and then upload it if it is correct ;
then this will involve a preview of the document before uploading Operation, the following is a record of stepping on the pit record

docx-preview

This is a pure front-end JavaScript library . Its advantage is that it can preview files online without relying on the back-end. The disadvantage is that it does not support doc, does not support doc, does not support doc , and the important thing is said three times ; The github address is as follows: docx-preview , interested friends can take a closer look at the official introduction;.docx

Install

npm install docx-preview -S

If the installation fails all the time, you can try to use it cnpmto install

cnpm install docx-preview -S

In addition, due to the need for parsing , it is necessary to useadditionalInstall and introduce a parsing library jszip . Since the library is not in the form of a module, it needs to be introduced in the header tag in html . The file address: https://unpkg.com/jszip/dist/jszip.min.js

<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8" />
        <script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
    </head>
    <body>
    </body>
</html>

It is recommended to download the file directly in the project and put it into the project;

use

Let's take a look at the official example first

<!--optional polyfill for promise-->
<script src="https://unpkg.com/promise-polyfill/dist/polyfill.min.js"></script>
<!--lib uses jszip-->
<script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script src="docx-preview.min.js"></script>
<script>
    var docData = <document Blob>;

    docx.renderAsync(docData, document.getElementById("container"))
        .then(x => console.log("docx: finished"));
</script>
<body>
    ...
    <div id="container"></div>
    ...
</body>

Simply put, it has 3 parameters, the first parameter is the received file data stream , the second parameter is the container , and it has a then callback function, which will be executed successfully, but this is not it For all the APIs, you can go to github to find the specific APIs. These APIs should be used very little, and these few are enough;

Example of using docx-preview in Vue

This chapter implements an example of selecting files locally and displaying them online. The general steps are as follows:

  1. Select a docx file and get the file;
  2. Convert the file to blob format;
  3. Pass the data flow display in Blob format into dox-preview, and display it;

The first step is the first step , the Html part is as follows, the IViewcomponent Upload组件uses elementthe same, the purpose is to obtain the selected file through the component

<Upload
    action
    name="file"
    id="file"
    multiple="multiple"
    :auto-upload="false"
    :before-upload="init"
>
    <Button size="small" type="primary">点击上传</Button>
</Upload>

Read the file after selecting it

 init(file) {
    
    
    var reader = new FileReader();
    reader.onload = (e) => {
    
    

    };
    // 传入一个参数对象即可得到基于该参数对象的文本内容
    reader.readAsDataURL(file);
},

The second step is to read the file data and convert into a data stream in Blob format

 let arr = e.target.result.split(",");
let data = window.atob(arr[1]);
let mime = arr[0].match(/:(.*?);/)[1];
let ia = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
    
    
    ia[i] = data.charCodeAt(i);
}
const blob = new Blob([ia], {
    
     type: mime });
console.log(blob);

The third step is to plug docx-previewinto the display

docx.renderAsync(blob, this.$refs.demoDocContainer).then(
    (x) => {
    
    
        console.log(x);
    }
); // 渲染到页面

The display can be completed, the effect is as follows:
insert image description here

The complete code is as follows

<template>
    <div id="app">
        <Upload
            action
            name="file"
            id="file"
            multiple="multiple"
            :auto-upload="false"
            :before-upload="init"
        >
            <Button size="small" type="primary">点击上传</Button>
        </Upload>
        <div class="doc-preview" ref="demoDocContainer">1</div>
    </div>
</template>
<script>
let docx = require("docx-preview");
export default {
    
    
    name: "docx-demo",
    methods: {
    
    
        init(file) {
    
    
            var reader = new FileReader();
            reader.onload = (e) => {
    
    
                let arr = e.target.result.split(",");
                let data = window.atob(arr[1]);
                let mime = arr[0].match(/:(.*?);/)[1];
                let ia = new Uint8Array(data.length);
                for (var i = 0; i < data.length; i++) {
    
    
                    ia[i] = data.charCodeAt(i);
                }
                const blob = new Blob([ia], {
    
     type: mime });
                docx.renderAsync(blob, this.$refs.demoDocContainer).then(
                    (x) => {
    
    
                        console.log(x);
                    }
                ); // 渲染到页面
            };
            // 传入一个参数对象即可得到基于该参数对象的文本内容
            reader.readAsDataURL(file);
        },
    },
};
</script>
<style lang="less">
#app {
    
    
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
}
.doc-preview {
    
    
    width: 100%;
    height: 800px;
    background-color: #f5f5f5;
}
</style>

error handling

Encountered an error in the use of the use, as follows
insert image description here

Later, it was found that the reason was that the selected file format doc格式was , so it could not be recognized. I would like to emphasize that this component can only recognize the docx format, and does not support word recognition in the doc format ;

doc format recognition

If it is necessary to identify files in doc format, then the pure front-end should not work (mainly because I have not found a suitable method, if there is a big guy who has studied and lived a piece, please leave a message to let me know, thank you very much), so no matter which one of the following The method requires the cooperation of the background, and the general method is as follows;

Convert to PDF format

As in the title, pass the file in doc format to the background, and after the background gets it, convert it into PDF format, which will be convenient. The front desk can display the front desk through a tool library pdfjssimilar // mozilla.github.io/pdf.js/ , the specific usage can be viewed on the official website, if
you download it, you can download it from the official website, or install it on npm
insert image description here

Of course, in addition to pdfjs, there is another method, which is to display iframethrough . This method is simpler, but a little primitive, and to be honest, Iframeit is not but it is really easy to use in many cases. For example, now, The usage is as follows

<iframe :src="url"></iframe>

The url is the address of the file in the background. Due to the characteristics of the iframe, the file displayed by the path can be directly displayed in the area...

summary

If you do not need to recognize doc files, it is recommended to use docx-previewto preview online. If must be compatible with doc , it is recommended to convert to PDF format pdfjsand Iframepreview through or other library files;

Guess you like

Origin blog.csdn.net/zy21131437/article/details/126304514