Loading A .docx with PHPWord - php

I am attempting to load a .docx file with PHPWord, set a value in it, and save the file. The issue is the saved file comes out as a blank word document, 7kb in size. The document I put in is large and has multiple pages. Obviously its not loading it right. My code is as follows:
$PHPWord = new \PhpOffice\PhpWord\PhpWord();
$document = $PHPWord->loadTemplate('Resources/documents/test.docx');
$document->setValue('theDate', '2014-07-25');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$xmlWriter->save("php://output");
I have tried with multiple test.docx files of different sorts, but the output file is always blank.

I was able to solve this issue with what Progi1984 linked, calling $document->saveAs() and then reading the file to download it. Thank you :)

Related

Writing into Excel file using PhpSpreadsheet

I have a php code that is triggered whenever a user clicks a determined button. That code basically creates a new directory and a new Excel File inside that same dir. My goal is to write into that excel file. I have the following code (which is not working, btw):
$filename = 'moldes/VLMOLDES_'.$id.'/Orcamento161.xlsm';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A18')->setValue('3');
Everything but writing in the file is working as expected. When I click the button, it opens a blank page but nothing happens! I've tried a lot of different ways but I'm a noob in phpSpreadSheets. How can I write in a specific cell in that file?
You're missing the following - you need to save the file at the end of your code or the changes won't be reflected in the file.
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save('moldes/VLMOLDES_'.$id.'/Orcamento161.xlsm');
Also, it may be preferred to use:
$worksheet->setCellValue('A18', '3');

Appending PDF Files in PHP with Base64

I have a series of base64 PDF Files that I would like to merge together. Currently I am using file_get_contents() and with PHPMailer can attach each of them separately.
$woFile = file_get_contents($url);
$invoiceFile = file_get_contents($invPDF64);
$tsFile = file_get_contents($tsPDF64);
...
$mail->AddStringAttachment($woFile, "1.pdf", "base64", "application/pdf");
$mail->AddStringAttachment($invoiceFile, "2.pdf", "base64", "application/pdf");
$mail->AddStringAttachment($tsFile, "3.pdf", "base64", "application/pdf");
All the examples I've seen online such as FPDF require the file to be locally downloaded, at least from what I saw. Is there a way to append each of these PDF files into one, and then have that attached to the email?
Thanks in advance!
I'm not sure if you specifically need to merge the PDFs into one PDF, or if you just want one file. Here are options for both:
If you want to merge all PDFs into a single PDF file, then this is a duplicate question. You mention not wanting to have a local file, but this may be an unreasonable constraint (e.g., memory issues with large PDFs). Use temporary files as appropriate and clean up after yourself.
If you just want a single file, consider putting the files into a ZIP archive and sending that. You might also like the ZipStream library for this purpose. Here's some minimal code using the native library:
$attachmentArchiveFilename = tempnam('tmp', 'zip');
$zip = new ZipArchve();
# omitting error checking here; don't do it in production
$zip->open($attachmentArchiveFilename, ZipArchve::OVERWRITE);
$zip->addFromString('PDFs/first.pdf', $woFile);
$zip->addFromString('PDFs/second.pdf', $invoiceFile);
$zip->addFromString('PDFs/third.pdf', $tsFile);
$zip->close();
$mail->addAttachment($attachmentArchiveFilename, 'InvoicePDFs.zip');
# be sure to unlink/delete/remove your temporary file
unlink( $attachmentArchiveFilename );

addObject() function is not working with .docx file in php

