WP8 - WebBrowser control to display images from resource folder - c#

I am working on WP8application, I have few images in location Resources\Graphics\ i am trying to display images from these folder, but its not picking the path.
Here is my code :
<img src=\"/Resources;component/Graphics/"+ImageName).Append("\" ") this is in my string which i am using in my WebBrowserControl.
WebBrowserControl.NavigateToString(html); // here html is a string which has all the html code in it.
But its not display the images. What is the issue here how to fix this ?

I faced a similar issue when I tried to open images that have been saved to local storage. I could solve this by putting an HTML file at the same location so that I could access the files with "./filename.ext".
It did not work with any of the resource path constructions that I used to access the local file within the webview.

The only way to achieve this is by storing in the images and the dynamically generated Html content file in the Isolated storage of the application.
Go through this link for how to store the content in Isolated storage and display it using Web browser control: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff431811(v=vs.105).aspx
Here you go,
First of all store the images,which you want to show on the Html files into the Isolated storage of the application using the following method.
public static void CopyContentToIsolatedStorage(string file)
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (iso.FileExists(file))
return;
var fullDirectory = System.IO.Path.GetDirectoryName(file);
if (!iso.DirectoryExists(fullDirectory))
iso.CreateDirectory(fullDirectory);
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(file, UriKind.Relative)).Stream)
{
// Create a stream for the new file in isolated storage.
using (IsolatedStorageFileStream output = iso.CreateFile(file))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
By calling the method as,
CopyContentToIsolatedStorage("Graphics/ImageName.png");//Pass the image folder path here
And then,form the Html dynamically like shown the below
StringBuilder HtmlString = new StringBuilder(#"<html><head><title>Test html File</title></head>");
HtmlString.Append(#"<body>");
HtmlString.Append(#"<img src=""Graphics/""#"+ ImageName + "/>");
HtmlString.Append(#"</body></html>");
And then save the Html file into Isolated Storage using the following code
var bytes = Encoding.UTF8.GetBytes(html.ToString());
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream output = iso.CreateFile("Testfile.html"))
{
output.Write(bytes, 0, bytes.Length);
}
}
Now call that html file using your browser control like below,
WebBrowserControl.Navigate(new Uri("Testfile.html", UriKind.Relative));

Related

Is there a function that takes a filename from the Image object

I'm using the Movie Maker Library Timeline SDK Control 6.0 dll
And to add a photo you need a STRING of a file name. So far everything is fine
But I want to insert a function that gets an IMAGE object
But the library does not have a function that cables an IMAGE object
What I need is to get the file name out of the IMAGE object
That is: string fileName = image
Image img = default;
using (WebClient client = new WebClient())
{
string url = textBox1.Text;
Stream stream = client.OpenRead(url);
img = Image.FromStream(stream);
axTimelineControl1.AddImageClip(trackIndex: 1, fileName :img.ToString(),
clipStartTime: axTimelineControl1.GetMediaDuration(img.ToString()), clipStopTime: 4);
}
You've got a small bit of an "XY problem" here--you're asking the wrong question. Your axTimelineControl1 expects an image's file name. This implies that it also expects there to be an image saved to disk with that file name.
But all you have is a remote image, behind some URL. client.OpenRead(url) downloads the image into a Stream, but you can't do anything with that directly.
So, you don't want to take that image, and put it into a WinForms Image object. Instead, you want to save that image to disk with a file name, and then give that file name to your axTimelineControl1.
You have a few options for doing that:
1) You could take the Stream you got from client.OpenRead(), turn it into a FileStream and save it to disk.
2) You could use the WebClient to download the image directly to disk, and then give the image's file name to the axTimelineControl1.
Let's do 2) instead. It'll save a few steps.
First, create the file.
string fileName = System.IO.Path.GetTempFileName();
System.IO.File.Create(fileName).Close();
We're creating a "Temp" file here--these are meant to be treated as disposable. Note that Windows doesn't clean them up for you, so once you're done with it, your program should delete it. System.IO.File.Create() gives us a FileStream object, but we don't need it, so we Close() it right away, so that the WebClient will be able to write to our file.
Next, we download our image, and tell WebClient to save it to our newly-created Temp file:
// Defining my own URL here. Feel free to substitute your own.
string url = "https://derpicdn.net/img/view/2018/5/18/1735426.jpeg";
using (var client = new WebClient())
{
client.DownloadFile(url, fileName);
}
Now we have an image on disk, and we can tell the Movie Maker SDK Control where to find it:
float duration = axTimelineControl1.GetMediaDuration(fileName);
axTimelineControl1.AddImageClip(
trackIndex: 1,
fileName: fileName,
clipStartTime: duration,
clipStopTime: 4);
And that should do it.
The entire code listing:
string fileName = System.IO.Path.GetTempFileName();
System.IO.File.Create(fileName).Close();
// Defining my own URL here. Feel free to substitute your own.
string url = "https://derpicdn.net/img/view/2018/5/18/1735426.jpeg";
using (var client = new WebClient())
{
client.DownloadFile(url, fileName);
}
float duration = axTimelineControl1.GetMediaDuration(fileName);
axTimelineControl1.AddImageClip(
trackIndex: 1,
fileName: fileName,
clipStartTime: duration,
clipStopTime: 4);
Don't forget to clean up your temp file!

PDF to bmp Images (12 pages = 12 images)

I have to deconstruct/extract a pdf page by page into bitmap images. This will be done on a server via a web service which I've setup. How do I get this right? It has to be page by page (1 page per image).
I am really stuck and I know one of you geniuses have the answer that I've been looking for.
I have tried: http://www.pdfsharp.net/wiki/ExportImages-sample.ashx Which didn't work correctly.
I am using C#;
The PDF is not password protected;
If this solution could take a Uri as a parameter for the location of the PDF it would be excellent!
The solution should not be reliant on Acrobat PDF Reader at all
I have been struggling for a very long time trying to use MigraDoc and PDFSharp and their alternatives to achieve the aforementioned problem.
ANY help/advice/code would be greatly appreciated!!
Thanks in advance!
LibPdf
This library converts converts PDF file to an image. Supported image formats are PNG and BMP, but you can easily add more.
Usage example:
using (FileStream file = File.OpenRead(#"..\path\to\pdf\file.pdf")) // in file
{
var bytes = new byte[file.Length];
file.Read(bytes, 0, bytes.Length);
using (var pdf = new LibPdf(bytes))
{
byte[] pngBytes = pdf.GetImage(0,ImageType.BMP); // image type
using (var outFile = File.Create(#"..\path\to\pdf\file.bmp")) // out file
{
outFile.Write(pngBytes, 0, pngBytes.Length);
}
}
}
Or Bytescout PDF Renderer SDK
using System;
using Bytescout.PDFRenderer;
namespace PDF2BMP
{
class Program
{
static void Main(string[] args)
{
// Create an instance of Bytescout.PDFRenderer.RasterRenderer object and register it.
RasterRenderer renderer = new RasterRenderer();
renderer.RegistrationName = "demo";
renderer.RegistrationKey = "demo";
// Load PDF document.
renderer.LoadDocumentFromFile("multipage.pdf");
for (int i = 0; i < renderer.GetPageCount(); i++)
{
// Render first page of the document to BMP image file.
renderer.RenderPageToFile(i, RasterOutputFormat.BMP, "image" + i + ".bmp");
}
// Open the first output file in default image viewer.
System.Diagnostics.Process.Start("image0.bmp");
}
}
}

Create an Excel file on server and send to a browser

I'm using EPPlus to create an excel file on the server. The problem is that I wan't the file to be saved on the clients harddrive and when I the application up on a server I believe this will save the file on the server harddrive.
Is it possible to send this file back to the client/browser some how?
public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear)
{
List<Calculation> newList = new List<Calculation>();
newList.Add(cList.First()); //Getting the values for the first row
var StartValue = newList[0].StartValue;
var radio = form["advanceOrArrears"];
string fileName = newList[0].CalculationName;
string path = #"C:\ExcelFiles\" + fileName + ".xlsx"; //Path for the file
FileInfo info = new FileInfo(path);
info.Directory.Create(); //If C:\ExcelFiles does not exist, create it
if (!info.Exists)
{
using (ExcelPackage package = new ExcelPackage(info))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
//Styles for the sheet
package.Save();
}
}
}
The easiest way would be to send the bytes as File to browser. If your library for creating Excel files allows you to save to stream (like for example ClosedXML does) then you can do in your MVC action
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "file.xlsx");
If you can't save it to memory stream then save it to server's disc and then you can just pass file path and content type to return File().
I've used a httphandler for sending the byte file object to the browser.
This link should help, Generating a file, then launching a secure download
So save the file on the server then transmit it to the user in your controller:
return new FilePathResult(myFilePath,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Database file cannot be found

In my Windows Phone 8 C#/XAML .NET 4.5 project I'm using (with the help of LINQ-2-SQL) a local database (SQLite probably) created by another member of the team.
But when I run the application, it throws an exception:
The database file cannot be found. Check the path to the database. [ Data Source = C:\Data\Users\DefApps\AppData\{XXXXX-XXXXX-XXXXXX-XXXXX}\Local\database.sdf ]
The .sdf file with the database is in the project in /Database/database.sdf and the properties are set to Build action: Embedded resource & Copy to output directory: Copy always.
In the databaseContext.cs, which is a class used as context (not sure I'm naming it right, I'm new to linq-2-sql), the connection string is defined as:
Data Source=isostore:/database.sdf
Is this the right settings? What can I do to make it work?
You will have to move the database to isolated storage first. Heres how you could do it.
public static void MoveReferenceDatabase()
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri("DutchMe.sdf", UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile("DutchMe.sdf"))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
Else
set the connection string to Data Source=appdata:/database.sdf . I am not very sure about the second solution.

How to save a Text/document file to specific folder using MemoryStream in asp.net using c#?

I have a file path from Sharepoint Document Library. The FileStrem contains the stream bytes of file from server. Now i want to Save file from these bytes using MemoryStream to specific folder using C# in asp.net.
public byte[] FileStream { get; set; }
Below code i am using to save the Image File from sharepoint. It works!
MemoryStream mStream = new MemoryStream(analystPhotoObj.FileStream);
Bitmap bitmap = new Bitmap(mStream);
bitmap.Save(path + #"\MemberPhoto\" + analystPhotoObj.DocumentID + "." + analystPhotoObj.FileType);
Now the same thing i want to do for saving the text/document file.Only the thing is the FILE TYPE is being changed from *BITMA*P to TEXT/DOCUMENT file
Help appreciated!
Thanks!
Try using the second param of bitmap.Save:
Save(Stream, System.Drawing.Imaging.ImageFormat.Bmp)

Categories