webservice to return pdf with asp.net - c#

I have a html to pdf conversion tool which resides on our server that I can access using a url with querystrings.
Something like myurl.com/createpdf.aspx?page=http://www.somesite.com.
The tool then converts the web page and displays it as a pdf.
I would like to offer this functionality as a web service, so that our clients can access this programmatically.
Ideal case would be, that our clients send in the site they would like to have converted and the web service then returns the pdf.
Would that make sense?
What would be the best way to implement this?
cheers,
Terry

Use file IO to read the PDF in and have your webmethod return it as a byte[] array. For example like this:byte[] filebytes = null;
using (FileStream fs = File.OpenRead(fileName))
{
filebytes = new byte[fs.Length];
fs.Read(filebytes, (int)0, (int)fs.Length);
}
return filebytes;
It will be Base64 encoded and you will then be able to Save and view the file on the client.

You could also write an http-handler that returns the pdf with the appropriate mime type. This way you would not have all the processing overhead of an aspx page.

Related

How I can save *.docx file in sql server and show it

I have some problem. I'am try to save *.docx fail in sql server and show it in web-site. I can save my file in sql server using this code
Byte[] bytes = File.ReadAllBytes(varFilePath);
String file = Convert.ToBase64String(bytes);
using (SqlConnection sql_connetion = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_connection"].ConnectionString))
{
sql_connetion.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO use_of_rule (ID, taj) Values('3', #File)", sql_connetion))
{
sqlWrite.Parameters.Add("#File", bytes);
sqlWrite.ExecuteNonQuery();
return "ok";
}
}
I want to display the content of the file in the web browser. How I can do it?
If you are using Word from WAS (Office Web App Server), you need to do something like this:
1 Create a simple web site to read the data from sql.
You could create a Generic Handler (ashx) in ASP.Net site, providing the plain word file data as response. Dont forget to set the content type as "application/vnd.openxmlformats-officedocument.wordprocessingml.document".
2 Use url encoding to encode the link created in step 1, including all parameters you may want to pass into it.
3 To launch Word, you need to nav it to http(s)://your.was.server.name/op/view.aspx?src=paste.encoded.url.here

System.Text.Encoding.Default.GetBytes fails

Here is my sample code:
CodeSnippet 1: This code executes in my file repository server and returns the file as encoded string using the WCF Service:
byte[] fileBytes = new byte[0];
using (FileStream stream = System.IO.File.OpenRead(#"D:\PDFFiles\Sample1.pdf"))
{
fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
}
string retVal = System.Text.Encoding.Default.GetString(fileBytes); // fileBytes size is 209050
Code Snippet 2:
Client box, which demanded the PDF file, receives the encoded string and converts to PDF and save to local.
byte[] encodedBytes = System.Text.Encoding.Default.GetBytes(retVal); /// GETTING corrupted here
string pdfPath = #"C:\DemoPDF\Sample2.pdf";
using (FileStream fileStream = new FileStream(pdfPath, FileMode.Create)) //encodedBytes is 327279
{
fileStream.Write(encodedBytes, 0, encodedBytes.Length);
fileStream.Close();
}
Above code working absolutely fine Framework 4.5 , 4.6.1
When I use the same code in Asp.Net Core 2.0, it fails to convert to Byte Array properly. I am not getting any runtime error but, the final PDF is not able to open after it is created. Throws error as pdf file is corrupted.
I tried with Encoding.Unicode and Encoding.UTF-8 also. But getting same error for final PDF.
Also, I have noticed that when I use Encoding.Unicode, atleast the Original Byte Array and Result byte array size are same. But other encoding types are mismatching with bytes size also.
So, the question is, System.Text.Encoding.Default.GetBytes broken in .NET Core 2.0 ?
I have edited my question for better understanding.
Sample1.pdf exists on a different server and communicate using WCF to transmit the data to Client which stores the file encoded stream and converts as Sample2.pdf
Hopefully my question makes some sense now.
1: the number of times you should ever use Encoding.Default is essentially zero; there may be a hypothetical case, but if there is one: it is elusive
2: PDF files are not text, so trying to use an Encoding on them is just... wrong; you aren't "GETTING corrupted here" - it just isn't text.
You may wish to see Extracting text from PDFs in C# or Reading text from PDF in .NET
If you simply wish to copy the content without parsing it: File.Copy or Stream.CopyTo are good options.

How to pass a URI image path to FileInfo class?

I have the below program that converts an image to byte array
public byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
If I pass the value as "D:\\ENSource\\1.png", it works properly.
But If I send the value as "http://i.stack.imgur.com/PShuQ.png" it throws exception
URI formats are not supported
How can I achieve this?
FileInfo and FileStream work with local files, there is no way to "pass Uri" to either of them.
To handle Uri you can either:
map server to local drive (i.e. if server supports WebDAV).
use Http related classes (like HttpClient, WebClient) to download file from server and get bytes. I.e. Image to byte array from a url.
Edit!
Please see #Alexei's response.
He tossed in a much better (read: simpler) solution that uses webclient.
I'm leaving the response here in case someone wants to see a more "verbose" example of querying a web server.
I just gave Alexei an up tick (he's quite right), but just to fill this in . . .
Your communicating with a web server, not a file system.
As a result, you will need to "request" the data from the server manually, and then pass the resulting stream.
Please see the following code snippet . . .
http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Download-Image-from-URL.html

How to save byte[] as wav file in silverlight application?

In my MVC Application I added a Silverlight Audio Recorder. This recorder record audio using System.Windows.Media; namespace as byte[] that represents an wav file.
Now I need to save this byte[] as .wav file on local disk (server).
So far I've tried the following:
byte[] audioData; // Here I contain my data
System.IO.File.WriteAllBytes(#"C:\Temp\yourfile.wav", this.audioData); // Doesn't work
BinaryWriter Writer = null;
string name = #"C:\Temp\yourfile.wav";
try
{
Writer = new BinaryWriter(File.OpenWrite(name));
Writer.Write(this.audioData);
Writer.Flush();
Writer.Close();
}
catch
{
...
}
But nothing work for me... What I did wrong?
Ok. Let's say I can send my data as json string to the controller:
WebClient net = new WebClient();
string data = UTF8Encoding.UTF8.GetString(this.audioData, 0, this.audioData.Length);
net.UploadStringAsync(new Uri("/Home/SaveFile", UriKind.Relative), data);
How would I get this data in MVC Action?
Silverlight is running client side, your MVC code is server-side, so this won't work in it's current guise.
I'd recommend using a web service to send the data back to your server to save it.
Take a look at using WCF or maybe WebAPI to get up and running with it.
If you really wanted to do get intricate, you could also use something like SignalR to have the client / server (which is essentially what this set up is) send communicate with each other and send the data back through that. Though it seems a little overkill for this.

How do you programatically call an ashx file from dot.net?

I have been provided with an ashx "service" that returns an image. I'm new to ashx files - so don't know how to handle it.
I need to stream the image into a byte[] so I can copy it somewhere else. How do I do that?
You can use WebClient.DownloadData pointing to asxh.
So let me give you a sample. Let's say you have image located on asp.net page, like this:
<img src="http://someServer/someSite/MyHandler.ashx?id=myId"/>
In this case you can use following code:
using (System.Net.WebClient wclient = new System.Net.WebClient())
{
byte[] data = wclient.DownloadData(
"http://someServer/someSite/MyHandler.ashx?id=myId");
}
Alternatively you can use WebRequest

Categories