Search code examples
c#asp.netpdfstreamhttppostedfile

How to use file in file system for HttpPostedFile


I have the following code for creating PDF Thumbnails, but this code only works for input files with HttpPostedFile. But my files are in the file system an I don't know how to handle them without HttpPostedFile. How can I create thumbnails of files in the file system?

This is the code:

<%@ Page language="c#" %> 
<%@ Register TagPrefix="tc" Assembly="TallComponents.PDFThumbnail" Namespace="TallComponents.Web.PDF" %> 
<script runat="server"> 
    protected void DisplayThumbs_Click(object sender, System.EventArgs e) 
    { 
        thumbnails.Controls.Clear(); 
        HttpPostedFile postedFile = Request.Files[ "pdf" ]; 
        if ( null != postedFile ) 
        { 
            byte[] buffer = new byte[ postedFile.ContentLength ]; 
            postedFile.InputStream.Read( buffer, 0, buffer.Length ); 
            string unique = Guid.NewGuid().ToString(); 
            Session[ unique ] = buffer;      

            int n = Thumbnail.GetPageCount( postedFile.InputStream ); 

            for ( int i=1; i<=n; i++ ) 
            { 
                Thumbnail thumbnail = new Thumbnail(); 
                thumbnail.SessionKey = unique; 
                thumbnail.Index = i; 
                thumbnails.Controls.Add( thumbnail ); 
            } 
        } 
    } 
</script> 
<HTML>
    <body> 
        <form id="Form1" method="post" runat="server" enctype="multipart/form-data"> 
            <input width="100%" type="file" size="50" name="pdf" /> <br/> 
            <asp:button Runat="server" Text="Display thumbs" ID="DisplayThumbs" OnClick="DisplayThumbs_Click" /> <br/> 
            <asp:Panel ID="thumbnails" runat="server" /> 
        </form> 
    </body> 
</HTML> 

Thanks in advance


Solution

  • If you use it to process a file-system based stream, you only need the "core logical code" from the asp.net code. You may use it like this:

    private static IList<Thumbnail> GetThumbnails(System.IO.File pdfFile) 
    { 
        string unique = Guid.NewGuid().ToString(); 
    
        using(System.IO.Stream stream = pdfFile.OpenRead())
        {
            int n = Thumbnail.GetPageCount( stream ); 
            List<Thumbnail> thumbnails = new List<Thumbnail>();
    
            for ( int i=1; i<=n; i++ )   // Note: please confirm the loop should really start from the index 1 (instead of 0?)
            { 
                Thumbnail thumbnail = new Thumbnail(); 
                thumbnail.SessionKey = unique; 
                thumbnail.Index = i; 
                thumbnails.Add( thumbnail ); 
            }
    
            return thumbnails;
        }
    }