-->

Images in Html to PDF using wkhtmltopdf in mvc 4

2019-07-15 12:58发布

问题:

I am using wkhtmltopdf to convert html to pdf. I am using mvc 4. I was able to convert html to pdf. The only problem I have is that images do not render. There is small rectangle where image should appear. I have my images in database so when I get html string in my controller this is how image is shown right before I pass this string to converter:

<img src="/Images/Image/GetImageThumbnail?idImage=300" alt=""/>

So I am thinking that this approach is not working becuase I pass string to converter so image cannot be rendered. Any ideas how to solve this problem if images are in db?

回答1:

I solve a similar issue by replacing src from src="/img/derp.png" to src="http://localhost/img/derp.png". I get the host part from the request that my Controller receives.

// Here I'm actually processing with HtmlAgilityPack but you get the idea
string host = request.Headers["host"];
string src = node.Attributes["src"].Value;
node.Attributes["src"].Value = "http://" + host + src;

This means that the server must be also be able to vomit images directly from URLs like that.

I guess it could be done with string.Replace as well if your HTML is in a string

string host = request.Headers["host"];
html = html.Replace("src=\"/", "src=\"http://"+host+"/"); // not tested