doutai1509 2014-08-06 19:47
浏览 42

PHP创建动态pdf

Im trying to create a dynamic pdf using php,

I can load the pdf once the form is submitted but soon as I try to edit the pdf it fails to load

I shortened the code to keep it straight forward

PDF Structure

Your Name is : <<NAME>>

PHP Dynamic Script

set_time_limit(180); 

//Create Variable Names
$name = $_POST['name'];

function pdf_replace($pattern, $replacement, $string) {
    $len = strlen($pattern);
    $regexp = '';

    for($i = 0; $i <$len; $i++) {
        $regexp .= $pattern[$i];
        if($i < $len - 1) {
            $regexp .= "(\)\-{0,1}[0-9]*\(){0,1}";
        }
    }
    return ereg_replace ($regexp, $replacement, $string);
}

header('Content-Disposition: filename=cert.pdf');
header('Content-type: application/pdf');

//$date = date('F d, Y');

$filename = 'testform.pdf';
$fp = fopen($filename, 'r');
$output = fread($fp, filesize($filename));

fclose($fp);

//Replace the holders
$output = pdf_replace('<<NAME>>', $name, $output);


echo $output;

If I comment out the output it loads the form fine but soon as I try to run the function to replace the placeholder it fails to load. Anyone do something like this before?

  • 写回答

5条回答 默认 最新

  • dongyumiao5210 2014-08-20 08:23
    关注

    I've tried your code and I can assume there are one of the following reasons that can cause the problem:


    When you call pdf_replace() PHP returns Deprecated notice on ereg_replace() function. This breaks PDF structure and cause PDF fail to load. This function is deprecated since PHP 5.3.0. Simple solution is to start using preg_replace() instead.

    function pdf_replace($pattern, $replacement, $string) {
        return preg_replace('/'.preg_quote($pattern,'/').'/', $replacement, $string);
    }
    

    In case you can't do it then the solution is to either edit php.ini file and edit error_reporting parameter. You can add "^ E_DEPRECATED" to your current config value to disable Deprecated notices. Other option is to add error_reporting() at the beginning of your script with appropriate value.


    I do not see the PDF you use but some PDF generators encode PDF source. In this case it is a problem to find text there. For example I've tried "Print to PDF" feature on Mac and I was not able to find plain text in source there. So either fopen or ereg_replace can complain about wrong file format. In this case you should use some library that can work with PDF in more clever manner. I prefer FPDF but there are plenty of such libraries.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用