HtmlTextWriter - Filepaths containing spaces - c#

I'm trying to use HtmlTextWriter to create a html page which is all working fine until I try to create images into a folder that contains spaces in its file path
C:\Documents and Settings....
What seems to be happening is
m_htmlWriter.AddAttribute(HtmlTextWriterAttribute.Src, imageName);
is converting spaces into %20 which as a result, the file path for the source becomes invalid and results in my webbrowser and installed internet browsers not being able to display said images, and instead displaying the broken image icon/image..
I've tried multiple different things to get this to work including
Uri.UnescapeDataString, including an # symbol infront of the imageName
I've also found that if i copy the link from the page source (C:\Documents%20and%20Settings\... then windows is unable to find the file(expected this)
I'm unable to use HtmlAgilityPack due to restrictions I am under.. Anyone have any ideas?

Just add a boolean parameter to tell the HtmlTextWriter class that you don't want it encoded: -
m_htmlWriter.AddAttribute(HtmlTextWriterAttribute.Src, imageName, false);
There are two similar methods available:
AddAttribute(HtmlTextWriterAttribute, String)
AddAttribute(HtmlTextWriterAttribute, String, Boolean)
Using the second one should fix the problem.

Related

Link to an external file in iTextSharp

I want to provide links to files uploaded on the server in iTextSharp documents.
The problem I'm facing is the string containing my file path is getting mangled en-route from my code onto the page.
Let's say the full path for the file, I'm trying to link is "C:\site uploads\some_file.txt".
I'm trying to create the link using the "Anchor" object, like so:
string path = "C:\site uploads\some_file.txt";
string name = "some_file.txt";
Anchor anchor = new Anchor(name, new Font(Font.FontFamily.UNDEFINED, 12));
anchor.Reference = path;
pdfDoc.Add(anchor);
ASP.NET C# will double up those backslashes in "path", as it does, but iTextSharp will further alter the string to something like C%5%20site%HCuploads%20some%34file.txt, which does not work as a clickable link in my document. FYI, I know I didn't get my % codes just right; those are offered for example only.
I'm not trying to launch any external applications from my document, I just want to enable the user to download this file. Any advice would be appreciated.
Why do you link to a local file? If someone else downloads that PDF on their machine, it won't have that directory.
The backslashes and colon are escaped.
Use https:// links. If you do want to link to local files, use a file:// link.

C# Reporting Error in Processing 'Illegal Path'

I am trying to get reporting in C# to work. I'm trying to embed my rdlc file as such:
var reportDataSource = new ReportDataSource("ProspectsDataSet", _allProspects);
ReportViewer.LocalReport.DataSources.Add(reportDataSource);
ReportViewer.LocalReport.ReportEmbeddedResource = "SdcDatabase.Modules.EnquiryModule.View.Reports.ProspectsReport.rdlc";
ReportViewer.ZoomMode = ZoomMode.PageWidth;
ReportViewer.RefreshReport();
The build action on the rdlc file itself is set to embedded resource and the copy to output directory set to copy always.
I have double checked and I'm certain that that is the correct namespace in the ReportEmbeddedResource string. However when I try to load the report I get this error:
I have tried switching a few things around in the path, such as replacing '.' with '/' and '\' but so far I have not been able to get anything to fix this. I have also tried using LocalPath instead of EmbeddedResource but again I come across errors.
I have searched for this issue but haven't found anything to resolve my issue thus far.
I have a reporting wrapper class that works well for my apps. I have a property to hold the name of the ".rdlc" report definition I want to run. Then, when I call my "RunReport()" method, I assign the report based on reading a stream from my application assembly resource. A short version for what you have might be
ReportViewer.LocalReport.LoadReportDefinition( GetRDLCStream( "ProspectsReport.rdlc" ));
Then, lower, I have a method
private Stream GetRDLCStream( string rptRDLC)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
"SdcDatabase.Modules.EnquiryModule.View.Reports." + rptRDLC);
return stream;
}
Obviously, I am not positive of the naming convention of your path to your project but am implying the above path. However, it should reflect (for example)
"NameOfYourApp.SubFolderWithinPath.MaybeReportsSubFolder." + actualReport.RDLC name
This way, I never have to worry about copying out a resource and hoping the paths work. I know it is embedded and where within the assembly.

WPF WebBrowser - built-in search dialog doesn't work if content was loaded with NavigateToString

I use WebBrowser to display generated XML. My XML string loaded into browser by call to NavigateToString:
var text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ Environment.NewLine
+ "<whatever/>";
Browser.NavigateToString(text);
After browser loads string content I'm trying to search for any displayed text using standard Ctrl+F search dialog - but it always shows warning "No matches found".
If I save the XML string to a file and use Browser.Navigate(filename) it works.
Any ideas?
When you navigate to a file, the WebBrowser control performs MIME-type sniffing (often using the file extension as a hint). Then it creates an Active Document object of the corresponding type. Most often it's an instance of MSHTML Document, but can also be an XML, PDF or Word document, all of which support Active Document interfaces.
Now, when you navigate to a string with NavigateToString, the WebBrowser doesn't make any attempts to recognize the document type, and simply creates and instance of MSHTML Document (rather than XML Document), then tries to parse the content as HTML and fails.
I don't think you can get the desired behavior using NavigateToString, and I believe the same applies to NavigateToStream. To illustrate what's going on, take your XML content and save it as filename.html, filename.txt and filename.xml. Try opening each file with IE.
On a side note, when you navigate to a URL, the server actually has an option to suggest the MIME type, using HTTP headers. The browser may or may not tolerate such suggestion (it will still perform some validation checks).
The bottom line: you will not be able to render XML with NavigateToString or NavigateToStream. You're going to have to convert it to HTML first (e.g., with an XSLT transform).
I just had the same problem.
There is even the possibility to open the xml file directly using the overload:
webbrowser.Navigate(string filepathToXML)
Going this way, the builtin search panel works like a charm.

