Jump to content

Convert .fdf to .pdf


Ty44ler

Recommended Posts

I currently have a web form that uploads the form data to an .fdf file and emails it.

 

However, I just realized that most people I email it to cannot open an .fdf and it needs to be in pdf.

 

Is there any way to convert an fdf file to pdf using php??

 

 

Here is my code which currently creates the .fdf:

function createFDF($file,$info){
    $data="%FDF-1.2\n%âãÏÓ\n1 0 obj\n<< \n/FDF << /Fields [ ";
    foreach($info as $field => $val){
    	if(is_array($val)){
        	$data.='<</T('.$field.')/V[';
        	foreach($val as $opt)
        		$data.='('.trim($opt).')';
        	$data.=']>>';
    	}else{
        	$data.='<</T('.$field.')/V('.trim($val).')>>';
    	}
    }
    $data.="] \n/F (".$file.") /ID [ <".md5(time()).">\n] >>".
        " \n>> \nendobj\ntrailer\n".
        "<<\n/Root 1 0 R \n\n>>\n%%EOF\n";
    return $data;
}

Link to comment
Share on other sites

FDF is supposed to be a subtype of PDF so it's strange people have trouble opening it (although admittedly, I don't recall ever having to open it). Theoretically Adobe Reader is all they need... ???

 

I'm not sure if it's possible to obtain all the features FDF within PDF... perhaps you should refer to PDF specification?

http://www.adobe.com/devnet/pdf/pdf_reference.html

Link to comment
Share on other sites

The problem is that it reads from the other pdf and applies the information to it. In short I'd have to make sure everyone has the original pdf with the same document path which will be hard to do, which is why I was just hoping to convert it on transmission and send the flattened pdf.

Link to comment
Share on other sites

Here is my code that creates the fdf data...

// 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);

 

Now how would I take the variable that contains the fdf data ($fdf_data) and convert it into a pdf? I found this piece of code that will convert it, but don't know how to implement it:

 function FDF2PDF($FileFDF,$FilePDF_Out='')
{
//Laod FDF
//$FilePDF_In=self::Load($FileFDF,TRUE);

//Prepare the name of the PDF
$FilePDF_Ref=basename($FilePDF_In);

//Find the name of the output file
if (!$FilePDF_Out)
  {$FilePDF_Out=str_replace(".fdf",".pdf",$FileFDF);}

//Retrieve the PDF
if ($FilePDF_Ref AND !file_exists($FilePDF_Ref))
  {copy($FilePDF_In,$FilePDF_Ref);}

//Empty the old version of PDF if it exists
if ($FilePDF_Out AND file_exists($FilePDF_Out))
  {unlink($FilePDF_Out);}

//Converted
exec("pdftk $FilePDF_Ref fill_form $FileFDF output $FilePDF_Out");

return $FilePDF_Out;
}

Link to comment
Share on other sites

1. This looks like a part of some larger class. You will need whole class to be able to use it.

