Dan Monego
Dan Monego

Reputation: 10087

Issue serving PDF files to Google Chrome

I wrote a webservice using ASMX style calls to serve PDF files. The service processes data sent to it as a POST operation, writes the data to the response, and sends the data back after adding a new mime type to the headers.

The PDF files are generated client side in a flex application using AlivePDF.

It's worked fine for a while, but it recently began failing in google chrome - Instead of opening the PDF in either a new window or a PDF viewer (depending on the browser's configuration), chrome simply displays an empty page.

Is there a reason why this code would fail to open a PDF if it has been passed valid PDF data in the input stream?

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Print : System.Web.Services.WebService
{


    [WebMethod]
    public string PrintPDF()
    {
        HttpRequest request = HttpContext.Current.Request;
        HttpResponse response = HttpContext.Current.Response;
        string requestMethod = request.Params["method"];
        string requestFilename = request.Params["name"];

        if(!validateRequest(request))
        {
            throw new ArgumentException(String.Format("Error downloading file named '{0}' using disposition '{1}'", requestFilename, requestMethod));
        }
        response.AddHeader("Content-Disposition", "attachment; filename=\"" + requestFilename + "\"");
        byte[] pdf = new byte[request.InputStream.Length];
        request.InputStream.Read(pdf, 0, (int)request.InputStream.Length);
        response.ContentType = "application/pdf";
        response.OutputStream.Write(pdf, 0, (int)request.InputStream.Length);
        response.Flush();
        response.End();
        return "Fail";
    }

    private bool validateRequest(HttpRequest request)
    {
        string requestMethod = request.Params["method"];
        string requestFilename = request.Params["name"];

        Regex cleanFileName = new Regex("[a-zA-Z0-9\\._-]{1, 255}\\.[a-zA-Z0-9]{1, 3}");
        return (requestMethod == "attachment" || requestMethod == "inline") &&
               cleanFileName.Match(requestFilename) != null;
    }
}

Upvotes: 0

Views: 1240

Answers (1)

InsanelyADHD
InsanelyADHD

Reputation: 548

This is a common problem with Chrome. It has to do with Chrome's homebrewed pdf viewer being really picky.

While this doesn't fix the display issue, you can force a download, fixing the accessibility issue.

<a href="http://www.domain.com/painful.pdf">Broken</a>
<a href="http://www.domain.com/painful.pdf" download="notsopainful">Works</a>

Upvotes: 1

Related Questions