Слияние данных FDF в PDF с PHP - PullRequest
3 голосов
/ 14 февраля 2012

В моем нынешнем виде у меня есть код для создания файла .xfdf на сервере и PDF для его заполнения. Я продолжаю получать pdf, который я хочу заполнить полями формы, которые все еще не заполнены. Сотрудник Packet.pdf - это файл PDF, заполненный Application.xfdf. Оба находятся в каталоге / results на моем веб-сервере.

Я знаю, что начальная часть моего кода неполная, у меня есть только проверка поля «Имя» перед отправкой. Я хотел бы завершить это, но главная проблема, которую я имею, заключается в том, чтобы заполнить указанный PDF-файл на веб-сервере, и готовый продукт был отправлен пользователю по электронной почте.

Я взял отсюда код "Pass Thru", но я думаю, что это для сторонней прикладной функции. Любая помощь будет отличной, заранее спасибо!

<?php 
    // check that a form was submitted 
    if(isset($_POST) && is_array($_POST) && count($_POST)){ 
        // we will use this array to pass to the createFDF function 
        $data=array(); 


        if(isset($_POST['FIRST_NAME'])){ 
            // the name field was submitted 
            $pat='`[^a-z0-9\s]+$`i'; 
            if(empty($_POST['FIRST_NAME']) || preg_match($pat,$_POST['FIRST_NAME'])){ 
                // no value was submitted or something other than a 
                // number, letter or space was included 
                die('Invalid input for First Name field.'); 
            }else{ 
                // if this passed our tests, this is safe 
                $data['FIRST_NAME']=$_POST['FIRST_NAME']; 
            } 



            if(!isset($_POST['FIRST_NAME'])){ 
                // Why this? What if someone is spoofing form submissions 
                // to see how your script works? Only allow the script to 
                // continue with expected data, don't be lazy and insecure ;) 
                die('You did not submit the correct form.'); 
            } 

            // Check your data for ALL FIELDS that you expect, ignore ones you 
            // don't care about. This is just an example to illustrate, so I 
            // won't check anymore, but I will add them blindly (you don't want 
            // to do this in a production environment). 
            $data['LAST_NAME']=$_POST['LAST_NAME']; 
            $data['FIRST_NAME']=$_POST['FIRST_NAME']; 
            $data['MIDDLE_NAME']=$_POST['MIDDLE_NAME']; 
            $data['ADDRESS']=$_POST['ADDRESS']; 
            $data['ADDRESS_APT']=$_POST['ADDRESS_APT']; 
            $data['CITY']=$_POST['CITY']; 
            $data['STATE']=$_POST['STATE']; 
            $data['ZIP']=$_POST['ZIP']; 
            $data['HOME_PHONE_AREA']=$_POST['HOME_PHONE_AREA']; 
            $data['HOME_PHONE_PREFIX']=$_POST['HOME_PHONE_PREFIX']; 
            $data['HOME_PHONE_SUBSCRIBER']=$_POST['HOME_PHONE_SUBSCRIBER']; 


            // if we got here, the data should be valid, 
            // time to create our FDF file contents 

            // need the function definition 
            require_once 'createXFDF.php'; 

            // some variables to use 

            // file name will be <the current timestamp>.fdf 
            $fdf_file='Application.xfdf'; 

            // the directory to write the result in 
            $fdf_dir=dirname(__FILE__).'/results'; 

            // need to know what file the data will go into 
            $pdf_doc='results/Employee Packet.pdf'; 

            // generate the file content 
            $fdf_data=createXFDF($pdf_doc,$data); 

            // this is where you'd do any custom handling of the data 
            // if you wanted to put it in a database, email the 
            // FDF data, push ti back to the user with a header() call, etc. 

            // write the file out 

             if($fp=fopen($fdf_dir.'/'.$fdf_file,'w')){ 
                fwrite($fp,$fdf_data,strlen($fdf_data)); 
                echo $fdf_file,' written successfully.'; 
            }else{ 
                die('Unable to create file: '.$fdf_dir.'/'.$fdf_file); 
            } 
            fclose($fp); 
        } 
            //define the receiver of the email  
$to = me@me.com';  
//define the subject of the email  
$subject = 'Test email with attachment';  
//create a boundary string. It must be unique  
//so we use the MD5 algorithm to generate a random hash  
$random_hash = md5(date('r', time()));  
//define the headers we want passed. Note that they are separated with \r\n  
$headers = "From: webmaster@site.com\r\nReply-To: webmaster@site.com";  
//add boundary string and mime type specification  
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";  
//read the atachment file contents into a string, 
//encode it with MIME base64, 
//and split it into smaller chunks 
$attachment = chunk_split(base64_encode(file_get_contents('results/Employee Packet.pdf')));  
//define the body of the message.  
ob_start(); //Turn on output buffering  
?>  
--PHP-mixed-<?php echo $random_hash; ?>   
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"  

--PHP-alt-<?php echo $random_hash; ?>   
Content-Type: text/plain; charset="iso-8859-1"  
Content-Transfer-Encoding: 7bit 

Hello World!!!  
This is simple text email message.  

--PHP-alt-<?php echo $random_hash; ?>   
Content-Type: text/html; charset="iso-8859-1"  
Content-Transfer-Encoding: 7bit 

<h2>Hello World!</h2>  
<p>This is something with <b>HTML</b> formatting.</p>  

--PHP-alt-<?php echo $random_hash; ?>--  

--PHP-mixed-<?php echo $random_hash; ?>   
Content-Type: application/vnd.adobe.xfdf   
Content-Transfer-Encoding: base64   
Content-Disposition: attachment; filename = "Finished Form fill.pdf" 
passthru("results/Employee Packet.pdf results/Application.xfdf output - "); 
exit; 
<?php echo $attachment; ?>  
--PHP-mixed-<?php echo $random_hash; ?>--  

<?php  
//copy current buffer contents into $message variable and delete current output buffer  
$message = ob_get_clean();  
//send the email  
$mail_sent = @mail( $to, $subject, $message, $headers );  
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"  
echo $mail_sent ? "Mail sent" : "Mail failed";  
    } 
?> 
...