2. You will also need pdftk binary (don't ask me where to get it or what it is).

3. It seems you just need to pass a filename of saved fdf file, but it's hard to be sure without seeing whole class.

 

 

 

Link to comment
Share on other sites

1. This looks like a part of some larger class. You will need whole class to be able to use it.

2. You will also need pdftk binary (don't ask me where to get it or what it is).

3. It seems you just need to pass a filename of saved fdf file, but it's hard to be sure without seeing whole class.

 

1. Here's the whole class. I just don't know how to implement it into my code...

class pdf_fdf
{
/**
* make a file FDF
*
* @param string $FichierIn Name PDF file reference
* @param array $Data1 List of variables to include
* @param array $Data2 List of variables to include unprotected
* @return FDF
*/
public static function Make($FichierIn,$Data1,$Data2="")
{
$Out = "%FDF-1.2\n%????\n";
$Out .= "1 0 obj \n<< /FDF << /Fields [\n";

if ($Data1)
  {
  foreach ($Data1 as $DataKey=>$DataVal)
         {
         $DataVal=str_replace("\r\n","\n",$DataVal);
         $DataVal=str_replace("\r"  ,"\n",$DataVal);
         $Out.= "<< /T (".addcslashes($DataKey,"\n\r\t\\()").") /V (".addcslashes($DataVal,"\n\r\t\\()").") >> \n";
         }
  }

if (is_array($Data2))
  {
  foreach ($Data2 as $DataKey=>$DataVal)
         {
         $DataVal=str_replace("\r\n","\n",$DataVal);
         $DataVal=str_replace("\r"  ,"\n",$DataVal);
         $Out.="<< /T (".addcslashes($DataKey,"\n\r\t\\()").") /V /".$DataVal." >> \n";
         }
  }

$Out.= "]\n/F ($FichierIn) >>";

$Out.= ">>\nendobj\ntrailer\n<<\n";
$Out.= "/Root 1 0 R \n\n>>\n";
$Out.= "%%EOF";

return $Out;
}

/**
* Save a file FDF
*
* @param string $FichierIn Name PDF file reference
* @param array $Data Fields
* @param string $FichierOut Name File final
* @return bool
*/
public static function Save($FichierIn,$Data,$FichierOut)
{
if ($FId=fopenw($FichierOut,'w'))
  {
  $Data=self::Make($FichierIn,$Data);
  fwrite($FId,$Data,strlen($Data));
  $Out=TRUE;
  }
  else
  {$Out=FALSE;}
return $Out;
}

/**
* Load a file FDF
*
* @param string $Fichier File to analyse
* @param bool $PDF Type of file (PDF | FDF)
* @return string
*/
public static function Load($Fichier,$PDF=FALSE)
{
$Out=array();

if ((file_exists($Fichier))and($Fichier>''))
  {
  $Data=File($Fichier);

  if ($PDF)
    {
    $Nb=count($Data);
    for ($i=4;$i<$Nb;$i++)
       {
       $DataOut=array();
       if(eregi("/F \(([^)]*)\)",$Data[$i],$DataOut))
         {
         $Out=$DataOut[1];
         break;
         }
       }
    }
    else
    {
    $Nb=count($Data)-9;
    for ($i=4;$i<$Nb;$i++)
       {
       $DataOut=array();

       $In=$Data[$i];
       $In=str_replace('\)','§PF§',$In);
       $In=str_replace('\r\n',EOL,$In);
       $In=str_replace('\n',EOL,$In);
       $In=str_replace('\r',EOL,$In);
       $In=stripslashes($In);

       eregi("/T \(([^)]*)\) /V \(([^)]*)\)",$In,$DataOut);
       $Out[$DataOut[1]]=str_replace("§PF§",")",$DataOut[2]);
       }
     }
  }

return $Out;
}

/**
* Transform an FDF PDF
*
* @param string $FileFDF Filename a PDF transfrmer
* @param string $FilePDF_Out Filename of output
* @return string
*/
public static function FDF2PDF($FileFDF,$FilePDF_Out='')
{
//Laod FDF
$FilePDF_In=self::Load($FileFDF,TRUE);

//Prepare the name of the PDF
$FilePDF_Ref=basename($FilePDF_In);

//Find the name of the output file
if (!$FilePDF_Out)
  {$FilePDF_Out=str_replace(".fdf",".pdf",$FileFDF);}

//Retrieve the PDF
if ($FilePDF_Ref AND !file_exists($FilePDF_Ref))
  {copy($FilePDF_In,$FilePDF_Ref);}

//Empty the old version of PDF if it exists
if ($FilePDF_Out AND file_exists($FilePDF_Out))
  {unlink($FilePDF_Out);}

//Converted
exec("pdftk $FilePDF_Ref fill_form $FileFDF output $FilePDF_Out");
echo ("successful");
return $FilePDF_Out;
}

/**
* HTML header for FDF
*
*/
public static function Header()
{
header('Content-type: application/vnd.fdf');
//header( "Content-type: application/vnd.adobe.xfdf");
}
}

 

2. I also have the pdftk.exe saved to my c:/ on my server.

3. Could you please explain how to pass the filename through here?

 

I appreciate it so much, this would be a huge help to me.

Link to comment
Share on other sites

I think you should have pdftk.exe in same directory as your script.

 

Then running

<?php
pdf_fdf::FDF2PDF('fileName.fdf');

 

should create 'fileName.pdf' in the same directory.

 

I'm doing a lot of guessing here. It would be best if you could ask creator of this class.

 

Link to comment
Share on other sites

I tried to contact the creator of the class, but the email address is no longer valid... :(

 

Thanks for helping me even though you may not know much about it...

 

Where would I put this at?

pdf_fdf::FDF2PDF('fileName.fdf');

 

Here's what runs after the user submits the form....

 


<?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();
        
        // This displays all the data that was submitted. You can
        // remove this without effecting how the FDF data is generated.
        

	echo'<pre>POST '; print_r($_POST);echo '</pre>';


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

		$data['VoltsPHHZ']=$_POST['VoltsPHHZ'];
		$data['Charge_lbs']=$_POST['Charge_lbs'];
		$data['Charge_Oz']=$_POST['Charge_Oz'];
		$data['Method_Used']=$_POST['Method_Used'];
		$data['Refrigerant_Type']=$_POST['Refrigerant_Type'];			
            
            // I wanted to add the date to the submissions
            $data['Date']=date('m-d-Y');
            
            // if we got here, the data should be valid,
            // time to create our FDF file contents
            
            // need the function definition
            require_once 'createFDF.php';
            
            // some variables to use
            
            // file name will be <the current timestamp>.fdf
	$fdf_file=$_POST['Serviced_By'].'-'.date('d-m-Y').'.fdf';
            
            // the directory to write the result in
           $fdf_dir=dirname(__FILE__).'/results';
            
            // location of pdf to write to...
		$pdf_doc='../Refrigerant Information Compliance Form.pdf';					

            
            // generate the file content
           $fdf_data=createFDF($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 it 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);
        }																					
    
else{
        echo 'You did not submit a form.';
    }																								
?>

Link to comment
Share on other sites

Well it runs, but there is an error...

 

Warning: basename() expects parameter 1 to be string, array given in "C:\****\submissiontest.php" on line 155

successfullaura.fdf written successfully.successful

 

This is line 155:

//Prepare the name of the PDF
$FilePDF_Ref=basename($FilePDF_In);

 

I thought it was only passing the serviced by and date string?

Link to comment
Share on other sites

yep, you were right about that one...

 

Let me just say again how much I really do appreciate you helping me out like this.

 

It's getting there, but now it receives this error on line 161:

 

Warning: copy(Array) [function.copy]: failed to open stream: No such file or directory in C:\******\submissiontest.php on line 163

successfullaura.fdf written successfully.successful

 

Here's the line of code:

//Retrieve the PDF
if ($FilePDF_Ref AND !file_exists($FilePDF_Ref))
  {copy($FilePDF_In,$FilePDF_Ref);}

 

Link to comment
Share on other sites

Well I don't get any errors anymore :), but there is only the fdf file that I was getting before I ran it through the converter....

 

 

I echoed out the variables to see their values and it looks like the path is messed up... but maybe I'm wrong...

 

part of submissiontest.php:

//Laod FDF
$FilePDF_In=self::Load($FileFDF,TRUE);

//Prepare the name of the PDF
$FilePDF_Ref=basename($FileFDF);

//Find the name of the output file
if (!$FilePDF_Out)
  {$FilePDF_Out=str_replace(".fdf",".pdf",$FileFDF);}

//Retrieve the PDF
if ($FilePDF_Ref AND !file_exists($FilePDF_Ref))
  {copy($FileFDF,$FilePDF_Ref);}

//Empty the old version of PDF if it exists
if ($FilePDF_Out AND file_exists($FilePDF_Out))
  {unlink($FilePDF_Out);}

//Converted
exec("pdftk $FilePDF_Ref fill_form $FileFDF output $FilePDF_Out");


//This is where the variables are echoed out to see the values....
echo ("<br />$FilePDF_Out <br /> $FileFDF  <br />$FilePDF_Ref");

return $FilePDF_Out;
}

 

displays this:

laura.fdf written successfully.

C:\xampp\htdocs\My Dropbox\test/results/laura.pdf

C:\xampp\htdocs\My Dropbox\test/results/laura.fdf

laura.fdf

 

here's my submit_form.php code if you need to see that as well...

require_once 'submissiontest.php';
            // write the file out
          if($fp=fopen($fdf_dir.'/'.$fdf_file,'w')){
                fwrite($fp,$fdf_data,strlen($fdf_data));

		//pdf_fdf::FDF2PDF($fdf_dir.'/'.$fdf_file);
		//pdf_fdf::FDF2PDF('fileName.fdf');


		echo $fdf_file,' written successfully.';
		  
            }else{
                die('Unable to create file: '.$fdf_dir.'/'.$fdf_file);
            }
            fclose($fp);

		pdf_fdf::FDF2PDF($fdf_dir.'/'.$fdf_file);
        }																					
    
