@qwentry

Из-за чего ошибка при использовании docxtemplater и JSZip/PizZip?

Доброго времени суток.
Использую библиотеку docxtemplater для подстановки данных в шаблон документа ворд.
Для начала прям по примеру сделал, как в документации, все работает..
Но стоит мне поменять путь .docx файла на свой,
loadFile("https://docxtemplater.com/tag-example.docx",functi... - путь из примера документации
loadFile('../assets/tag-example.docx',function(error,content) - мой путь
то сразу вылеает ошибка:
Uncaught Error: Can't find end of central directory : is this a zip file ?
at ZipEntries.readEndOfCentral (zipEntries.js?5921:191)
at ZipEntries.load (zipEntries.js?5921:296)
at new ZipEntries (zipEntries.js?5921:32)
at PizZip.module.exports [as load] (load.js?07ec:25)
at new PizZip (index.js?547c:41)
at eval (TestDoc.vue?9786:49)
at XMLHttpRequest.xhr.onreadystatechange (index.js?85d7:82)

Сам код вот:
<template>
  <div class="main-container">
    <button class="btn btn-primary" @click="renderDoc">Сформировать документ</button>
  </div>
</template>

<script>
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import PizZipUtils from "pizzip/utils/index.js";
import { saveAs } from "file-saver";

function loadFile(url,callback){
  PizZipUtils.getBinaryContent(url,callback);
}

export default {
  methods: {
    renderDoc() {
      loadFile('../assets/tag-example.docx',function(error,content){
        if (error) { throw error };

        // The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
        function replaceErrors(key, value) {
          if (value instanceof Error) {
            return Object.getOwnPropertyNames(value).reduce(function(error, key) {
              error[key] = value[key];
              return error;
            }, {});
          }
          return value;
        }

        function errorHandler(error) {
          console.log(JSON.stringify({error: error}, replaceErrors));

          if (error.properties && error.properties.errors instanceof Array) {
            const errorMessages = error.properties.errors.map(function (error) {
              return error.properties.explanation;
            }).join("\n");
            console.log('errorMessages', errorMessages);
            // errorMessages is a humanly readable message looking like this :
            // 'The tag beginning with "foobar" is unopened'
          }
          throw error;
        }

        var zip = new PizZip(content);
        var doc;
        try {
          doc = new docxtemplater(zip);
        } catch(error) {
          // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
          errorHandler(error);
        }

        doc.setData({
          first_name: 'John',
          last_name: 'Doe',
          phone: '0652455478',
          description: 'New Website'
        });
        try {
          // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
          doc.render();
        }
        catch (error) {
          // Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)
          errorHandler(error);
        }

        var out=doc.getZip().generate({
          type:"blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        }) //Output the document using Data-URI
        saveAs(out,"output.docx")
      })
    },
  },
}
</script>

<style scoped>

</style>


Подскажите как исправить эту ошибку с "Can't find end of central directory : is this a zip file ?"
  • Вопрос задан
  • 354 просмотра
Решения вопроса 1
Aetae
@Aetae Куратор тега JavaScript
Тлен
А у тебя есть этот файл в ../assets/tag-example.docx на сервере? Скорее всего нет.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Dittmerok
Логично, что нет. Так и как можно заменить файл, которые лежит на серваке. Своим файлом, который я хочу рассположить локально в проекте?
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы