简体   繁体   中英

Get image with Url.Action and stream to PDF (ASP.NET MVC 3 C#)

I'm trying to stream images to a View and make a PDF file of it.

This is my (Partial) CSHTML file:

@if (TempData["foto"] != null)
{
    <p>
        @Html.Raw(TempData["foto"] + "")
    </p>
}

In the controller I'm using this code to fill TempData["foto"]:

TempData["foto"] = "<img src = \"" + Url.Action("getImage", "base", new { @type = "machine", @val = sqlOnderhoud.First().machine_id }) + "\" class = \"imgMachine\" alt = \"Afbeelding machine\" />";

The code in BaseController/getImage is:

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();
}

}

When i stream the image to the screen without creating a PDF of it, it will show my image. BUt when I open the PDF file afterwards, there is a broken image... I think it's because the base/getImage is not executed when it's read as plain text.

To get the HTML string I use this code:

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();
}

Code that makes the PDF:

byte[] pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, para.baseURL);

Hopefully someone can help me to get the image in the PDF file too!

Kind Regards, Dennis

PS: The reason why I stream images, is because of the fact the images are outside of the Content folder, they're on another HDD...

修复:因为PDF是在服务器上创建的,所以我可以从站点D:\\链接文件,并且它现在在PDF中显示我的图像!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM