如何在javascript中打开pdf文件新的浏览器窗口

时间:2011-10-11 13:43:58

标签: javascript

我需要在新的浏览器标签中打开pdf文件。这该怎么做。 我正在使用

var docLocation = '../downloads/doc.pdf';
window.open(docLocation,"resizeable,scrollbar"); 

但它会打开浏览器的下载对话框。怎么做到这一点?

5 个答案:

答案 0 :(得分:4)

显示pdf的能力完全取决于用户是否有可用于显示pdf的插件,并且还将其设置设置为以这种方式处理pdf文件。

有一些flash小部件可以用来向用户呈现pdf内容,但是直接回答你的问题,你无法控制用户对他们选择处理pdf文件的偏好。

答案 1 :(得分:3)

此代码将在label.append("tspan").text("hello ").attr("dx", -30);;//making a tspan and adding to x label DOM label.append("tspan").text("World").attr("dy", 20).attr("dx", -25);//making a tspan and adding to x label text DOM

的完整窗口中打开pdf文档
JavaScript

打开窗口的功能如下所示:

var pdf = MyPdf.pdf;
window.open(pdf);

答案 2 :(得分:2)

这里

    <a href="javascript:void(0);" onclick="javascipt:window.open('YourPDF.pdf');" class="popup">Clic to open.</a>

您需要在电脑上安装阅读器

答案 3 :(得分:2)

确保Content-Type标题是'application / pdf'而不是'application / octet-stream'

答案 4 :(得分:0)

我尝试了上述所有解决方案,其中没有一个适用于我,我在mvc 3上运行javascript,并且razor,adobe 11作为插件安装在Chrome和Firefox上。这是我为了让它在所有上述浏览器上工作而做的。

制作PDF控制器,从这样的javascript调用

用于主视图的剃刀代码中的

    var URL_OPEN_REPORT_PDF                   = "@Url.Content("~/Report/OpenPDF/")";

的javascript:

    var sURL = URL_OPEN_REPORT_PDF;
    sURL = AddURLParameter(sURL, "ReportArchive", moControl.treeOrganization.getUserData(sItemUI, "reportarchive"));
    window.open(sURL);

controller ReportController.cs:

    [Authorize]
    [HttpGet]
    public ActionResult OpenPDF(string ReportArchive)
    {
        PDFResult oPdfResult = new PDFResult();

        ReportArchive oReportArchive;

        var serializer = new JavaScriptSerializer();
        oReportArchive = serializer.Deserialize<ReportArchive>(ReportArchive);
        string FilePath = Server.MapPath(string.Format("~/Content/Reports/{0}", oReportArchive.FileName));

        WebClient User = new WebClient();

        Byte[] FileBuffer = User.DownloadData(FilePath);

        if (FileBuffer != null)
        {
            oPdfResult.Length = FileBuffer.LongLength;
            oPdfResult.FileBuffer = FileBuffer;
            Response.BinaryWrite(FileBuffer);

        } return View("PDF", oPdfResult);
    }

ViewModel PDFResult.cs:

public class PDFResult
{
    /// <summary>
    /// Content Length
    /// </summary>
    public long Length { get; set; }

    /// <summary>
    /// Content bytes
    /// </summary>
    public Byte[] FileBuffer { get; set; }
}

查看PDF.cshtml:

@model Report.PDFResult
@{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-length", Model.Length.ToString()); 
    Layout = null;
}
相关问题