edit docx file using phpword - php
is it possible to edit existing docx file using phpword?
i want to add footer text to my existing docx file.
there are lot of examples but those examples are creating the doc file from scratch not editing the file
can someone link to me an example? thank you
just like this.
<?php
require_once 'PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add header
$header = $section->createHeader();
$table = $header->addTable();
$table->addRow();
$table->addCell(4500)->addText('This is the header.');
$table->addCell(4500)->addImage('_earth.jpg', array('width'=>50, 'height'=>50, 'align'=>'right'));
// Add footer
$footer = $section->createFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));
// Write some text
$section->addTextBreak();
$section->addText('Some text...');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('HeaderFooter.docx');
?>
Yes you can edit.
From documentation
PHPWord is a library written in pure PHP that provides a set of
classes to write to and read from different document file formats. The
current version of PHPWord supports Microsoft Office Open XML (OOXML
or OpenXML), OASIS Open Document Format for Office Applications
(OpenDocument or ODF), and Rich Text Format (RTF).
Actually this is the procedure
Load our existing file as template.
Edit
Save
From the Documentation, I found an example,
<?php
include_once 'Sample_Header.php';
// Template processor instance creation
echo date('H:i:s'), ' Creating new TemplateProcessor instance...', EOL;
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Sample_07_TemplateCloneRow.docx');
// Variables on different parts of document
$templateProcessor->setValue('weekday', htmlspecialchars(date('l'))); // On section/content
$templateProcessor->setValue('time', htmlspecialchars(date('H:i'))); // On footer
$templateProcessor->setValue('serverName', htmlspecialchars(realpath(__DIR__))); // On header
// Simple table
$templateProcessor->cloneRow('rowValue', 10);
$templateProcessor->setValue('rowValue#1', htmlspecialchars('Sun'));
$templateProcessor->setValue('rowValue#2', htmlspecialchars('Mercury'));
$templateProcessor->setValue('rowValue#3', htmlspecialchars('Venus'));
$templateProcessor->setValue('rowValue#4', htmlspecialchars('Earth'));
$templateProcessor->setValue('rowValue#5', htmlspecialchars('Mars'));
$templateProcessor->setValue('rowValue#6', htmlspecialchars('Jupiter'));
$templateProcessor->setValue('rowValue#7', htmlspecialchars('Saturn'));
$templateProcessor->setValue('rowValue#8', htmlspecialchars('Uranus'));
$templateProcessor->setValue('rowValue#9', htmlspecialchars('Neptun'));
$templateProcessor->setValue('rowValue#10', htmlspecialchars('Pluto'));
$templateProcessor->setValue('rowNumber#1', htmlspecialchars('1'));
$templateProcessor->setValue('rowNumber#2', htmlspecialchars('2'));
$templateProcessor->setValue('rowNumber#3', htmlspecialchars('3'));
$templateProcessor->setValue('rowNumber#4', htmlspecialchars('4'));
$templateProcessor->setValue('rowNumber#5', htmlspecialchars('5'));
$templateProcessor->setValue('rowNumber#6', htmlspecialchars('6'));
$templateProcessor->setValue('rowNumber#7', htmlspecialchars('7'));
$templateProcessor->setValue('rowNumber#8', htmlspecialchars('8'));
$templateProcessor->setValue('rowNumber#9', htmlspecialchars('9'));
$templateProcessor->setValue('rowNumber#10', htmlspecialchars('10'));
// Table with a spanned cell
$templateProcessor->cloneRow('userId', 3);
$templateProcessor->setValue('userId#1', htmlspecialchars('1'));
$templateProcessor->setValue('userFirstName#1', htmlspecialchars('James'));
$templateProcessor->setValue('userName#1', htmlspecialchars('Taylor'));
$templateProcessor->setValue('userPhone#1', htmlspecialchars('+1 428 889 773'));
$templateProcessor->setValue('userId#2', htmlspecialchars('2'));
$templateProcessor->setValue('userFirstName#2', htmlspecialchars('Robert'));
$templateProcessor->setValue('userName#2', htmlspecialchars('Bell'));
$templateProcessor->setValue('userPhone#2', htmlspecialchars('+1 428 889 774'));
$templateProcessor->setValue('userId#3', htmlspecialchars('3'));
$templateProcessor->setValue('userFirstName#3', htmlspecialchars('Michael'));
$templateProcessor->setValue('userName#3', htmlspecialchars('Ray'));
$templateProcessor->setValue('userPhone#3', htmlspecialchars('+1 428 889 775'));
echo date('H:i:s'), ' Saving the result document...', EOL;
$templateProcessor->saveAs('results/Sample_07_TemplateCloneRow.docx');
echo getEndingNotes(array('Word2007' => 'docx'));
if (!CLI) {
include_once 'Sample_Footer.php';
}
Now see the lines of code given below , how to access existing header and footer
$headers = $section->getHeaders();
$header1 = $headers[1]; // note that the first index is 1 here (not 0)
$elements = $header1->getElements();
$element1 = $elements[0]; // and first index is 0 here normally
// for example manipulating simple text information ($element1 is instance of Text object)
$element1->setText("adding text here - old part: " . $element1->getText());
$footers = $section->getFooters(); // to access footer
You can find more examples here . If you want to add more styles, please read this page. And you can also see some recipes in their documentation.
In the footer of your file(template) docx, you can put a variable like this ${var1}.
Open a file as template with "TemplateProcessor".
$templateObject = new TemplateProcessor($filename);
Replace var1 variable in your file
$templateObject->setValue('var1', 'test');
Transform your template into a PhpWord
$fileName = $templateObject->save();
$phpWordObject = IOFactory::load($fileName);
unlink($fileName);
return $phpWordObject;
Save/Render your phpWord instance
// create the writer
$writer = $this->wordService->createWriter($phpWordObject, 'Word2007');
// create the response
$response = $this->wordService->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'export.docx'
);
$response->headers->set('Content-Type', 'application/msword');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
Might be useful for Laravel 5 users. You can use this in your controllers.
public function wordDocumentFromWordTemplate() {
$templateFile = public_path('templates') . '/template-file.docx';
$templateObject = new TemplateProcessor($templateFile);
$templateObject->setValue('var1', 'Text for var1');
$wordDocumentFile = $templateObject->save();
$headers = [
'Content-Type' => 'application/msword',
'Cache-Control' => 'max-age=0'
];
return response()->download($wordDocumentFile, 'result.docx', $headers);
}
Related
PHPWord: fill a template and output .pdf
I'm using a PHPWord to create word documents. To do so I'm using layouts: $template = new \PhpOffice\PhpWord\TemplateProcessor($this->config->application->fileTemplateFolder.'invoice.docx'); $template->setValue('date', date("F jS, Y")); $temp_file = tempnam(sys_get_temp_dir(), 'invoice_'); $temp_file .= '.docx'; $template->saveAs($temp_file); It works fine. My problem is to create the a PDF file. Here is how I trying to create the file: $path = '/Users/andredx/Projects/x/vendor/dompdf/dompdf'; require_once __DIR__ . '/../../vendor/dompdf/dompdf/autoload.inc.php'; \PhpOffice\PhpWord\Settings::setPdfRendererPath($path); \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF'); $temp_doc = \PhpOffice\PhpWord\IOFactory::load($temp_file); // this line executes $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($temp_doc , 'PDF'); // this one get' my an error which I cannot see $xmlWriter->save('/Users/andredx/Projects/x/_test.pdf', TRUE); unlink($temp_file); I can't figure out what I'm doing wrong. Maybe the path of the converter, but I'm trying to insert the path in many ways and it is not working. Relevant info: the document has images and tables. Can you help me to find out what I'm doing wrong? Thanks
Saving DOMPDF to specified directory and then sending as email
Hi I am trying to save dompdf to a specific directory in codeigniter file and then taking the saved file and sending it as a email. I am using codeigniter to do all this work. Here is the function. public function generateCreditAggreement(){ $this->load->helper('file'); require_once(APPPATH.'third_party/dompdf/dompdf_config.inc.php'); $pdfroot = dirname(dirname(__FILE__)); $pdfroot .= '/third_party/pdf/'; $dompdf = new Dompdf(); $msg = $this->load->view('credit_agreement_view', '', true); $html = mb_convert_encoding($msg, 'HTML-ENTITIES', 'UTF-8'); $dompdf->load_html($html); $paper_orientation = 'Potrait'; $dompdf->set_paper($paper_orientation); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Download folder // $dompdf->stream('document.pdf'); //save the pdf file on the server $pdf_string = $dompdf->output(); file_put_contents($pdfroot, $pdf_string ); } The error I am getting is that Message: file_put_contents(C:\Apache24\htdocs\faceloan\faceloan\application/third_party/pdf/): failed to open stream: No such file or directory But the directory does exist , and the path name is right.
The path .../third_party/pdf/ is probably a directory and not a file. PHP can't save your data as a directory. Specify a filename as first parameter of file_put_contents(), e.g. third_party/pdf/my_document.pdf.
mPDF - No PDF generated when called from within another function
I have a mail_merge function (using cakephp) which when called directly from the browser e.g. domain.com/contacts/mail_merge will generate the PDF and save it to the server as needed with the database mapped fields. When however I try to call this mail_merge function from another function. e.g. $this->mail_merge($cond, 1); The PDF won't generate. The database fields are still coming though to the mail_merge function so it's not this issue. Any idea why this might be happening? I have updated my code below to now include a simple generated txt file with the code I am trying to put onto the PDF and this works so there is simply something about mPDF that won't generate a PDF when called from a function. Thanks My mail_merge function is as follows: // FUNCTION GENERATE MAIL MERGE - mPDF // --------------------------------------------------------------> function mail_merge($conditions=NULL, $mail_merge_id=1) { // REMOVE THE STANDARD LAYOUT // ------------------------------------------------------> $this->layout = null; // GET THE CONTACTS // -------------------------------------------------------------> $contacts = $this->Contact->Card->find('all', array( 'limit' => 10, //'fields' => $fields, 'contain' => array('Contact', 'Prospect', 'SaleDetail'), 'conditions' => $conditions )); $this->set('contacts', $contacts); // GE THE CONTENTS // ------------------------------------------------------------> $this->loadModel('MailMerge'); $content = $this->MailMerge->find('first', array( 'conditions' => array('MailMerge.id' => $mail_merge_id), 'fields' => array('MailMerge.description') )); $this->set('content', $content); // initializing mPDF // ---------------------------------------------------------------------------> $this->Mpdf->init(); // RENDER THE VIEW AND SET AS A VARIABLE TO WRITE THE HTML // ---------------------------------------------------------------------------> $response = $this->render('mail_merge'); $thebody = $response->body(); $this->Mpdf->WriteHTML($thebody); // setting filename of output pdf file // ---------------------------------------------------------------------------> $thefilename = "mail_merge_".date("d.m.Y_His").".pdf"; $this->Mpdf->setFilename(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilename); // setting output to I, D, F, S // ---------------------------------------------------------------------------> $this->Mpdf->setOutput('F'); // TEMP - CREATE TXT FILE ON THE SERVER // ------------------------------------------------------------------------> $thefilenametxt = "mail_merge_".date("d.m.Y_His").".txt"; $ourFileHandle = fopen(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilenametxt, 'w'); fwrite($ourFileHandle, $thebody); fclose($ourFileHandle); return $thefilename; } // END MAIL MERGE
I discovered the issue lied with the setOutput function of the component. When I changed: $this->Mpdf->setFilename(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilename); $this->Mpdf->setOutput('F'); To $this->Mpdf->Output(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilename, 'F'); it worked as needed.
File only downloading when opened in new window/tab
I have a function that creates different file types depending on a variable, I have it generating an XML, but when I click the link to the page to do so (XML), nothing happens. If I click to open it in a new tab or manually enter the url in the title bar then the file will download as I want it to. function asset($asset_id, $display = ''){ $this->load->model('model_asset'); $asset = $this->model_asset->get_by_id($asset_id, true); switch($display) { case 'xml': $this->load->helper('array_to_xml_helper'); $asset_arr = get_object_vars($asset); $filename = $asset->title .'-'. $asset->subtitle . '.xml'; $xml = Array2XML::createXML('asset', $asset_arr); header ("Content-Type:text/xml"); header('Content-Disposition: attachment; filename="'. $filename .'"'); echo $xml->saveXML(); break; } } How can I make this work with dynamically generated files (I'm using a arraytoxml utility function I found here)
You can try to set file in attachement Add this to your headers : Content-disposition: attachment filename=huge_document.pdf
Edit .doc or .docx file using php
I have to modify the uploaded .doc or .docx file in php. I googled but i only found how to read that. I want the word file as it is and put text at the bottom of that MS Word file at run time. How is this possible anyone know please reply or give me example script. Thanks,
I'm the developer of PHPWord. You can use the PHPWord_Template Class to open an existing DOCX File and then replace some text marks with your individual text. Alternatively you can open the DOCX file with the ZipArchive extension and then read/write every xml File (document.xml, header.xml, footer.xml, ...) you want. This method is nothing else than the PHPWord_Template class. ;)
You can use PHPWord.
I have same requirement for Edit .doc or .docx file using php and i have find solution for it. And i have write post on It :: http://www.onlinecode.org/update-docx-file-using-php/ if($zip_val->open($full_path) == true) { // In the Open XML Wordprocessing format content is stored. // In the document.xml file located in the word directory. $key_file_name = 'word/document.xml'; $message = $zip_val->getFromName($key_file_name); $timestamp = date('d-M-Y H:i:s'); // this data Replace the placeholders with actual values $message = str_replace("client_full_name", "onlinecode org", $message); $message = str_replace("client_email_address", "ingo#onlinecode.org", $message); $message = str_replace("date_today", $timestamp, $message); $message = str_replace("client_website", "www.onlinecode.org", $message); $message = str_replace("client_mobile_number", "+1999999999", $message); //Replace the content with the new content created above. $zip_val->addFromString($key_file_name, $message); $zip_val->close(); }
You only replace the predefined variables. In the following code https://github.com/PHPOffice/PHPWord I also did this problem in phpword using the following code if(!file_exists('file/word.docx')){ $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('demo.docx'); $templateProcessor->setValue('name', 'Akbarali'); $templateProcessor->setValue('time','13.02.2021'); $templateProcessor->setValue('month', 'January'); $templateProcessor->setValue('state','Uzbekistan'); $templateProcessor->saveAs('file/word.docx'); } This will change the words in the demo.docx file. The new file is then saved in the word.docx file folder. you can define variables in the form of ${name} in the demo word file. that is, ${name}, ${time}, ${month} and ${state}
In this post we will show you How to update docx file using php, hear for How to update docx file using php we will give you demo and example for implement. Hear we will show you how to Edit .doc or .docx file using php. Hear we use “client_full_name”, “client_email_address”, “date_today”, “client_website”, “client_mobile_number” in .doc or .docx files $template_file_name = 'template.docx'; $rand_no = rand(111111, 999999); $fileName = "results_" . $rand_no . ".docx"; $folder = "results_"; $full_path = $folder . '/' . $fileName; try { if (!file_exists($folder)) { mkdir($folder); } //Copy the Template file to the Result Directory copy($template_file_name, $full_path); // add calss Zip Archive $zip_val = new ZipArchive; //Docx file is nothing but a zip file. Open this Zip File if($zip_val->open($full_path) == true) { // In the Open XML Wordprocessing format content is stored. // In the document.xml file located in the word directory. $key_file_name = 'word/document.xml'; $message = $zip_val->getFromName($key_file_name); $timestamp = date('d-M-Y H:i:s'); // this data Replace the placeholders with actual values $message = str_replace("client_full_name", "onlinecode org", $message); $message = str_replace("client_email_address", "ingo#onlinecode", $message); $message = str_replace("date_today", $timestamp, $message); $message = str_replace("client_website", "www.onlinecode", $message); $message = str_replace("client_mobile_number", "+1999999999", $message); //Replace the content with the new content created above. $zip_val->addFromString($key_file_name, $message); $zip_val->close(); } } catch (Exception $exc) { $error_message = "Error creating the Word Document"; var_dump($exc); }
Try having a look at http://www.tinybutstrong.com/ as it can create and edit Word documents, we use it in a mail merge style for generating invoices in doc and pdf.
Some of these answers dont contain the full steps so here is what ive done: Create your word document. With in this document anything you want to replace with PHPWORD mark it like this -> ${variable_name} so for example ${value1} $file = "docs/input/word/source.docx"; $output_file = "docs/input/word/modified.docx"; $PHPWord = new \PhpOffice\PhpWord\PhpWord(); $document = $PHPWord->loadTemplate($file); $document->setValue('value1', 'Enter Your Text Here'); $document->saveAs($output_file);