MvcRazorToPdf - images not rendering, MVC4

一世执手 提交于 2019-12-22 14:47:13

问题


I have been trying to render an image but with no positive result. Is there anything specific I need to add to make it work. I am not including the rest of the View which renders fine, but in the pdf, the image is missing.

I have followed the below link:
https://github.com/andyhutch77/MvcRazorToPdf

View

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


<div style="width: 200%; height: 80px;">
    <div>
        <img alt="Test123" src="@imagePath\image.jpg" /> // not rendering
        @*<img alt="Test123" src="@Url.Content("~/Images/image.jpg")" />*@
    </div>
</div>

I can see that the <div> is occupying the width and height but it is not showing the image inside of it.


回答1:


I had the same problem. My solution is this: in the controller try to put in the model the complete image path with Server.MapPath:

model.ImgPath = Server.MapPath("~/Content/Images/image.jpg");

then use

byte[] pdfOutput = ControllerContext.GeneratePdf(
                    model,
                    "ImagePage",
                    (writer, document) =>
                    {
                        document.SetMargins(/*put your margins here*/);
                        document.SetPageSize(PageSize.A4);
                        document.NewPage();
                    });

where ImagePage is the .cshtml view I used for the purpose. Remember to set the margins.

Then in the view do something like this:

<img src="@Model.ImgPath" />

So, in your case, another problem maybe the use of div properties, especially the percentage. I had this problem too, and in the end I used TuesPechkin library for some things, but I still use MvcRazorToPdf for other things like print pages with dynamic content. Depends on the purpose. Try to remove div properties.

I hope this will help you!




回答2:


If you want to convert HTML to PDF without any issue, just use Pechkin here is the Fluent API :

byte[] pdf = new Pechkin.Synchronized.SynchronizedPechkin(
                          new Pechkin.GlobalConfig()).Convert(
                                new Pechkin.ObjectConfig()
                               .SetLoadImages(true)   //control image rendering
                               .SetPrintBackground(true)
                               .SetScreenMediaType(true)
                               .SetCreateExternalLinks(true), html); //html is your html string

In less code you can get better results. It also works on IIS8 whothout any issue, what else you want :-) FYI I am not the committer of Pechkin.



来源:https://stackoverflow.com/questions/25270553/mvcrazortopdf-images-not-rendering-mvc4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!