Solved

php  populate locked Word template form

Posted on 2011-09-03
14
567 Views
Last Modified: 2012-05-12
I have a ms Word doc template that is locked via password so I can't get to the field properties.  I don't have access to the password either.

I want to be able to populate the fields via a PHP form so I can capture the field data into a MySQL database and then also produce the word document but with the fields filled out so I can then print it.

Let me just say that LiveDocX is not a viable option because of security concerns for the content of the form.  All processing has to stay in our intranet.
0
Comment
Question by:yoshcomputers
  • 8
  • 4
  • 2
14 Comments
 

Author Comment

by:yoshcomputers
Comment Utility
Here is the actual file I want to be able to populate via PHP.  I have saved it as an XML file and can get to the field names, but not sure how to populate it back with values. OCFS-8018-Service-Summary-Form.dot
0
 
LVL 76

Accepted Solution

by:
GrahamSkan earned 500 total points
Comment Utility
I don't know PHP, but if you can use COM and hence the Word Object Model, you don't need to remove forms protection to fill in the forms.

In VBA, it is:
objDoc.FormFields("Text1").Result = "Some Text"
and
objDoc.FormFields("Check1").CheckBox.Value = True

If you don't know the field names, you could use the numerical index instead:
objDoc.FormFields(1).Result = "Some Text"

And you could list the names as in this VBA macro

Sub ListFormFieldNames
    Dim i as Integer
    Dim ffld as FormField

    For i = 1 to ActiveDocument.FormFields.Count
         Debug.print i, ffld.Name
    Next i
End Sub

Finally, because forms protection is a convenience and not a security measure, you can get an unprotected copy of the document. In the Word application, create a blank document and 'Insert' the form document. In Word 2007, that is done by:
Insert tab> Text group> Object > Text from file...
As I recall, in earlier Word versions, you go via the Insert menu item on the standard toolbar.




 
0
 
LVL 31

Expert Comment

by:Helen_Feddema
Comment Utility
Here is some code that works with a document made from a partially locked template, unprotects the appropriate section to update doc properties filled from VBA Automation code, and then reapplies protection  If there is a password, it is set using the Password argument:
With appWord
   .Visible = True
   .Selection.WholeStory
   .Selection.Fields.Update
   Debug.Print "Going to save as " & strSaveNamePath
   .ActiveDocument.SaveAs strSaveNamePath
   .Activate
   .Selection.HomeKey unit:=wdStory
   If strWordTemplate = "Needs Protection.dotx" Then
       doc.Sections(1).ProtectedForForms = False
   End If
End With

If strWordTemplate = "Needs Protection.dotx" Then
   'Protect section with form fields for user data entry
   doc.Sections(1).ProtectedForForms = True
   doc.Protect Password:="", Type:=wdAllowOnlyFormFields
   doc.Sections(2).ProtectedForForms = False
End If

Open in new window

0
 
LVL 31

Expert Comment

by:Helen_Feddema
Comment Utility
This particular document had both DocProperty fields filled from Access, and form fields, to be filled in by the user.
0
 

Author Comment

by:yoshcomputers
Comment Utility
I was able to unprotect the document and can get to the bookmarked names of the fields.  But I still don't know how to populate them with PHP.  I would need examples for PHP, not VBA.  I would prefer not to use a COM because it is very likely the servers I am dealing with won't have Microsoft Office installed.  But even if all I could get was a COM example, I would be happy.

Here are 5 of the Bookmarknames for the fields:
Text1, Text2, Text3, Check17, Check18

An example to include populating the fields and having Check17 and Check18 mark as true and save the file with a new filename would award you all the points.
0
 

Author Comment

by:yoshcomputers
Comment Utility
OK...moving right along.  I figured out how to edit the Text fields via a COM interface (still not my preference)...but I haven't been able to get checkboxes to show they are checked.  I have tried values of true, checked, and even 'X' but it just displays text next to the checkbox instead of showing the checkbox is checked.

I wonder if it is a factor of the document has to be in unprotected mode to be able to edit the fields.  However if I put it in protected mode, I get an error saying I can't access the fields because the document is protected.
0
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
I think that everyone is on a learning curve here. There definitely shouldn't be any restriction on updating form fields while protection is on. That is the whole point of forms protection. In fact it is better to keep protection on when updating the form field contents: when protection is re-enabled there is a specific argument to keep the previous form field contents.