I am trying to attach(embedding) a .docx file to word document using phpword addObject() function, it's attaching file but while clicking on attached file it's not opening. If i do it for .doc file it's opening the attached file. I am using phpword library.
<?php
require_once '../PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add text elements
$section->addText('You can open this OLE object by double clicking on the icon:');
$section->addTextBreak(2);
// Add object
$section->addObject('Test.docx');
//if i use $section->addObject('Test.doc'); it's opening attached file. here Test.doc is word97-2003 format.
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Object.docx');
?>
Multiple issues were already logged for this, but no solution proposed for the issue yet :-(
addObject() function is not working with .docx file, it's working with .doc(word97-2003) file
Add Object Issue
Unable to open embedded object

Making DomPDF as my pdf writer for phpWord

I used laravel for my app and the dompdf is found in:
../vendor/dompdf/dompdf
What I wanted to achieve is to convert my .docx file (Microsoft Word) to .pdf file. The docx file was generated by phpWord by loading the template file and replacing the values.
Here's the snippet:
// Get the absolute path of the template file
$wordTemplatePath = $this->getDocumentTemplatePath('resignation.docx');
// Load the template file
$document = $this->phpWord->loadTemplate($wordTemplatePath);
// This will be filled with data
$wordData = []
.... Process to fill the data .....
// Replace value to actual word document
$this->setTemplateValues($wordData, $document);
// Generate its filename
$file = $this->generateFileName('Retirement-Certificate.docx', $id);
// Fetch the absolute path to save the document
$filepath = $this->getSavePath($file);
// Save the word document
$document->saveAs( $filepath );
After that, a .docx file will be generated. I wanted to make a PDF version of that as well. so I search and found this code snippet and added in my code:
\PhpOffice\PhpWord\Settings::setPdfRendererPath('../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererName('DOMPDF');
//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load($filepath);
//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');
But I got this error:
{"error":
{"type":"PhpOffice\\PhpWord\\Exception\\Exception","message":"PDF rendering library or library path has not been defined.",
"file":"C:\\xampp\\htdocs\\vagrant\\vendor\\phpoffice\\phpword\\src\\PhpWord\\Writer\\PDF.php",
"line":49}}
How would I make DomPDF as my pdf writer for PHPWord? I can't find any other options so I ask here. I hope you can help me. Thanks!
You must set it to the absolute path.
Put this into your bootstrap.php file.
define('PHPWORD_BASE_DIR', realpath(__DIR__));
This is your call:
$domPdfPath = realpath(PHPWORD_BASE_DIR . '/../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load($filepath);
//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');
I think #Franz Holzingers answer is right on point except that the version of PHP word that I installed today requires the renderer name to be DomPDF. The method fails if it is all caps as shown. Also the version that I installed to day uses a configuration file so while the explicit calls work, if you place them after the configuration file loads, they are overwritten if you place them before the configuration loads. I propose a simpler answer is to locate the file "phpword.ini.dist" located in the directory above "src" in the phpword install directories; edit the line for the DomPDF directory to show where you installed DomPDF and then save the file in the same directory but under the name phpword.ini. Now the configuration loader will perform the calls that Frank documented for you. If you enter the path to DomPDF incorrectly, you get no warning but you can test that it installed correctly using the method \PhpOffice\PhpWord\Settings::getPdfRendererPath(domPdfPath); If the return from that method is empty, it means that the path name you specified in the configuration file did not exist. Note that the loader does not check that the path contains DomPDF, only that the path exists.
It is worth noting that at this time, phpword supports three PDF rendering engines. Any of the three can be configured in the ini file mentioned above by providing the path to the installation and setting the name of the PDF renderer to one of these values (case sensitive): DomPDF, TCPDF or MPDF. DomPDF is recommended and the default but it appears in the code that if you have an investment in or a preference for one of the others, you can used it with phpword.

Loading macros from .XLS file

I have an .XLS file with macros I have to modify and keep the macros and images it contains. I can open the file and modify the cell data but it loses the macros and images. I tried to search for the problem on Google but I only found solutions for .xlsm files. I hope it's possible to keep the macros in an .xls file too. Here is my code for the opening and saving:
include_once libraries_get_path('PHPExcel').'/PHPExcel.php';
include_once libraries_get_path('PHPExcel').'/PHPExcel/IOFactory.php';
$template = PHPExcel_IOFactory::load('private://xls/form_template.xls');
$template->setActiveSheetIndex(0);
// Modifying the cells data here...
$objWriter = PHPExcel_IOFactory::createWriter($template, 'Excel5');
$objWriter->save('sites/default/files/'.$filename);
It's a really important function in the project and the customer needs it ASAP.

Categories