我需要使用jQuery和JavaScript从控制器设置一个PDF文件

4zcjmb1e  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(88)

我发现这个例子,在一个模态或弹出一个PDF文件打开。
Example这是我的Javascript代码的例子,它通过从文件夹中获取PDF文件来设置它,但我需要从控制器函数中设置文件。

<script type="text/javascript">
        $(function () {
            var fileName = "Example.pdf";
            $("#btnShow").click(function () {
                $("#dialog").dialog({
                    modal: true,
                    title: fileName,
                    width: 540,
                    height: 450,
                    buttons: {
                        Close: function () {
                            $(this).dialog('close');
                        }
                    },
                    open: function () {
                        var object = "<object data=\"{FileName}\" type=\"application/pdf\" 
 width=\"500px\" height=\"300px\">";
                        object += "If you are unable to view file, you can download from <a href=\"{FileName}\">here</a>";
                        object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
                        object += "</object>";
                        object = object.replace(/{FileName}/g, "Files/" + fileName);
                        $("#dialog").html(object);
                    }
                });
            });
        });
    </script>

但是你必须从一个控制器中设置pdf文件,这样才能调用控制器,但是我想知道如何将这个控制器注入JavaScript代码,以便能够设置我想要显示的文件。

src="@Url.Action("GetPDF", "Home", new { Model.Id })"
ifmq2ha2

ifmq2ha21#

你可以用下面的代码修改你的代码,用jQuery和JavaScript从控制器加载PDF文件:

<script type="text/javascript">
$(function () {
    $("#btnShow").click(function () {
        $.get("/path/to/controller/action", function (data) {
            var object = "<object data=\"data:application/pdf;base64,{base64EncodedPdf}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
            object += "If you are unable to view file, you can download from <a href=\"/path/to/controller/action\">here</a>";
            object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
            object += "</object>";
            object = object.replace(/{base64EncodedPdf}/g, data);
            $("#dialog").html(object);
        });
        $("#dialog").dialog({
            modal: true,
            title: "Example.pdf",
            width: 540,
            height: 450,
            buttons: {
                Close: function () {
                    $(this).dialog('close');
                }
            }
        });
    });
});
</script>

相关问题