如何在转换为pdf的ejs模板中添加图像

how to add image in ejs template which is converted to pdf

我正在使用 api 将我的 ejs 模板转换为 pdf,它会获取多个数据。我能够从 api 的 json 响应中将数据插入模板。但我在图像方面遇到了麻烦。该图像是 html canvas 的一团。我将它转换为 base64 并通过另一个 api.

将其名称插入到数据库中

我的 api 回复,

  "data2": [
            {
                "graph_img": "http://localhost:5000/public/images/graph_images_for_pdf/2021102161712PM.jpeg"
            }
        ],

我是如何在 ejs 模板中使用它的,

<% dataw.data2.forEach(function(a){ %>   
                        <div class="row">
                            <div class="col-sm-6"> 
                                <div class="mb-4 pull-left">

                                   <div >  <%= a.graph_img %>  </div>
                                </div>
                            </div>
                          
                        </div>
                        <% }); %>

这在我的 pdf 中提供了 http://localhost:5000/public/images/graph_images_for_pdf/2021102161712PM.jpeg。如何改为添加图片。

  var fs = require ("fs");
      var image = graphimage;
      var bitmap = Buffer.from(image, 'base64');
       var _path = "./public/images/graph_images";
      var imagename = nmae+".jpeg";
      fs.writeFileSync(_path+'/'+imagename, bitmap);

这就是我在 api 中保存文件的方式。其中 graphimage 是来自前端的字符串。

您需要去掉字符串开头的base64签名标签,才能成功解析。代码应该是这样的

var fs = require ("fs");
      var image = graphimage.replace("data:image/jpeg", "");
      var bitmap = Buffer.from(image, 'base64');
       var _path = "./public/images/graph_images";
      var imagename = nmae+".jpeg";
      fs.writeFileSync(_path+'/'+imagename, bitmap);