1

我在我的 Asp.net MVC5 项目中使用 MvcRazorToPdf 从模型创建 pdf。这很好用,但我想包含来自 base64 字符串的图像,因为我不想保存生成的图像。

System.Drawing.Image img = generator.GenerateImage();
string imageBase64Data = Convert.ToBase64String(Helper.ImageToByteArray(img));
string imageDataURL = string.Format("data:image/png;base64,{0}", imageBase64Data);
ViewBag.Image = imageDataURL;

return new PdfActionResult(myobject);

...

<img src="@ViewBag.Image" />

工作正常,如果在普通视图中显示图像,但 pdf 不显示图像。

感谢您的帮助或替代方案。

4

2 回答 2

1

可能我回答太晚了。如果您需要基于 base64 字符串的图像是为了避免将图像存储在文件系统中,您可以编写一个返回图像文件并在img标签中引用该 url 的操作:

public ActionResult GetImage(/*probably some id*/)
{ 
    System.Drawing.Image img = generator.GenerateImage();
    ImageConverter converter = new ImageConverter();
    var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));
    return File(bytes, "image/jpg"); // if your image is jpg
}

然后你的剃须刀看起来像:

<img src='@Url.Action("GetImage", "Images", null, Request.Url.Scheme)' />

注意Request.Url.Scheme Url.Action重载的使用非常重要,因为 iTextSharp 需要完整的限定 URL。

于 2015-06-08T18:19:30.497 回答
0

在 MvcRazorToPdf 中,您只能使用图像文件的完整(本地)路径,如下所示:

@model MvcRazorToPdfExample.Models.PdfExample
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_PdfLayout.cshtml";
    var imagePath = Server.MapPath("~/Content/Images");
}

 <img src="@imagePath\avatar.jpg" alt="mug shot" />

据我所知,不支持 Base64 图像。我从示例视图中复制了上面的片段: https ://github.com/andyhutch77/MvcRazorToPdf/blob/master/MvcRazorToPdfExample/Views/Pdf/Index.cshtml

于 2015-03-09T14:46:23.567 回答