[英]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.