【问题标题】:Converting BLOB (docxtemplater) to PDF - REACT将 BLOB (docxtemplater) 转换为 PDF - REACT
【发布时间】:2022-12-26 08:02:07
【问题描述】:

大家好我正在使用 React.js 和 Node.js 开发一个网站,我在其中根据用户的输入生成一个 word 文档,这与 docxtemplater 一起工作得很好!

问题是我想让用户直接下载 word 文档作为 PDF 文档,但 docxtemplater 只允许我们将文件另存为 docx。 要转换 docx,我想用 gridfs 将我的 blob 文档保存在 mongodb 中(已经完成并且工作正常),然后获取我的 blob 并将其转换为 pdf(我被阻止了)

这是我的代码部分,用于生成我的 docx 并将生成的单词 docx 保存在 mongodb 中(我有意删除了一些对这个问题不重要的东西)

import React, { useState, useEffect } from "react";
import Docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import PizZipUtils from "pizzip/utils/index.js";
import { saveAs } from "file-saver"; 
import axios from "axios";

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

export const DocxFile = ({ formData }) => {
  const [file, setFile] = useState(null);
  const [currentlyUploading, setCurrentlyUploading] = useState(false);
  const [docxId, setDocxId] = useState(null);
  const [progress, setProgress] = useState(null);
  const [inputContainsFile, setInputContainsFile] = useState(false);
  const [template, setTemplate] = useState();


  const generateDocument = () => {
    loadFile(template, function (error, content) {
      if (error) {
        throw error;
      }

      var zip = new PizZip(content);
      var doc = new Docxtemplater(zip, {
        paragraphLoop: true,
        linebreaks: true,
      });

      doc.setData({
        company: formData.general.companyClient,
        version: formData.documentVersion,
        quote: formData.general.quoteNumber,
        HERE MY DATA //Working :)
      });
      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;
        }

        if (error.properties && error.properties.errors instanceof Array) {
          const errorMessages = error.properties.errors
            .map(function (error) {
              return error.properties.explanation;
            })
            .join("\n");
        }
        throw error;
      }
      var out = doc.getZip().generate({
        type: "blob",
        mimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      saveAs(
        out,
        `${name}.${documentVersion}.docx`
      );

      setFile(out);
      setInputContainsFile(true);
    });
  };

  const fileUploadHandler = () => {
    const fd = new FormData();
    fd.append("docx", file, file.name);
    axios
      .post(`api/docx/upload`, fd, {
        onUploadProgress: (ProgressEvent) => {
          setProgress((ProgressEvent.loaded / ProgressEvent.total) * 100);
          console.log(
            "upload progress",
            Math.round((ProgressEvent.loaded / ProgressEvent.total) * 100)
          );
        },
      })
      .then(({ data }) => {
        setDocxId(data);
        setFile(null);
        setInputContainsFile(false);
        setCurrentlyUploading(false);
      })
      .catch((err) => {
        console.log(err);
        if (err.response.status === 400) {
          const errMsg = err.response.data;
          if (errMsg) {
            console.log(errMsg);
          }
        } else {
          console.log("other error", err);
          setInputContainsFile(false);
          setCurrentlyUploading(false);
        }
      });
  };
  const handleClick = () => {
    if (inputContainsFile) {
      setCurrentlyUploading(true);
      fileUploadHandler();
    }
  };

  return (
    <>
      <button
        className="modify__button1 enregistrer generator__button"
        onClick={generateDocument}
      >
       Generate the docx
      </button>
      <label htmlFor="file" onClick={handleClick}>
        {file ? <>SUBMIT</> : <></>}
      </label>
    </>
  );
};

这是我发送后在 mongodb 上得到的:MongodbBLOB

之后,我将执行获取请求以获取我的 blob(我已经知道如何获取我的 blob)但是,我如何将其转换为 pdf(并保留用于我的 docx 的模板)?

【问题讨论】:

    标签: reactjs blob gridfs docxtemplater


    【解决方案1】:

    更新 :

    我找到了一个名为 docx-pdf 的包,它允许我将我的 docx 转换为 pdf。

    但不幸的是,我在编译时遇到了很多 webpack 问题(无法解析 'fs'、'child_process'、'path'),因为“webpack < 5 过去默认包含 node.js 核心模块的 polyfill。 “

    我会尝试解决这个问题,如果我成功转换了我的 docx,我会更新这个答案 :)

    【讨论】:

    • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以在in the help center找到更多关于如何写出好的答案的信息。
    【解决方案2】:

    任何更新 ?

    我也有兴趣使用 docxtemplater 将 docx 创建为 pdf。

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2019-08-19
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 2018-06-25
      • 2014-12-04
      相关资源
      最近更新 更多