Save Image to word of HTML reference

I export data from my database to word in HTML format from my web application, which works fine for me , i have inserted image into record,
the document displays the image also , all works fine for me except when i save that file and send to someone else .. ms word will not find link to that image
Is there anyway to save that image on the document so path issues will not raise
Here is my code : StrTitle contains all the HTML including Image links as well
string strBody = "<html>" +
"<body>" + strTitle +
"</body>" +
"</html>";
string fileName = "Policies.doc";
//object missing = System.Reflection.Missing.Value;
// You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
You can create your html img tag with the image data encoded with base64. This way the image data is contained in the html document it self.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
You images are probably only available via filesystem (i.e. their src starts with file).
There are a few ways
Make the image available via the internet: make sure their src starts with http and that they are hosted on a web server visible to the downloader (for example, the same server from which they are dowonloading the image)
Use a library, for example see NuGet
You can inline the images as #DevZer0 suggests.
Based on experience
Is the simplest to implement but has some annoyances (the server needs to be available to the user)
Is probably the best way if you do a lot of Word or Office files manipulation.
Can be done and it would solve the problem, although you wouldn't have a full library to support further use cases.
Use a word document creation library if you really want to have flexibility in creating doc or docx type files. Like all other popular document formats, the structure needs to be accurate enough for the program that opens up the documents. Like you obviously cannot create a PDF file just by setting content type "application/PDF", if your content is not in a structure that PDF reader expects. Content type would just make the browser identify the extension (incorrectly in this case) and download it as a PDF, but its actually simple text. Same goes for MS word or any other format that requires a particular document structure to be parsed and displyed properly.
Since every picture, table is of type shape in Word/Excel/Powerpoint, you could simply add with your program an AlternativeText to your picture, which would actually save a URL of the download URL and when you open, it will retrieve its URL and replace it.
foreach (NetOffice.WordApi.InlineShape s in docWord.InlineShapes)
{
if (s.Type==NetOffice.WordApi.Enums.WdInlineShapeType.wdInlineShapePicture && s.AlternativeText.Contains("|"))
{
s.AlternativeText=<your website URL to download the picture>;
}
}
This would be the C# approach, but would require more time for the picture. If you write a small software for it, which replaces all pictures which contain a s.AlternativeText, you could replace a lot of pictures at same time.
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(s.AlternativeText, false, true);
It will look for the picture at that location.
You can do that for your whole document with the 1 loop I wrote you. Means, if it is a picture and contains some AlternativeText, then inside you loop you use the AddPicture function.
Edit: Anoter solution, would be to set a hyperlink to your picture, which would actually go to a FTP server where the picture is located and when you click on the picture, it will open it, means he can replace it by himself(bad, if you have 200 pictures in your document)
Edit according Clipboard:
string html = Clipboard.GetText(TextDataFormat.Html);
File.WriteAllText(temporaryFilePath, html);
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(temporaryFilePath, false, true);
The Clipboard in Word is capable to transform a given HTML and when you paste it to transform that table or picture into Word. This works too for Excel, but doesn't for Powerpoint. You could do something like that for your pictures and drag and drop from your database.

C# WebBrowser Navigate to File Path fails (file exists)

I have a web browser in C# that I want to make navigate to a path (html file) on my local pc.
I tried using this:
if (File.Exists(Path + b.HTML))
{
browserCom1.Navigate(Path + b.HTML);
}
The file Exists, but the browser is keep opening an error of Internet Explorer: "cannot find file:///(my path here)"
It is weird because the file is correct. for example if I use:
System.Windows.Forms.OpenFileDialog browseFile = new
System.Windows.Forms.OpenFileDialog();
browseFile.ShowDialog();
String path = browseFile.FileName;
browserCom1.Navigate(path);
and I select the same file that it tried navigating to before, it works.
If I print the above brwseFile File Name to Console(which is the same as my Path+b.HTML by the way), and copy-paste it into the Navigate(...) Function (changing each '\' to '//') it Doesn't work.
I have no Idea what to do.
I tried something else like:
String path=(File.Open(Path + b.HTML, FileMode.Open).Name);
browserCom1.Navigate(path);
but the application keep getting freezed upon this.
I also tried with new URI(path) and all.
How can I simpley navigate to a HTML file on my computer?
You have http slashes, but should have file system slashes, like c:\something\something.html
I had the same problem. Resolved when I cleaned for double \\ in the code.
If that's not your problem - your problem may be some else problem related to parsing from string to uri.
my path was like this: c:\users\someone1\\myFolder\protocol.htm

Categories