Images in Html to PDF using wkhtmltopdf in mvc 4 - asp.net-mvc-4

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?

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

Related

How to upload an image on Pentaho dashboard ? ( variable, condition, local path)

I want to display an image depending on parameter called "ca_code" on dashboard.
All the images are in a repository of my current theme ( I know that you can also upload images to server, must be easiler but I need to keep this), here's an example of an image path:
D:\pentaho\pentaho-8-2\pentaho-server\pentaho-solutions\system\common-ui\resources\themes\sapphire\img_project\CA120.jpg
Here, 120 is a ca_code. I get this ca_code as variable by query component.
Here's what I tried on Post Fetch of query component:
function f(ca_code) {
var ca_code=ca_code.resultset;
var img = '<img src="../common-ui/resources/themes/sapphire/img_project/CA'+ca_code.resultset+'.jpg/content"/>';
var img_default='<img src="../common-ui/resources/themes/sapphire/img_project/CA000.jpg/content"/>';
document.getElementById('ca_logo').innerHTML=img;
}
And it doesn't work, think it is the path prob.
When I used HTML on Layout Panel, the path was fine, the image was displayed but I can't do on HTML because I need variable ca_code, I want to do it on Query Component - Post Fetch.
And also, how to check if the image exists ? If it doesn't exist, I want to display img_default.
Any help would be nice !

Is it possible to save a base64 string as an image in a image file using only PhantomJS?

I'm trying to capture a particular element on a web page using PhantomJS. Using getBoundingClientRect(), I'm able to clip Off the unnecessary elements(for which the entire page gets rendered and then clipped). Now I'm to trying to focus and capture a particular canvas component and store it in an image file. Once base64 string is obtained, how do I save base64 string as an image in an image file without the aid of any utility like casperjs? The below code doesn't work for me.
img = chart1.canvas.toDataURL();
ext = img.split(';')[0].match(/jpeg|png|gif/)[0];
data = img.replace(/^data:image\/\w+;base64,/, "");
fs.write('myChart.png', data, 'w');

HtmlUnit - lazy loading of images

I am using HtmlUnit to download URL and the webpage is using lazy loading (I think) to load some of the images. Which settings should I use in HtmlUnit so that I can get those images.
For example, this is one of the URLs I am trying to download-
http://www.ebay.com.au/sch/i.html?_from=R40&_trksid=p2050601.m570.l1313.TR10.TRC0.A0.H0.Xiphone6s.TRS0&_nkw=iphone6s&_sacat=0
The product images (after first few) have dummy src value-
As you can see the src tag has dummy value and actual image url is stored in imgurl attribute. I think the webpage uses some javascript to change the src attribute by correct value once we scroll down.
This is my sample code-
webClient = new WebClient(BrowserVersion.FIREFOX_38);
webClient.getOptions().setActiveXNative(false);
webClient.getOptions().setAppletEnabled(false);
webClient.getOptions().setDoNotTrackEnabled(true);
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.setCssErrorHandler(new SilentCssErrorHandler());
Page page = webClient.getPage(url);
I have tried the following-
1) Increase window height-
webClient.getCurrentWindow().setInnerHeight(60000);
webClient.getCurrentWindow().setInnerWidth(60000);
2) Try to scroll down after page is downloaded
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(true);
webClient.waitForBackgroundJavaScript(10 * 1000);
HtmlPage page = (HtmlPage) webClient.getPage(url);
page.getBody().type(KeyboardEvent.DOM_VK_PAGE_DOWN);
Thread.sleep(3000);
String html = page.asXml();
But so far, I have not been able to get the correct src URL.
If anyone has successfully fixed this lazy loading issue, please suggest some workarounds.
thank you!

Docx4j v3 Docx to HTML with Images

I'm working to convert a docx to html using Docx4j version 3.
The document contains white space consisting of tabs, spaces and newlines. The resulting HTML either has unrecognized characters or does not preserve whitespace at all.
The java code I'm using is:
WordprocessingMLPackage wordMLPackage = Docx4J.load(is);
HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
htmlSettings.setImageDirPath( System.getProperty("user.dir") + uploadedImagesDirectory );
htmlSettings.setWmlPackage(wordMLPackage);
Docx4J.toHTML(htmlSettings, out, Docx4J.FLAG_EXPORT_PREFER_XSL);
String result = ((ByteArrayOutputStream)out).toString();
How can I preserve the whitespace in the document. Also, is there a method to apply css to a particular node? Specifically, I have 3 images which should be evenly spaced horizontally on the page.
I've looked over the documentation and searched online with no success.
Thank you.
I resolved the issue and it was not related to Docx4j.
Docx4j parsed the document perfectly! The problem was related to sending the output in an email.
I set the Spring helper javamail mime encoding to resolve this issue:
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");

Trying to display an image in a razor view being converted to HTML in winform app

I'm using the Razor View Engine to Generate HTML outside of a MVC app (In a win forms)
Most of my Razor Views work pretty logically, but I'm having issues displaying an image.
I'm trying to display a PNG image that's been retrieved from a database. Since I'm in a winforms app a lot of the helper functions I'd normally use are absent, so I'm trying to do it inline.
string base64 = Convert.ToBase64String( #Context.Model.ETA640StudentProfileVM[ currentRecord ].ImageObj );
imageBytes);
<img src="#String.Format( "data:image/png;base64,{0}", base64 )" />
But when I evaluate this code to display the image using the code above, which I got here:
StackOverflow Article
I get this error out of the Razor Renderer
Line: 305\t Col: 1\t Error: The name 'WriteAttribute' does not exist in the current context
called like this:
return RenderTemplate(sourceCodeReader, referencedAssemblies, context, null);
The Razor engine is what is throwing the error... All my other HTML works fine so far...
Here is the code the Razor View Engine is outputting for the statement (from the error text)
WriteLiteral(" <img");
WriteAttribute("src", Tuple.Create(" src=\"", 6855),
Tuple.Create("\"", 6915) , Tuple.Create(Tuple.Create("", 6861),
Tuple.Create<System.Object, System.Int32>(String.Format(
#"data:image/png;base64,{0}", base64 ) , 6861), false) );
WriteLiteral(" />\r\n");
As you can see, the WriteAttribute is inside the Quotes for the WriteLiteral statement...
This seems pretty evidently incorrect.
Anyone got any idea why that pair of lines causes the Razor engine to Puke?
Has anyone used the Razor engine to generate HTML to display a PNG frim the Database and had it work outside of an MVC app?
(P.S. I had another question that approached this same error from a much worse perspective, that question has been deleted)
Edit: For those who follow, the issue appears to be directly related to parsing a variable in the path of an image tag.. for example this works perfectly.
<img src="D:\Project Files\EFolderReportGenerator3G\WinForm\EFolderReportGenerator3G\bin\Debug\Tmp.png" border="0" height="155" />
But this dies horribly (both double slashing and using the #"" string literal way of dealing with the '\' chaaracters)
#string path = "D:\\Project Files\\EFolderReportGenerator3G\\WinForm\\EFolderReportGenerator3G\\bin\\Debug\\Tmp.png";
<img src="#path" border="0" height="155" />
Now I'm trying to solve the relative path issue so my solution is portable.
The code:
<img src="#String.Format( "data:image/png;base64,{0}", base64 )" />
Isn't being parsed correctly by StackOverflow because of the quotes for the src attribute and the Format method argument aren't obvious, I'm not sure if the Razor engine can follow either. Maybe you could try moving the string format to an assignment and reference that variable instead of calling the method inline like that. It might at least reveal more about the problem.