[英]Get image with Url.Action and stream to PDF (ASP.NET MVC 3 C#)
我正在尝试将图像流式传输到视图,并使其制成PDF文件。
这是我的(部分)CSHTML文件:
@if (TempData["foto"] != null)
{
<p>
@Html.Raw(TempData["foto"] + "")
</p>
}
在控制器中,我使用以下代码填充TempData [“ foto”]:
TempData["foto"] = "<img src = \"" + Url.Action("getImage", "base", new { @type = "machine", @val = sqlOnderhoud.First().machine_id }) + "\" class = \"imgMachine\" alt = \"Afbeelding machine\" />";
BaseController / getImage中的代码是:
public ActionResult getImage(string type, string val)
{
if (!String.IsNullOrEmpty(type) && !String.IsNullOrEmpty(val))
{
string filePath = String.Empty;
if (type == "machine")
{
filePath = WebConfigurationManager.AppSettings["upload_path"] + "\\machines\\" + val + ".jpg";
}
else if (type == "handtekening")
{
filePath = WebConfigurationManager.AppSettings["upload_path"] + "\\handtekeningen\\" + val + ".jpg";
}
FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
FileStreamResult result = new FileStreamResult(stream, "image/png");
result.FileDownloadName = type + "-" + val + ".png";
return result;
}
else
{
return View();
}
}
当我将图像流式传输到屏幕而不创建PDF时,它将显示我的图像。 BUT,当我随后打开PDF文件时,图像损坏了……我认为这是因为当base / getImage作为纯文本读取时未执行。
要获取HTML字符串,请使用以下代码:
string body = string.Empty;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "TemplatePDF/onderhoud_rapportage");
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
body = sw.GetStringBuilder().ToString();
}
生成PDF的代码:
byte[] pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, para.baseURL);
希望有人也能帮助我将图像保存在PDF文件中!
亲切的问候,丹尼斯
PS:之所以要流图像,是因为这些图像位于Content文件夹之外,它们位于另一个HDD上...
修复:因为PDF是在服务器上创建的,所以我可以从站点D:\\链接文件,并且它现在在PDF中显示我的图像!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.