else{
        echo 'You did not submit a form.';
    }	

Link to comment
Share on other sites

Perhaps try using \ instead of / as your path separator...

 

What's in $FilePDF_Ref ?

 

I tried  switching the slashes, but then it throws a parse error on the line that the slash is in...

 

here's what I tried and neither work...

pdf_fdf::FDF2PDF($fdf_dir.'\'.$fdf_file);

pdf_fdf::FDF2PDF($fdf_dir.\.$fdf_file);

 

$FilePDF_Ref is the location of the pdf file that has the text fields laid on top of it for formatting.

 

$FilePDF_Ref = Refrigerant Information Compliance Form.pdf

Link to comment
Share on other sites

I've tried running it from the command line and it does work. It outputs the file into the same folder..

 

I ran it from the command line using some dummy files and it worked...

pdftk testform.pdf fill_form testfdf.fdf output itworked.pdf flatten

 

How can I get it so that php will take the fdf file that it created and stick it in there so that it outputs my pdf? ahh, this is so frustrating I feel like it's so close, but still so far....

Link to comment
Share on other sites

Well, I've figured it out. I appreciate your help. If it weren't for your posts I never would have got on the right track...

 

            // 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);

		exec('pdftk Refrigerant_Information_Compliance_Form.pdf fill_form '.$fdf_file.' output '.$pdf_file.' flatten');

		echo $fdf_file;
        }																					
    
