MvcRazorToPdf - images not rendering, MVC4

3k views Asked by At

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.

2

There are 2 answers

0
Tonigno On

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!

0
tom On

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.