Does PHP have an equivalent of the VB boolean values of True and False? Perhaps you should show the code that you are using, so that any PHP as well as Word experts can pool resources and see what methods you are trying.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:yoshcomputers
Comment Utility
Fair enough comment form Graham.  I am including the code for accessing the file and then writing the Text values.  I have a suspicion that the Range->Text is the problem with making a checkbox checked instead of putting the textual value next to it.  But I don't know what term to try.  I have tried Range->Value and Range->Checked but it reports an error 'Unable to lookup `Checked' or 'Value'

com_load_typelib('Word.Application');

$word = new COM("word.application") or die("Unable to instantiate Word");

// use like this. Place your's word file in C drive
$word->Documents->Open('C:/Files/Form1818_g.doc');
echo $current_date = date("m/d/Y");

$tim= date("Y-m-d");

$info_array=array(  "Text1"      => "Yosh",
                    "Text2" => "$tim" ,
                    "Text3"   => "sparsh" ,
                    "Check17"   => True,
                    "Check18"   => 'Checked') ;

foreach($info_array as $bookmarkname => $re)
    {
        $objBookmark = $word->ActiveDocument->Bookmarks($bookmarkname);
		echo $bookmarkname."<br>";
        $range = $objBookmark->Range;
	echo $range->Text = $re ;
    }

$new_file = "C:/Files/Form1818_newedit.doc";

$word->Documents[1]->SaveAs($new_file);

$word->ActiveDocument->Close(false);

$word->Quit();
$word = null;

Open in new window

0
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
Hmm.

Even VB programmers are tempted to use the form field's bookmark and try to extract the data from it.

However the .Result method of the formfield object is actually designed to get the relevant information. This is because the text of range of its bookmark includes extra unneeded text that would have to be stripped off with a complex algorithm.

Thought I'm sure that it is possible, I can't see how the PHP code does exactly what we would do in VB. For instance, in VB, the For Each construct walks through the whole collection, and not through a particular named subset.

This my best guess at shoehorning my code into PHP. I've used an asterisk-> 'FormFields(*)' to wildcard the list, so that it will include all items.

foreach($ffld)
    {
        $ffld = $word->ActiveDocument->FormFields(*);
            echo $ffld.Name"<br>";
      echo $ffld->Result = $re ;
    }
0
 

Author Comment

by:yoshcomputers
Comment Utility
Well,
I figured it out myself and here is the workaround code I have in place for now.
In order to access a Checkbox state you have to access it via the FormFields Object, not the Bookmarks Object.

If the Type is 'TextInput' You can access the 'Results' property to keep the data in an input field or you could use 'Range->Text' to just display the data.
For Type is CheckBox you have to then access the CheckBox Value state to toggle it from True or False.

The following code is using the $info_array to capture the name of the Field/Bookmark and its value as described in the prior code example above.
foreach($info_array as $bookmarkname => $re)
    {
        $objFormFields = $word->ActiveDocument->FormFields($bookmarkname);
		echo "<br>".$bookmarkname." = ".$objFormFields->Type;
		if ($objFormFields->Type == 70){ //Type 70 is 'TextInput' , Type 71 is 'CheckBox'
			echo $objFormFields->Result = $re ;
		} else {
			echo $objFormFields->CheckBox->Value = $re;
		}

    }

Open in new window

0
 

Author Comment

by:yoshcomputers
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 0 points for yoshcomputers's comment http:/Q_27290437.html#36482010

for the following reason:

I ultimately had to dig through Microsofts MSDN library to find the answer I needed<br /><a href="http://msdn.microsoft.com/en-us/library" target="_blank">http://msdn.microsoft.com/<wbr />en-us/libr<wbr />ary</a>
0
 

Author Comment

by:yoshcomputers
Comment Utility
On second review of the support answers, I realize that GrahamSkan had the right terminology but because it was in VBA and didn't specify I was using the wrong Object (the Bookmark object)  I didn't realize he was showing me the correct object to use (the FormFields object).  I just thought it was a different term for VBA vs PHP.

GrahamSkan should get 300 points.  I would have been able to award all of it had it been more clear about which object to use and that the protection problem I was having was because I was trying to access the Bookmark->Range->Text data instead of the FormFields->Results.  Also didn't address the CheckBox value issue I discovered on my own.
0
 

Author Closing Comment

by:yoshcomputers
Comment Utility
Keep in mind the code that I finally ended up using at the bottom of the results is correct for PHP
0
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
Thanks. Yes, it is sometimes hard to know what to be explicit about, and what to take as read.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Shortcuts in Word Just the other day I had a training for Microsoft and they wanted me to show how well the new Windows and Office behaved on a touch device, which by the way is great, but it was only then that I realized that using keyboard shortc…
Using Word 2013, I was experiencing some incredible lag when typing.  Here's what worked for me....
This video shows and describes the main difference between both orientations in Microsoft Word. Viewers will understand when to use each orientation and how to get the most out of them.
This Experts Exchange video Micro Tutorial shows how to tell Microsoft Office that a word is NOT spelled correctly. Microsoft Office has a built-in, main dictionary that is shared by Office apps, including Excel, Outlook, PowerPoint, and Word. When …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now