Convert PDF to Stream from URL

I have a PDF, which is located at say http://test.com/mypdf.pdf .

How to convert PDF to Stream , and then use this Stream convert it to PDF.

I tried the following but got an exception (see image):

 private static Stream ConvertToStream(string fileUrl) { HttpWebResponse aResponse = null; try { HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(fileUrl); aResponse = (HttpWebResponse)aRequest.GetResponse(); } catch (Exception ex) { } return aResponse.GetResponseStream(); } 

enter image description here

+4
source share
2 answers

This will work:

 private static Stream ConvertToStream(string fileUrl) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { MemoryStream mem = new MemoryStream(); Stream stream = response.GetResponseStream(); stream.CopyTo(mem,4096); return mem; } finally { response.Close(); } } 

However, you are solely responsible for the lifetime of the returned memory stream.

The best approach:

 private static void ConvertToStream(string fileUrl, Stream stream) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { Stream response_stream = response.GetResponseStream(); response_stream.CopyTo(stream,4096); } finally { response.Close(); } } 

Then you can do something like:

 using (MemoryStream mem = new MemoryStream()) { ConvertToStream('http://www.example.com/',mem); mem.Seek(0,SeekOrigin.Begin); ... Do something else ... } 

You can also return the response stream directly, but you will need to check its lifetime, having released the answer, it can free the stream, and, therefore, a copy of mem.

+5
source

You can look at WebClient.DownloadFile .

You give it the url and name of the local file, and it saves the file directly to disk. Could save you a step or two.

You can also try WebClient.DownloadData , which saves the file in the byte[] internal memory.

EDIT

You did not specify the web service protocol to which you upload the file. The simplest (RESTful) form would be to simply send the file to the data to another URL. Here's how you do it.

 using (WebClient wc = new WebClient()) { // copy data to byte[] byte[] data = wc.DownloadData("http://somesite.com/your.pdf"); // POST data to another URL wc.Headers.Add("Content-Type","application/pdf"); wc.UploadData("http://anothersite.com/your.pdf", data); } 

If you use SOAP, you will have to convert the file to a Base64 string, but hopefully you are using a generated client that will take care of this for you. If you could elaborate on the type of web service you are sending the file to, I could perhaps provide additional information.

+5
source

Source: https://habr.com/ru/post/1443422/


All Articles