else{
        echo 'You did not submit a form.';
    }	

 

I was overcomplicating it with the other code, it's not even needed. Since my first code had already created the .fdf file all you have to do is run the fdf name as a variable and place it in the exec() statement and pdftk takes care of the rest. I did the same with the pdf name as I didn't want two pdf's of the same name. Thank you for your help again!

Link to comment
Share on other sites

  • 11 months later...
I was overcomplicating it with the other code, it's not even needed. Since my first code had already created the .fdf file all you have to do is run the fdf name as a variable and place it in the exec() statement and pdftk takes care of the rest. I did the same with the pdf name as I didn't want two pdf's of the same name. Thank you for your help again!

 

I'm having a problem with this step.  Where do all my files need to be located in order to perform the exec() command properly?  I can do it fine using the command line where all these files (i.e., pdftk.exe, libiconv2.dll, my PDF form, the generated FDF file, and resulting final PDF file) are in the same directory.  Is that the key though?  Even if I specify path names?  Because I can't seem to get the exec() command to properly run.  My PDF is not being generated.  Any thoughts?

Link to comment
Share on other sites

  • 3 weeks later...

Well, I've figured it out. I appreciate your help. If it weren't for your posts I never would have got on the right track...

 

            // 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);

		exec('pdftk Refrigerant_Information_Compliance_Form.pdf fill_form '.$fdf_file.' output '.$pdf_file.' flatten');

		echo $fdf_file;
        }																					
    
else{
        echo 'You did not submit a form.';
    }	

 

I was overcomplicating it with the other code, it's not even needed. Since my first code had already created the .fdf file all you have to do is run the fdf name as a variable and place it in the exec() statement and pdftk takes care of the rest. I did the same with the pdf name as I didn't want two pdf's of the same name. Thank you for your help again!

 

Were you able to resolve this?  This is driving me crazy.  I think I'm at the same point you were when you were seeking help.  Thanks for any help.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.