简体   繁体   English

使用PHP和jQuery将PDF打印到页面

[英]Print PDF to page with PHP & jQuery

So I need a little help with a php script I am writing that loads a PDF in a new tab through a PHP script. 所以我需要一些关于我正在编写的PHP脚本的帮助,它通过PHP脚本在新选项卡中加载PDF。 I am doing it this way to make sure that the PDF can only be accessed if the user is logged in and has a link to it, otherwise the .htaccess in the parent directory to the PDF blocks access. 我这样做是为了确保只有用户登录并且有链接才能访问PDF,否则PDF目录的父目录中的.htaccess会阻止访问。
I am able to read from the PDF using the code below: 我可以使用以下代码从PDF中读取:

$file = '../path-to-file.pdf';
$filename = 'filename.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
@readfile($file);

The result of this is then passed into an AJAX function shown below which generates a new tab and throws the response onto it: 然后将结果传递给下面显示的AJAX函数,该函数生成一个新选项卡并将响应抛出到它上面:

$.ajax({
    url: '../includes/function.projects.php?view-media=' + item,
        success: function(data) {
            $(window.open().document.body).html(data);
        }
    })

This all works smoothly, it's only when the new tab opens, because I am writing the response straight to the documents HTML, I am getting a screen full of text like this: 这一切都很顺利,只有当新标签打开时,因为我正在直接写文档HTML,我得到一个充满文字的屏幕,如下所示:

%PDF-1.5 %���� 2 0 obj << /Linearized 1 /L 17007 /H [ 687 126 ] /O 6 /E 16732 /N 1 /T 16731 >>

So my question is quite simply this; 所以我的问题很简单; Has anyone tried managed to do this before? 有没有人试过设法做到这一点? If so, are there any libraries I should be using/headers I'm missing etc 如果是这样,是否有我应该使用的库/我缺少的标题等

I have already seen this question here but I cannot get the answers people are listing to work so I am out of ideas. 我已经在这里看到了这个问题,但我无法得到人们列出的工作答案,所以我没有想法。

Any help would be greatly appreciated, Thanks in advance! 任何帮助将不胜感激,提前致谢!

Right so I have a solution. 对,所以我有一个解决方案。 If someone can come up with a better way of doing this, please let me know but for now this works perfectly! 如果有人可以提出更好的方法,请告诉我,但现在这完美! I found a JS library called PDFObject which can be used to make a cross-browser solution for easily embedding PDFs into a html document. 我发现了一个名为PDFObject的JS库,可用于制作跨浏览器解决方案,以便将PDF轻松嵌入到html文档中。 With this, I can pass in a PDF link on the server along with a target div for it to embed into (which in my case I have setup inside of a modal so we stay on the same page). 有了这个,我可以在服务器上传递一个PDF链接以及一个目标div,以便嵌入(在我的情况下,我已经设置了一个模态,所以我们保持在同一页面上)。

Because we are staying on the same page, I can block access to the entire page using a function I had written previously in the project which redirects the user to the index if they don't have the right access level. 因为我们停留在同一页面上,所以我可以使用我之前在项目中编写的函数阻止访问整个页面,如果用户没有正确的访问级别,则会将用户重定向到索引。 Something along the lines of this would work: 根据这一点的某些方面可行:

function checkSession() {
    if(empty($_SESSION)) {
        header("Location: /?cheeky_monkey");
    }
}

If the user tried to access the PDF directly, then this code in the htaccess blocks them. 如果用户试图直接访问PDF,则htaccess中的此代码会阻止它们。 It only allows access if being targeted through the application: 它只允许通过应用程序进行目标访问:

SetEnvIf Referer "localhost" is_local_referer
<FilesMatch "\.pdf$">
    Require env is_local_referer
</FilesMatch>

With that out the way, all that needs to happen is to throw a URL at the script tag to load when a PDF is clicked on, accomplished through this sequence of code: 除此之外,所有需要发生的事情是在脚本标记处抛出一个URL,以便在单击PDF时加载,通过以下代码序列完成:

  1. First we need to grab the URL for the PDF (you might be able to skip this step) 首先,我们需要获取PDF的URL(您可以跳过此步骤)

To begin with, this javascript is called whenever someone clicks to view a PDF (this call is simply nested as an onclick attribute): 首先,只要有人点击查看PDF(此调用只是嵌套为onclick属性),就会调用此javascript:

function viewMedia(projectID, type, item) {
    $.ajax({
        url: '../includes/function.projects.php?cid=' + projectID + '&type=' + type + '&view-media=' + item,
        success: function(data) {
            $('.pdf-script').html('<script>PDFObject.embed("' + data + '", "#the-pdf");</script>');
            $('#viewMediaModal').modal('toggle');
        }
    })
}

This is the code that is ran on the php page. 这是在php页面上运行的代码。

public function viewMedia($item) {
    $mediaItems = unserialize($this->media);
    $file = '/path/to/pdf/' . $mediaItems[$item]['file'];
    echo $file;
}

An example of the returned data from this function: 此函数返回数据的示例:

/path/to/pdf/example-pdf.pdf
  1. Using this to load the PDF 使用它来加载PDF

Once we have the correct URL for the PDF and the AJAX returns as successful, the data received back can be used to re-generate the javascript, this time with the new PDF link: 一旦我们拥有PDF的正确URL并且AJAX返回成功,收到的数据就可以用来重新生成javascript,这次使用新的PDF链接:

success: function(data) {
    $('.pdf-script').html('<script>PDFObject.embed("' + data + '", "#the-pdf");</script>');
    $('#viewMediaModal').modal('toggle');
}

This is what the structure of that modal body looks like: 这就是那个模态体的结构:

<div class="modal-body">
    <div id="the-pdf"></div>
    <div class="pdf-script" style="display: none;">
        <script>PDFObject.embed('', '#the-pdf');</script>
    </div>
</div>
  1. The result 结果

The result of the above code sequence toggles a modal that look like the below: 上面的代码序列的结果切换了一个如下所示的模态:

在此输入图像描述

And if the user tries to access the file directly: 如果用户尝试直接访问该文件:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM