Page 1 of 1

Automating MSWord Find/Replace in Headers

Posted: Tue Dec 05, 2006 7:16 pm
by mpiaser
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I'm able to write PHP code to find/replace strings in a MSWord document but it won't change strings that are in Header/footers.  It seems that I have to use something called STORIES to accomplish this but it is soooo confusing that I can't figure out how to do that.  My code is below (it works except for header/footer replacements):

Code: Select all

<?php

class MSWord
   {
       // Vars:
       var $handle;

       // Create COM instance to word
       function MSWord($Visible = false)
       {
           $this->handle = new COM("word.application") or die("Unable to instanciate Word");
           $this->handle->Visible = $Visible;
       }

       // Open existing document
       function Open($File)
       {
           $this->handle->Documents->Open($File,0,1);
       }

       function Replace($what, $with) {
           $this->handle->Documents[1]->Activate();
           $this->handle->ActiveDocument->Select();
  //         $this->handle->ActiveDocument->Sections(1)->Headers(1)->Range->StoryType;
           $this->handle->Selection->Find->ClearFormatting();
           $this->handle->Selection->Find->Replacement->ClearFormatting();
           $this->handle->Selection->Find->Execute($what, false, false, false, false, false, true, 1, false, $with, 2, false, false, false, false);
//           ActiveDocument.Sections(1).Headers(1).Range.StoryType

       }
       
        function InsertFile($name) {
           $this->handle->Documents[1]->Activate();
           $this->handle->ActiveDocument->Select();
           $this->handle->Selection->End();
           $Last=$this->handle->ActiveDocument->Content->End();
           $this->handle->Selection->SetRange($Last,$Last);
//           $this->handle->Selection->InsertBreak(7);  // 7 means wdPageBreak
           $this->handle->Selection->InsertFile($name);
//           $this->handle->Documents[1]->Sections(1)->Footers(1)->Range->Text("inserted footer");
       }
        function InsertTable() {
// **************************************
//Set MyRange = ActiveDocument.Content
//MyRange.Collapse Direction:=wdCollapseEnd
$Last=$this->handle->ActiveDocument->Content->End();
$a=5;
$this->handle->ActiveDocument->Tables->Add($Last,$a,'5');
//ActiveDocument.Tables.Add Range:=MyRange, NumRows:=6, _
//    NumColumns:=10This example adds a table with three rows and five columns to a new document and then inserts data into each cell in the table.

//Set newDoc = Documents.Add
//Set myTable = newDoc.Tables.Add(Selection.Range, 3, 5)
//With myTable
//For x = 1 to 3
//    For y = 1 to 5
//        .Cell(x,y).Range.InsertAfter "Cell " & x & "," & y
//    Next y
//Next x
//.Columns.AutoFit
//End With

// *******************************************
     }
       // Create new document
       function NewDocument()
       {
           $this->handle->Documents->Add();
       }

       // Write text to active document
       function WriteText( $Text )
       {
           $this->handle->Selection->Typetext( $Text );
       }

       // Set page margins
       function SetMargins($top,$bottom,$left,$right)
       {
            $this->handle->Documents[1]->PageSetup->TopMargin = "$top cm";
            $this->handle->Documents[1]->PageSetup->BottomMargin = "$bottom cm";
            $this->handle->Documents[1]->PageSetup->LeftMargin = "$left cm";
            $this->handle->Documents[1]->PageSetup->RightMargin = "$right cm";
       }

       // Number of documents open
       function DocumentCount()
       {
           return $this->handle->Documents->Count;
       }

       // Save document as another file and/or format
       function SaveAs($File, $Format = 0 )
       {
           $this->handle->ActiveDocument->SaveAs($File, $Format);
       }

       // Save active document
       function Save()
       {
           $this->handle->ActiveDocument->Save();
       }

       // close active document.
       function Close()
       {
           $this->handle->ActiveDocument->Close();
       }

       // Get word version
       function GetVersion()
       {
           return $this->handle->Version;
       }

       // get handle to word
       function GetHandle()
       {
           return $this->handle;
       }

       // Clean up instance with word
       function Quit()
       {
           if( $this->handle )
           {
               // close word
               $this->handle->Quit();

               // free the object
  //             $this->handle->Release();
               $this->handle = null;
           }
       }
   };

function SendDocumentToWord($Letter,$FileName,$Type)
{

include_once('SubstituteLetterVariables.php');


$Z=file_get_contents('C:/inetpub/wwwroot/SubstituteLetterVariables.txt');
$T=SubstituteLetterVariables($Z,'$Type','EPL');
if (is_file('C:\temp\SubstituteLetterVariables.tmp')) unlink('C:\temp\SubstituteLetterVariables.tmp');
file_put_contents('C:\temp\SubstituteLetterVariables.tmp',$T);

$Word = new MSWord(0); // (1) makes word doc visible

$FirstTime='Y';
foreach ($Letter as $ThisFile)
   {
    if ($FirstTime=='Y')
      {$Word->Open($ThisFile);
//      $Word->InsertTable();
//due('stop this madness');
       $FirstTime='N'; }
    else
      $Word->InsertFile($ThisFile);
   }
    
$f=fopen('C:\temp\SubstituteLetterVariables.tmp','r');
set_time_limit(30000);
while(!feof($f))
   {$data=fgets($f);
    $I=strpos($data,'==');
    if ($I<1) die("SendDocumentToWord - invalid parameter $data");

    $Variable='('.substr($data,0,$I).')';
    $Value=substr($data,$I+2);
     //echo "<BR>$Variable-->$Value";
 
    while (StrLen($Value)>240)
       { //echo "<BR>1Word with $Variable =>".SubStr($Value,0,240);
       $Word->Replace($Variable,SubStr($Value,0,240).'($%)');
        $Value=SubStr($Value,240);
        $Variable='($%)';    }
     // echo "<BR>2Word with $Variable ==>".$Value;
    $Word->Replace($Variable,$Value);

       
    }
fclose($f);

$Word->SaveAs($FileName);
$Word->Quit();

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/vnd.msword");
header("Content-Disposition: attachment; filename=\"".basename($FileName)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".@filesize($FileName));
set_time_limit(0);
@readfile("$FileName") or die("File not found.");

return $BytesWritten;
exit;

}

?>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Tue Dec 05, 2006 8:11 pm
by John Cartwright
Can you start putting your code in tags please, until then you won't get much help around here :x

Posted: Tue Dec 05, 2006 10:05 pm
by mpiaser
I'm able to write PHP code to find/replace strings in a MSWord document but it won't change strings that are in Header/footers. It seems that I have to use something called STORIES to accomplish this but it is soooo confusing that I can't figure out how to do that. My code is below (it works except for header/footer replacements):

Code: Select all

class MSWord 
{ 
// Vars: 
var $handle; 

// Create COM instance to word 
function MSWord($Visible = false) 
{ 
$this->handle = new COM("word.application") or die("Unable to instanciate Word"); 
$this->handle->Visible = $Visible; 
} 

// Open existing document 
function Open($File) 
{ 
$this->handle->Documents->Open($File,0,1); 
} 

function Replace($what, $with) { 
$this->handle->Documents[1]->Activate(); 
$this->handle->ActiveDocument->Select(); 
// $this->handle->ActiveDocument->Sections(1)->Headers(1)->Range->StoryType; 
$this->handle->Selection->Find->ClearFormatting(); 
$this->handle->Selection->Find->Replacement->ClearFormatting(); 
$this->handle->Selection->Find->Execute($what, false, false, false, false, false, true, 1, false, $with, 2, false, false, false, false); 
// ActiveDocument.Sections(1).Headers(1).Range.StoryType 

} 

function InsertFile($name) { 
$this->handle->Documents[1]->Activate(); 
$this->handle->ActiveDocument->Select(); 
$this->handle->Selection->End(); 
$Last=$this->handle->ActiveDocument->Content->End(); 
$this->handle->Selection->SetRange($Last,$Last); 
// $this->handle->Selection->InsertBreak(7); // 7 means wdPageBreak 
$this->handle->Selection->InsertFile($name); 
// $this->handle->Documents[1]->Sections(1)->Footers(1)->Range->Text("inserted footer"); 
} 
function InsertTable() { 
// ************************************** 
//Set MyRange = ActiveDocument.Content 
//MyRange.Collapse Direction:=wdCollapseEnd 
$Last=$this->handle->ActiveDocument->Content->End(); 
$a=5; 
$this->handle->ActiveDocument->Tables->Add($Last,$a,'5'); 
//ActiveDocument.Tables.Add Range:=MyRange, NumRows:=6, _ 
// NumColumns:=10This example adds a table with three rows and five columns to a new document and then inserts data into each cell in the table. 

//Set newDoc = Documents.Add 
//Set myTable = newDoc.Tables.Add(Selection.Range, 3, 5) 
//With myTable 
//For x = 1 to 3 
// For y = 1 to 5 
// .Cell(x,y).Range.InsertAfter "Cell " & x & "," & y 
// Next y 
//Next x 
//.Columns.AutoFit 
//End With 

// ******************************************* 
} 
// Create new document 
function NewDocument() 
{ 
$this->handle->Documents->Add(); 
} 

// Write text to active document 
function WriteText( $Text ) 
{ 
$this->handle->Selection->Typetext( $Text ); 
} 

// Set page margins 
function SetMargins($top,$bottom,$left,$right) 
{ 
$this->handle->Documents[1]->PageSetup->TopMargin = "$top cm"; 
$this->handle->Documents[1]->PageSetup->BottomMargin = "$bottom cm"; 
$this->handle->Documents[1]->PageSetup->LeftMargin = "$left cm"; 
$this->handle->Documents[1]->PageSetup->RightMargin = "$right cm"; 
} 

// Number of documents open 
function DocumentCount() 
{ 
return $this->handle->Documents->Count; 
} 

// Save document as another file and/or format 
function SaveAs($File, $Format = 0 ) 
{ 
$this->handle->ActiveDocument->SaveAs($File, $Format); 
} 

// Save active document 
function Save() 
{ 
$this->handle->ActiveDocument->Save(); 
} 

// close active document. 
function Close() 
{ 
$this->handle->ActiveDocument->Close(); 
} 

// Get word version 
function GetVersion() 
{ 
return $this->handle->Version; 
} 

// get handle to word 
function GetHandle() 
{ 
return $this->handle; 
} 

// Clean up instance with word 
function Quit() 
{ 
if( $this->handle ) 
{ 
// close word 
$this->handle->Quit(); 

// free the object 
// $this->handle->Release(); 
$this->handle = null; 
} 
} 
}; 

function SendDocumentToWord($Letter,$FileName,$Type) 
{ 

include_once('SubstituteLetterVariables.php'); 


$Z=file_get_contents('C:/inetpub/wwwroot/SubstituteLetterVariables.txt'); 
$T=SubstituteLetterVariables($Z,'$Type','EPL'); 
if (is_file('C:\temp\SubstituteLetterVariables.tmp')) unlink('C:\temp\SubstituteLetterVariables.tmp'); 
file_put_contents('C:\temp\SubstituteLetterVariables.tmp',$T); 

$Word = new MSWord(0); // (1) makes word doc visible 

$FirstTime='Y'; 
foreach ($Letter as $ThisFile) 
{ 
if ($FirstTime=='Y') 
{$Word->Open($ThisFile); 
// $Word->InsertTable(); 
//due('stop this madness'); 
$FirstTime='N'; } 
else 
$Word->InsertFile($ThisFile); 
} 

$f=fopen('C:\temp\SubstituteLetterVariables.tmp','r'); 
set_time_limit(30000); 
while(!feof($f)) 
{$data=fgets($f); 
$I=strpos($data,'=='); 
if ($I<1) die("SendDocumentToWord - invalid parameter $data"); 

$Variable='('.substr($data,0,$I).')'; 
$Value=substr($data,$I+2); 
//echo "<BR>$Variable-->$Value"; 

while (StrLen($Value)>240) 
{ //echo "<BR>1Word with $Variable =>".SubStr($Value,0,240); 
$Word->Replace($Variable,SubStr($Value,0,240).'($%)'); 
$Value=SubStr($Value,240); 
$Variable='($%)'; } 
// echo "<BR>2Word with $Variable ==>".$Value; 
$Word->Replace($Variable,$Value); 


} 
fclose($f); 

$Word->SaveAs($FileName); 
$Word->Quit(); 

header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private",false); 
header("Content-Type: application/vnd.msword"); 
header("Content-Disposition: attachment; filename=\"".basename($FileName)."\";"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".@filesize($FileName)); 
set_time_limit(0); 
@readfile("$FileName") or die("File not found."); 

return $BytesWritten; 
exit; 

}