在Angular 7的docx库中显示图片

问题描述

我正在使用Angular 7 我正在以docx格式导出文件。我在显示文件中的图像时遇到问题。

这是我正在引用的代码。而不是下面的代码中的“ fs”,我使用的是文件保存器,因为Angular不支持fs

import * as fs from "fs";

import { Document,Media,Packer,Paragraph,textwrappingSide,textwrappingType } from 'docx';

const doc = new Document();

const image = Media.addImage(doc,fs.readFileSync("./demo/images/pizza.gif"),200,200);

doc.addSection({
    children: [
        new Paragraph(image),],});

Packer.toBlob(doc).then((buffer) => {
    FileSaver.writeFileSync("My Document.docx",buffer);
});

我当前的代码在这里..我正在使用FileSaver,但不支持readFileSync方法..所以问题是如何在angualr中实现在docx文件显示图像

import * as FileSaver from 'file-saver';


import { Document,FileSaver.readFileSync("./demo/images/pizza.gif"),});


Packer.toBlob(doc).then((buffer) => {
    FileSaver.writeFileSync("My Document.docx",buffer);
});

感谢您的帮助。如果需要其他任何信息,请告诉我。

有关确切问题,请参考此链接https://stackblitz.com/edit/angular-jzfdbe?file=src%2Fapp%2Fcv-generator.ts

解决方法

我猜您要生成文件,然后立即触发下载到浏览器?

如果是这样,那么很幸运,您遇到了麻烦。此代码是跨浏览器兼容的。出于这种需要,我已经多次使用了相同的代码段。

Packer.toBlob(doc).then((blob) => {
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob,"My Document.docx");
    } else {
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = "My Document.docx";
        document.body.appendChild(link);
        link.click();
    }
});
,

嗨,伙计们,我在这个问题上挣扎了一段时间,经过几个小时的谷歌搜索,我想出了这个

定义数组缓冲区

arrayBuffer: ArrayBuffer;

从资产中获取图像并转换为arrayBuffer

this.http.get('/assets/logo-uvzsr.png',{responseType: 'blob'})
  .subscribe(
    res => {
      const bufferPromise = res.arrayBuffer();
      bufferPromise.then(
          buffer =>
          {
            this.arrayBuffer = buffer;
        }
      );

    }
  );

在图像运行中使用

      new Paragraph({
          children: [
            new ImageRun({
              data:  this.arrayBuffer,transformation: {
                width: 200,height: 200,},})
          ]
        })

我希望它会帮助某人 :) 快乐编码