1

i'm trying to implement docxtemplater in my react app to generate a word doc file however i keep getting this error.

in this code, a word docs is suppose to be generated when handleConvert is called. i'm using the template exactly from the docs from docxtemplater which also does not generate an output docs in my code. Originally, i linked a local word doc template named 'tag-example. i tried replacing 'https://docxtemplater.com/tag-example.docx' with 'tag-example.docx', the path to tag-example and even tried uploading the file on my firebase storage and using the link, which would bring me to a prompt to download the word docs file just like the one in the docxtemplater template does. But they all do not work, instead the error in the title comes up.

Would appreciate any help!

import React, { useState } from "react";
import { Button, Modal, Form } from "react-bootstrap";
import Docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import PizZipUtils from "pizzip/utils/index.js";
import { saveAs } from "file-saver";
import { auth, db } from "../../firebase";
import { getDoc, doc, updateDoc } from "@firebase/firestore";
import "./Note.css";

const ConvertButton = ({ noteTitle }) => {
  const [showModal, setShowModal] = useState(false);
  const [selectedTags, setSelectedTags] = useState([]);

  const handleCloseModal = () => {
    setShowModal(false);
  };

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

  //convert to cheatsheet
  const handleConvert = async () => {
    const user = auth.currentUser;
    const userId = user.uid;
    const userNotesRef = doc(db, "users", userId, "notes", noteTitle);
    const noteSnapshot = await getDoc(userNotesRef);
    const noteData = noteSnapshot.data().content;

console.log("Conversion:", selectedTags);
setShowModal(false);

let filteredData = {
  blocks: [],
};

console.log("filtering data...", filteredData);
const userFilteredRef = doc(
  db,
  "users",
  userId,
  "filteredStrings",
  noteTitle
);
await updateDoc(userFilteredRef, filteredData);

loadFile(
  'https://docxtemplater.com/tag-example.docx',
  function (error, content) {
    if (error) {
      throw error;
    }
    var zip = new PizZip(content);
    var doc = new Docxtemplater(zip, {
      paragraphLoop: true,
      linebreaks: true,
    });
    doc.setData(filteredData);
    try {
      doc.render();
    } catch (error) {
      function replaceErrors(key, value) {
        if (value instanceof Error) {
          return Object.getOwnPropertyNames(value).reduce(function (
            error,
            key
          ) {
            error[key] = value[key];
            return error;
          },
          {});
        }
        return value;
      }
      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);
      }
      throw error;
    }
    var out = doc.getZip().generate({
      type: "blob",
      mimeType:
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    });
    saveAs(out, "output.docx");
  }
);
};

  //choose tags
  const handleTagChange = (event) => {
    const { value, checked } = event.target;
    if (checked) {
      setSelectedTags([...selectedTags, value]);
    } else {
      setSelectedTags(selectedTags.filter((tag) => tag !== value));
    }
  };

  return (
    <>
      <Button
        type="button"
        id="cheatsheet-convert"
        className="btn-success"
        onClick={() => setShowModal(true)}
      >
        Convert to Cheatsheet
      </Button>
<Modal show={showModal} onHide={handleCloseModal}>
        <Modal.Header closeButton>
          <Modal.Title>Convert Settings</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group controlId="formTags">
              <Form.Label>Tags:</Form.Label>
              <Form.Check
                type="checkbox"
                id="boldTag"
                label="Bold"
                value="Bold"
                checked={selectedTags.includes("Bold")}
                onChange={handleTagChange}
              />
              <Form.Check
                type="checkbox"
                id="underlineTag"
                label="Underline"
                value="Underline"
                checked={selectedTags.includes("Underline")}
                onChange={handleTagChange}
              />
            </Form.Group>
          </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleCloseModal}>
            Cancel
          </Button>
          <Button variant="success" onClick={handleConvert}>
            Convert
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};

export default ConvertButton;
pauzi
  • 11
  • 1
  • There's nothing wrong with the zip file – Mark Adler Jul 28 '23 at 18:41
  • The text of the error message is a little bit misleading. In your case, the cause of the error is that the Word template can not be found in the location you specified. Can you open the Word file via a URL in your web browser? – Mario Varchmin Jul 31 '23 at 13:33

0 Answers0