如何使用PHP脚本打开安全的pdf


how to open the secured pdf with PHP script

我正在做一个项目,用户可以上传一个受密码保护的pdf文件。还有一个表单,用户可以为其提供密码

有没有办法用PHP打开这个受密码保护的pdf?

您可以通过使用简单的java程序并从PHP脚本中调用可执行jar文件来实现这一点。您需要pdfbox.jar文件来从PDF文件中删除密码,您可以从https://pdfbox.apache.org/download.cgi.在这个例子中,你得到一个文本文件,你也可以在解锁后生成PDF文件。

package pdftotext;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public class PdfTotext {
public static void main(String[] args) {
String filename = args[0];
String password = args[1];
PDDocument pd;
BufferedWriter wr;  
try {
        File input = new File(filename);  // The PDF file from where you would like to extract
        File output = new File("unlock.txt"); // The text file where you are going to store the extracted data
        pd = PDDocument.load(input,password);
        pd.setAllSecurityToBeRemoved(true);
        PDFTextStripper stripper = new PDFTextStripper();
        wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
        stripper.writeText(pd, wr);
        if (pd != null) {
            pd.close();
       }
      wr.close();
    } catch (Exception e){
     e.printStackTrace();
    } 
}
}

在PHP脚本中,您需要传递文件名和密码

<?php exec("java -jar pdfTotext.jar filename.pdf password"); ?>

确保可执行jar文件、库文件和pdf文件位于同一文件夹中。

我们提供一款名为SetaPDF Extractor的产品,它能够用PHP从PDF文档中提取文本。请注意,它不是免费的。如果您的身份验证正确,它还允许您从受保护的文档中提取文本。下面的代码只是一些伪逻辑,但应该显示什么是可能的。有关身份验证的详细信息可以在这里找到:

<?php
require_once("library/SetaPDF/Autoload.php");
// create a document instance
$document = SetaPDF_Core_Document::loadByFilename("Laboratory-Report.pdf");
if ($document->hasSecHandler()) {
    // get the security handler
    $secHandler = $document->getSecHandler();
    // auth by the user password
    if (!$secHandler->authByUserPassword('a secret password')) {
        // ... not authenticated
    }
    // auth by the owner password
    if (!$secHandler->authByOwnerPassword('another secret password')) {
        // ... not authenticated
    }
    // stop at least here if you are not authenticated
}
// create an extractor instance
$extractor = new SetaPDF_Extractor($document);
// get the plain text from page 1
$result = $extractor->getResultByPageNumber(1);
// output
echo '<pre>';
echo htmlspecialchars($result);
echo '</pre>';