Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using http response how to save the pdf files

Tags:

c#

I've written following code to get the content from a web page and save to the system. if the webpage is in html format i'm able to save it. if the web page is in pdf format i'm unable to save it. After saving if i opend the file blank pages are coming.

I want to know How to save the pdf files from the response.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
webContent = reader.ReadToEnd();
StreamWriter sw = new StreamWriter(FileName);
sw.WriteLine(webContent);
sw.Close();

Please help me ASAP.

like image 821
Vishnu Avatar asked Jan 28 '11 05:01

Vishnu


People also ask

How can I save data in PDF?

If the file is unsaved, select File > Save As. Select Browse to choose the location on your computer where you want to save the file. In the drop-down list, select PDF. Select Save.

Can we download PDF from Link?

Just open the link of the PDF in a browser, then click the three-dot icon and select Download.


2 Answers

StreamReader.ReadToEnd() returns a string. PDF files are binary, and contain data that is not string-friendly. You need to read it into a byte array, and write the byte array to disk. Even better, use a smaller byte array as a buffer and read in small chunks.

You can also simplify the whole thing by just using webclient:

using (var wc = new System.Net.WebClient())
{
    wc.DownloadFile(Url, FileName);
}
like image 56
Joel Coehoorn Avatar answered Oct 04 '22 23:10

Joel Coehoorn


HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
WebResponse response = request.GetResponse();

using (Stream stream = response.GetResponseStream())
using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
    stream.BlockCopy(fs);
}

...
public static class StreamHelper
{
    public static void Copy(Stream source, Stream target, int blockSize)
    {
        int read;
        byte[] buffer = new byte[blockSize];
        while ((read = source.Read(buffer, 0, blockSize)) > 0)
        {
            target.Write(buffer, 0, read);
        }
    }
    public static void BlockCopy(this Stream source, Stream target, int blockSize = 65536)
    {
        Copy(source, target, blockSize);
    }
}
like image 30
Artur Mustafin Avatar answered Oct 04 '22 22:10

Artur Mustafin