Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save FileSteam as PDF file

I am using a third party tool to get the scanned content from the scanner. On button click it executes the code and gives the content as a FileStream. Now I need to save this FileStream content as a pdf file in to a specified folder.

After saving I need to open the file in browser. How can I save the FileStream as a PDF file?

like image 640
ANP Avatar asked Oct 11 '22 10:10

ANP


1 Answers

You can write the stream directly to the output buffer of the response.

So if you're at the point in your code where you have the filestream from the scanner. Simply read bytes from the scanner filestream and write them to the Response.OutputStream

Set the contentType to application/pdf

Make sure you return nothing else. The users browser will do whatever it is configured to do now, either save to disk or show in the browser. You can also save to disk on the server at this point as well in case you wanted a backup.

I'm assuming your file stream is already a pdf, otherwise you'll need to use something like itextsharp to create the pdf.

Edit Here's some rough and ready code to do it. You'll want to tidy this up, like adding exception trapping to make sure the file stream gets cleaned up properly.

    public void SaveToOutput(Stream dataStream)
    {
        dataStream.Seek(0, SeekOrigin.Begin);
        FileStream fileout = File.Create("somepath/file.pdf");

        const int chunk = 512;
        byte[] buffer = new byte[512];

        int bytesread = dataStream.Read(buffer,0,chunk);

        while (bytesread == chunk)
        {
            HttpContext.Current.Response.OutputStream.Write(buffer, 0, chunk);
            fileout.Write(buffer, 0, chunk);
            bytesread = dataStream.Read(buffer, 0, chunk);
        }

        HttpContext.Current.Response.OutputStream.Write(buffer, 0, bytesread);
        fileout.Write(buffer, 0, bytesread);
        fileout.Close();

        HttpContext.Current.Response.ContentType = "application/pdf";
    }

Simon

like image 200
Simon Halsey Avatar answered Nov 06 '22 21:11

Simon Halsey