I'm using this code to load a image via HTTP/URL.
Uri uri = new Uri("http://Abundantcode.com/image.jpg", UriKind.Absolute)
imageControl.Source = new BitmapImage(uri);
How to use string-variable instead of a directly parsed string.
You can do this:
<Image Source="{Binding ImageUri}" />
Now set ImageUri to whatever string you want.
Related
I create a file pdf from html template using Spring Boot, flying saucer, thymeleaf. But image is not displaying in my file.
Project structure:
code html:
<div class="col-xs-6 invoice-col-2">
<img src="../static/images/mastercard.png" alt="mastercard"></img>
</div>
When I change img tag to:
<img src="../static/images/mastercard.png" alt="mastercard" th:src="#{static/images/mastercard.png}"></img>
When I create PDF file, I get an error:
org.thymeleaf.exceptions.TemplateProcessingException: Link base "static/images/mastercard.png" cannot be context relative (/) or page relative unless you implement the org.thymeleaf.context.IWebContext interface (context is of class: org.thymeleaf.context.Context)
Try using Spring's classpath: prefix. This loads your file directly from the classpath, no matter if you are running from a .jar or within your IDE. Here is an example:
<img alt="mastercard" th:src="#{classpath:static/images/mastercard.png}" />
More information about classpath: can be found in the official documentation.
In order to embed an image in a PDF generated by Flying Saucer,
1) Convert the image to a base64 encoded string.
Path path = Paths.get("src/main/resources/static/images/mastercard.png");
String base64Image = convertToBase64(path);
Function to convert image stored in a path like shown above, to a base64 encoded string
private String convertToBase64(Path path) {
byte[] imageAsBytes = new byte[0];
try {
Resource resource = new UrlResource(path.toUri());
InputStream inputStream = resource.getInputStream();
imageAsBytes = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
System.out.println("\n File read Exception");
}
return Base64.getEncoder().encodeToString(imageAsBytes);
}
2) Set the base64 encoded image in the thymeleaf context
Context context = new Context();
String image = "data:image/png;base64, " + base64Image;
context.setVariable("image", image);
String html = templateEngine.process("template", context);
3) In HTML, set the value of image as shown below:
<img th:src="${image}" style="width: 200px; height=100px"/>
4) Finally, render the HTML template to PDF
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html); // html -> String created in Step 2
renderer.layout();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
renderer.createPDF(baos)
Now you have the byteArrayOutputStream of the generated PDF, with which you can choose to store them to a file server or serve it to a client in a format of your choice.
Use standard html src atribute and relative path from root of the project.
You can put your image in the root of the project and use it like this:
<img src="mastercard.png" />
If you want to resource folders you can set it like this:
<img src="src/main/resources/static/images/mastercard.png" />
I faced the same issue but reading image file from disk is little costly, I would suggest you go with uri-data
http://www.tothenew.com/blog/using-data-urls-for-embedding-images-in-flying-saucer-generated-pdfs/
Because you anyway going to read image to generate PDF, better keep it in template.
I'd like to create an application that receives formatted text (RTF) or html, renders it an show it page by page..
Is there any control that aims to do that?
I tried to use the RichEditBox control to load a file but it stucks during the operation:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"myFile.rtf");
using (var memstream = await file.OpenReadAsync())
{
MainText.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.ApplyRtfDocumentDefaults, memstream);
}
I tried to load an HTML file this way:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"myFile.htm");
var stream = await file.OpenAsync(FileAccessMode.Read);
string app;
using (StreamReader rStream = new StreamReader(stream.AsStream()))
{
app = rStream.ReadToEnd();
}
myWebView.NavigateToString(app);
But I cannot find a way to "count" the lenght of the parsed text to chunk it in pages..
There is any other way or library to do that? Any example online?
If you want to show your HTML contents in pages then you can use RichTextBlock with RichTextBlockOverflow. RTF is not supported to RichTextBlock.
how to inject RTF file to RichTextBlock in c#/xaml Windows store app
Showing Html in WinRT with RichTextBlock or other component
XAML text display sample
Can I use phantomjs to create an image of the contents of <div><iframe ..></div> (The div contains an iframe)
how do I make this image (binary data) as part of a json ? , as ({img: binary data}) ?
Is it possible to load the iframe by itself? If you can achieve that then there's no reason why you can't call var base64string = page.renderBase64(); to get a base-64 encoded string. See the API for renderBase64().
You can re-create the image later by evaluating img.src = "data:image/png;base64," + base64string;.
I want to load local html file which in the local folder to the webview, but WebView doesn't support 'ms-aspx:///' protocal, I found a solution to read the html file to stream, and then convert it to string, using NavigateToString method to load the html, it works well. But, If there's an image in the html file, the image couldn't display, anyone can help?
I have solved.
Solution:
Convert the image file to base64 string
StorageFolder appFolder = ApplicationData.Current.LocalFolder;
StorageFile file = await appFolder.GetFileAsync("SplashScreen.png");
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
var reader = new DataReader(stream.GetInputStreamAt(0));
var bytes = new byte[stream.Size];
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(bytes);
base64 = Convert.ToBase64String(bytes);
}
Use StringBuilder to create the html string
sb.Append("<html><head><title>Image test</title></head><body><p>This is a test app!</p><img src=\"data:image/png;base64,");
sb.Append(base64);
sb.Append("\" /></body></html>");
TestWebView.NavigateToString(sb.ToString());
Try using the ms-appx-web:// scheme instead of ms-aspx:// to load html from a WebView. If that doesn't work, you may need to use the ms-appdata:// scheme to access the image if it's in your application data folder.
Some further resources that might help:
How to load a local HTML-File into Webview
URI schemes
How to reference content
In My webpage i am using a image tag, the src attribute is pointing to shared network location ie (/server/images/image1.png). The exact script is "<img src="file://///server/images/image1.png". It is working fine in IE. In firefox, when I do debug using firebug its showing image, but it's not displayed in page (user view). Even it's working fine when copy this location and place it in firefox address bar. What will be the problem while using img tag also what is the solution for this? Thanks in advance.
Putting this as an answer here so as to provide help for others like myself that was searching for how to display networked images and came accross this SO post in the top 3 search engine results. It also seems like a better answer than the java servlet issuing images in the response.
FireFox would not display networked images so I created an MVC helper that extends HtmlHelper.
public static class ImageHelper
{
/// <summary>Converts a photo to a base64 string.</summary>
/// <param name="html">The extended HtmlHelper.</param>
/// <param name="fileNameandPath">File path and name.</param>
/// <returns>Returns a base64 string.</returns>
public static MvcHtmlString PhotoBase64ImgSrc(this HtmlHelper html, string fileNameandPath)
{
var byteArray = File.ReadAllBytes(fileNameandPath);
var base64 = Convert.ToBase64String(byteArray);
return MvcHtmlString.Create(String.Format("data:image/gif;base64,{0}", base64));
}
}
use in the MVC View like so:
using
<img src="#Html.PhotoBase64ImgSrc(image)" height="60px" width="60px" alt="photo" />
here the 'image' in #Html.PhotoBase64ImgSrc(image) is a pure network UNC, e.g.
//Photos/ebaebbed-92df-4867-afe8-0474ef8644eb.jpg
Create a regular HTML img element like so:
<img id="image1" runat="server" ImageUrl=<%# Eval("Value") %>/>
And in code behind do this:
image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
Where bytes is a byte[].
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileName"] != null)
{
// Read the file and convert it to Byte Array
string filePath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\";
string filename = Request.QueryString["FileName"];
string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
}
}
You are done. The image will be displayed.
The solution usually is: use a web server.
You may have to make it like so.
<img src="../server/images/image1.png" />
Once you add the "../" it is basically telling your browser to go back one directory to search for the location after the "../" .
Where is the file located and where is the location of your HTML document?
UPDATE:
I do all of my work on a Network Server as well... This should do the trick.
<img alt="" src="file:///SERVER:/FOLDER/IMAGES/image1.png" />
Thanks,
Aaron
I wrote a servlet which reads the file from LAN using Java File Stream and sets it in response and it does the trick. Thanks to all for valuable response.