我使用ASMX风格的调用编写了一个Web服务来提供PDF文件。该服务处理作为POST操作发送给它的数据,将数据写入响应,并在向标头添加新的mime类型后将数据发回。
PDF文件是使用AlivePDF在flex应用程序的客户端生成的。
它运行了一段时间,但最近在谷歌chrome中开始失败——chrome没有在新窗口或PDF查看器中打开PDF(取决于浏览器的配置),而是简单地显示一个空页面。
如果在输入流中传递了有效的PDF数据,那么此代码将无法打开PDF,这是有原因的吗?
[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;
}
}
这是Chrome的常见问题。这与Chrome的自制pdf浏览器非常挑剔有关。
虽然这并不能解决显示问题,但您可以强制下载,从而解决可访问性问题。
<a href="http://www.domain.com/painful.pdf">Broken</a>
<a href="http://www.domain.com/painful.pdf" download="notsopainful">Works</a>