griegs
griegs

Reputation: 22770

Display a PDF from a MemoryStream from ASHX

What I need to do is;

  1. Get a pdf from sharepoint
  2. Get a single page, using PDFSharp
  3. Return that to the view and display that page

What I have thus far is;

        context.Response.ClearHeaders();
        context.Response.ContentType = "application/pdf";            
        context.Response.AddHeader("content-disposition", "inline; filename=Something.pdf");

        // Get a fresh copy of the sample PDF file from Sharepoint later on
        string filename = @"book.pdf";

        // Open the file
        PdfDocument inputDocument = CompatiblePdfReader.Open(filename, PdfDocumentOpenMode.Import);

        PdfDocument outputDocument = new PdfDocument();
        outputDocument.Version = inputDocument.Version;
        outputDocument.Info.Title = "Pages 1 to 30";
        outputDocument.Info.Author = "Slappy";

        outputDocument.AddPage(inputDocument.Pages[1]);

        MemoryStream ms = new MemoryStream();
        outputDocument.Save(ms, false);

        ms.WriteTo(context.Response.OutputStream);

What I can't figure out is how to then display that within the web page.

I have this;

<script src="../../Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.media.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.metadata.js" type="text/javascript"></script>

<script>
    $(function () {
        $.ajax({ url: '/GetBookPage.ashx',
            success: function (result) {
                $("a.media").attr('href', result);
                $('a.media').media({ width: 800, height: 600 });
            },
            async: false
        });
    });
</script>

<a class="media">PDF File</a>

The above works if I save the pdf to the filesystem and then point the href at that file.

Upvotes: 0

Views: 5617

Answers (1)

Joel Schlundt
Joel Schlundt

Reputation: 292

With the following handler:

public class GetBookPage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string filePath = @"c:\somepath\test.pdf";
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", "inline; filename=test.pdf");
            context.Response.WriteFile(filePath);
            context.Response.End(); 
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

I was able to get the PDF to display inline if you do the following:

<script type="text/javascript">
   $(function () {
        $('a.media').media({ width: 800, height: 600 });
    });
</script>

<a class="media" href="/GetBookPage.ashx?.pdf">PDF File</a>

The plugin is using the url (or more accurately the extension) to build the proper media container on the page. If you don't have ".pdf" it won't work as expected.

Upvotes: 2

Related Questions