doc.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import JSZip from 'jszip';
  2. import { saveAs } from 'file-saver';
  3. import JSZipUtils from 'jszip-utils';
  4. import Docxtemplater from 'docxtemplater';
  5. import ImageModule from 'docxtemplater-image-module-free';
  6. const loadImage = async (tagValue) => {
  7. try {
  8. const response = await fetch(tagValue);
  9. if (!response.ok) {
  10. throw new Error('Network response was not ok');
  11. }
  12. const blob = await response.blob();
  13. return URL.createObjectURL(blob);
  14. } catch (error) {
  15. console.error('There was a problem with the fetch operation:', error);
  16. return null; // 返回 null 或者合适的错误处理
  17. }
  18. };
  19. export const exportDocx = async (tempDocxPath, dataList, zipFileName) => {
  20. try {
  21. // 加载模板文件
  22. const content = await new Promise((resolve, reject) => {
  23. JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
  24. if (error) {
  25. reject(error);
  26. } else {
  27. resolve(content);
  28. }
  29. });
  30. });
  31. // 初始化 JSZip 实例,用于打包多个文件
  32. const zip = new JSZip();
  33. // 遍历每一条数据,生成单独的 .docx 文件
  34. for (let i = 0; i < dataList.length; i++) {
  35. const data = dataList[i];
  36. const imageOptions = {
  37. async getImage(tagValue) {
  38. const imageUrl = await loadImage(tagValue);
  39. console.log(imageUrl, "我在这里");
  40. return imageUrl;
  41. },
  42. getSize() {
  43. return [150, 150];
  44. },
  45. };
  46. const doc = new Docxtemplater(zip, {
  47. modules: new ImageModule(imageOptions),
  48. });
  49. doc.render({
  50. image: "logo.png",
  51. });
  52. const zipContent = doc.getZip(); // 获取 zip 对象
  53. if (!zipContent) {
  54. throw new Error('Docxtemplater failed to load zip content.');
  55. }
  56. // 生成 .docx 文件
  57. const out = await zipContent.generateAsync({
  58. type: 'blob',
  59. mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  60. });
  61. // 将生成的 .docx 文件添加到 zip 包中
  62. zip.file(`document_${i + 1}.docx`, out);
  63. }
  64. // 生成 zip 文件并保存
  65. const zipBlob = await zip.generateAsync({ type: 'blob' });
  66. saveAs(zipBlob, zipFileName);
  67. console.log(`文件已成功生成并打包为 ${zipFileName}`);
  68. } catch (error) {
  69. console.error('导出文件时出错:', error);
  70. throw error;
  71. }
  72. };