Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to save Template as PDF #311

Open
ghost opened this issue Jul 9, 2014 · 29 comments
Open

How to save Template as PDF #311

ghost opened this issue Jul 9, 2014 · 29 comments

Comments

@ghost
Copy link

ghost commented Jul 9, 2014

I've created an ivoice by using a Template.
How can I save this to PDF?
When using \PhpOffice\PhpWord\IOFactory::createWriter($doc, 'PDF');
It says $doc is not an instance of PHPWord. How do I get back the PHPWord object?


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

@nicolasidweb
Copy link

Hi,

You need to define your PDF writer.

First, download TCPDF or a library as proposed in PhpWord (DomPDF, MPDF...).

Define the path of this library :

\PhpOffice\PhpWord\Settings::setPdfRendererPath('path/to/tcpdf');
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

You need to save your template as docx and then open it with IOFactory and finally save it.

$phpWord = new \PhpOffice\PhpWord\PhpWord();

//Open template and save it as docx
$document = $phpWord->loadTemplate('yourtemplate.docx');
$document->saveAs('temp.docx');

//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load('temp.docx'); 

//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');  

@franzholz
Copy link

I start the PHP example Sample_07_TemplateCloneRow.php. I have added the following lines at the end of the sample's PHP code.
PHP loads the 'Sample_07_TemplateCloneRow.docx' and stores it back in PDF format. I have tried all 3 PDF converters. MPDF, DOMPDF and TCPDF. The generated PDF files contain all the texts on the right positions. However all the table lines of the cell borders and frames are missing in the generated PDF files. Is this a bug anywhere or are does PHPWord only offer the conversion of the texts inside of the DOCX files without the lines?

...
$phpWord = \PhpOffice\PhpWord\IOFactory::load(PATH_site . $name);
$rendererName = \PhpOffice\PhpWord\Settings::PDF_RENDERER_MPDF; //PDF_RENDERER_DOMPDF   PDF_RENDERER_TCPDF
$rendererLibraryPath = PATH_site . $generationConf['handleLib.']['rendererLibrary.']['path'];
\PhpOffice\PhpWord\Settings::setPdfRenderer($rendererName, $rendererLibraryPath);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF');
$objWriter->save('Sample_07_TemplateCloneRow.pdf');

@superjj74
Copy link

i've problems with pdf writer.. the pdf generated do not contain any images or layout position of source document.
i try the 3 writes and the result is the same, maybe the reader do not load correctly the source doc?

@ghost
Copy link
Author

ghost commented Nov 2, 2014

Hi, cannot see any images either, or page breaks or table cell background colours.
Producing a docx followed by a pdf as follows:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save($finalnamedocx);

\PhpOffice\PhpWord\Settings::setPdfRendererPath('tcpdf_min');
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord , 'PDF');
$xmlWriter->save($finalname.'.pdf');

Can anyone advise?

@gplaza
Copy link

gplaza commented Nov 28, 2014

same problem here : cannot see any images either, or page breaks or table cell background colours.

@adailtonjunior
Copy link

Me too! Has anybody a solution for this problem? Up

@ghost
Copy link
Author

ghost commented Feb 5, 2015

The answer is no. I've asked half a dozen colleagues and gurus to look into it with me and it just won't work. Ended up producing the whole file again with tcpdf, which sucks cause it cannot look exactly the same.

@janssenMA
Copy link

Really out of the box thinking is just to let MS Word open the file and save it as a PDF.
You'll need to install MS Word on your server, enable the COM extension in your php.ini (extension=php_com_dotnet.dll), and make sure the user that runs the Apache server has permissions to read / write in the folder.

Hope this helps someone:

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

// Open file
$readOnly = true;
$wdOpenFormatAuto = 0;
$msoEncodingAutoDetect=50001;
$word->Documents->Open( $sourcePath, false, $readOnly, false, "", "", true,"", "", $wdOpenFormatAuto, $msoEncodingAutoDetect);

// Save as PDF
$XlFixedFormatTypePDF = 17;
$word->ActiveDocument->ExportAsFixedFormat($destinationPath, $XlFixedFormatTypePDF, false, 0, 0, 0, 0, 7, true, true, 2, true, true, true);

@donquick
Copy link

Right - well that's several hours of my life I'm not going to get back then. Can anybody help me understand this, please? Can i assume that if you are going to go to the trouble of making a word file programatically (and learning to use phpWord in the process) then you are going to want to do something with the word doc you have created. Can i also assume that that is going to be something other than download it and open it in word and say horray i have a word file - otherwise you would have just done it locally in the first place, or written some vba or somehting, right? I am guessing that nearly everybody using phpWord wants to make a pdf from the resulting doc programatically and send it to customers or colleagues or whatever. So what is going on with tcphp. It is just the exact right tool if you want to take the doc that you have made (hours of work) and create a pdf that exactly resembles one that you would have made on the first word processor you bought back in 1988, but otherwise it is not waht you need at all unless you want to program it from scratch. Am i right in believing that you have to tell it how to interpret everything on the page, every font, every color, every image, etc. by setting properties.

Phpword is a good piece of work and has clearly been a project requiring many many hours of thought and work, but it has been a waste of time unless there is a simple add on that will create a simple, but loyal pdf. In my case it is a single page invoice, not complicated just a logo some text and a simple link.

Has anybody found a solution to this please. In the instructions for phpWord, it says somehting about the html-to-pdf method is used for generating pdfs which is why there is no resident save for that format. Has anybody tried that solution or found a pdfwriter that in any way does a half reasonable job of converting the .docx without too much difficulty. Thanks.

[@janssenMA I'm sure you are right about the COM, but i only have a shared server web host at my ISP and i don't think that i can start installing things as i please. I think i just have to use what is there.]

@ghost
Copy link
Author

ghost commented May 11, 2015

Understand your frustration. Mind you some people do want to generate a word document by itself without an intention to generate a pdf version of it (it's the case for some of my clients, they want to be able to keep editing the document once generated).

2 solutions (which are both very disappointing compared to 2 lines of code which could have made our lives much, much easier):

  • I found a guy that developed a word to pdf converter but with Python.
  • The one I would have gone with if I hadn't decided to recode all of it in tcpdf, an API called convertAPI: http:https://www.convertapi.com/word-pdf-api

@donquick
Copy link

Hi Underfrog, It sounds as if we have been down the same rocky road. Thank you for the answer, I will look at the link you provided. As i am personally not that bothered about the intermediate step (namely the doc) itself, I am now looking at this. http:https://html2pdf.fr/en/example which might give me a quick route to a pdf that I can attach to an email which is all i really want. I will post again if it works so that others can reduce the pain of learning phpword only to hit a big wall. cheers, Don

@str
Copy link

str commented Oct 7, 2015

+1 for the images problem. I tried both the PDF and HTML writers.

@buchmayr
Copy link

buchmayr commented Jun 20, 2016

+1 any news to this problem?
tried with tcpdf, dompdf, etc... no images

Settings::setPdfRendererName(Settings::PDF_RENDERER_TCPDF); Settings::setPdfRendererPath(ROOT_PATH . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . "tecnick.com" . DIRECTORY_SEPARATOR . "tcpdf"); // Settings::setPdfRendererPath(ROOT_PATH . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . "dompdf" . DIRECTORY_SEPARATOR . "dompdf"); $pdfWriter = IOFactory::createWriter($phpWord, 'PDF'); $pdfWriter->save($uploadPath . "mypdf.pdf");

@buchmayr
Copy link

Some more Info, it doesnt load the image from the Office-ZIP correctly:

#0 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Element\Image.php(138): PhpOffice\PhpWord\Element\Image->checkImage('zip:https://C:\\xampp\\...') #1 [internal function]: PhpOffice\PhpWord\Element\Image->__construct('zip:https://C:\\xampp\\...') #2 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Element\AbstractContainer.php(145): ReflectionClass->newInstanceArgs(Array) #3 [internal function]: PhpOffice\PhpWord\Element\AbstractContainer->addElement('Image', 'zip:https://C:\\xampp\\...') #4 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Element\AbstractContainer.php(112): call_user_func_array(Array, Array) #5 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007\AbstractPart.php(225): PhpOffice\PhpWord\Element\AbstractContainer->__call('addImage', Array) #6 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007\AbstractPart.php(225): PhpOffice\PhpWord\Element\Section->addImage('zip:https://C:\\xampp\\...') #7 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007\AbstractPart.php(177): PhpOffice\PhpWord\Reader\Word2007\AbstractPart->readRun(Object(PhpOffice\PhpWord\Shared\XMLReader), Object(DOMElement), Object(PhpOffice\PhpWord\Element\Section), 'document', Array) #8 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007\Document.php(160): PhpOffice\PhpWord\Reader\Word2007\AbstractPart->readParagraph(Object(PhpOffice\PhpWord\Shared\XMLReader), Object(DOMElement), Object(PhpOffice\PhpWord\Element\Section)) #9 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007\Document.php(58): PhpOffice\PhpWord\Reader\Word2007\Document->readWPNode(Object(PhpOffice\PhpWord\Shared\XMLReader), Object(DOMElement), Object(PhpOffice\PhpWord\Element\Section)) #10 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007.php(94): PhpOffice\PhpWord\Reader\Word2007\Document->read(Object(PhpOffice\PhpWord\PhpWord)) #11 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\Reader\Word2007.php(69): PhpOffice\PhpWord\Reader\Word2007->readPart(Object(PhpOffice\PhpWord\PhpWord), Array, 'Document', 'C:\\xampp\\htdocs...', 'word/document.x...') #12 C:\xampp\htdocs\ncheck_s\vendor\phpoffice\phpword\src\PhpWord\IOFactory.php(78): PhpOffice\PhpWord\Reader\Word2007->load('C:\\xampp\\htdocs...') #13 C:\xampp\htdocs\ncheck_s\module\Application\src\Application\Controller\CriteriaController.php(140): PhpOffice\PhpWord\IOFactory::load('C:\\xampp\\htdocs...') #14 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php(82): Application\Controller\CriteriaController->exportAction() #15 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent)) #16 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(444): call_user_func(Array, Object(Zend\Mvc\MvcEvent)) #17 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #18 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php(118): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #19 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\Mvc\DispatchListener.php(93): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response)) #20 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent)) #21 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(444): call_user_func(Array, Object(Zend\Mvc\MvcEvent)) #22 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #23 C:\xampp\htdocs\ncheck_s\vendor\zendframework\zendframework\library\Zend\Mvc\Application.php(314): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #24 C:\xampp\htdocs\ncheck_s\index.php(25): Zend\Mvc\Application->run() #25 {main}

@jslirola
Copy link

So we don't have a good converter yet, right? I'm generating a template but I would like to have images in the pdf. If anybody find something, write here.

Thank you.

@gplaza
Copy link

gplaza commented Nov 24, 2016

@jslirola : I use unoconv (https://github.com/dagwieers/unoconv) it's not a perfect solution, it's not PHP. But it's work.

1- use a normal word template (phpoffice word template)
2- save temporary the transformed word document
3- execute unoconv command with php to create PDF document.

@jslirola
Copy link

Thank you @gplaza, I saw that solution but it require unoconv installed on the server. I checked another options without luck:

  • PHPGearBox, require unoconv or libre-office-headless.
  • PHPDocx, it's not free and I was reading the conversion is not very good.
  • FPDF doesn't have a converter.

@Subhash106
Copy link

Hi All, In My case docx is converted in pdf with DomPDF but header and footer disappear in pdf. any idea to get header and footer in pdf file?

@orlleite
Copy link

I'm using PHPWord, thanks to share this project, for applying templates. I load a doc or odt and save it. And for exporting pdf, I'm using libreoffice directly by command line as php can run exec. The command is easy soffice --convert-to pdf myfile.doc --outdir /dir/for/the/file.

Sure it would be nice to use only phpword, but libreoffice is stable and most of the other projects use it for export pdf.

@erikig
Copy link

erikig commented Apr 21, 2017

Thanks - this discussion was quite helpful.
After attempting a number of solutions the most consistently capable solution was based on unoconv.

@eothein
Copy link

eothein commented Oct 28, 2017

This is a large drawback of using PHPWord: my application needs to generate word/odf versions and PDF versions ...

Strange the developers did not think this through

@FBnil
Copy link

FBnil commented Oct 28, 2017

@eothein If you are with time constraints I encourage you to use a paid version that are being offered with such functionality. I never used them, so I do not which one to recommend, but there are multiple out there.

The smear you make is quite hurtful. 'not think this through'... If you are dissatisfied, I'll give you your money back. Open source projects thrive with a mix of user-programmers that are willing to donate some time to make the product better. The core idea, Writing a docx from scratch works very well. I like this Unix idea of doing one thing well. The rest, like the TemplateProcessor was added in by others, and support for other formats was started, but not finished

However, Stick around, and with your help, the PDF exporter will get better. Just keep in mind this PHPWord is not 1.0 yet.

And what is the drawback of using more than one technology? Just use https://github.com/dagwieers/unoconv side by side with PHPWord. Let each do what they are good at.

Note: if you are using oowriter directly from the commandline... it is heavy (java) and takes a few seconds.

Other options: Use PostScript (GhostWriter) to produce perfect pdf's

@eothein
Copy link

eothein commented Oct 29, 2017

Dear FBnil

I changed my comment a little bit (LARGE to large), it was in on way my intention to be hurtful.

Well let me explain my frustration: when I was choosing a framework to generate odf/pdf versions of a document, I came across PHPWord which is encouraged on a lot of forums.

On the documentation site I found in one of the examples:

/* Note: we skip PDF, because "HTML-to-PDF" approach is used to create PDF documents. */

So my guess was that the functionality was already there. So trying and retrying to find out that after several hours the functionality is not complete was a frustrating. Maybe this explains my word choosing. My sincere apologies.

Jens Buysse

@FBnil
Copy link

FBnil commented Oct 29, 2017

@eothein : Yes, I can see why you feel it wasted your time, but you now know it's weaknesses, but do not forget it's strengths. May I kindly re-suggest, the UNO interface from OpenOffice?

# Launch OpenOffice.org as a service and talk to it. convert from/to any of the supported formats
$ ooffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"

There are many UNO bindings for many languages that relaunch the OpenOffice daemon and allow simple parameters for conversions. This dramatically saves time for high usage conversions.
here is a Perl binding
although easier to use Python bindings already have been suggested (I searched, but nothing for PHP afaik, although PHP has fsockopen(), so it is doable)

@xeux
Copy link

xeux commented Feb 19, 2018

@nicolasidweb is it possible to $document->saveAs('temp.docx'); in memory?

@xeux
Copy link

xeux commented Feb 19, 2018

Googling it is possible: $fileObj = $document->save(); then open $fileObj with PhpWord() and then to writer.

@demonicinn
Copy link

demonicinn commented Feb 28, 2018

i have issue with multiple languages convert docx file to pdf file
here is my code
`require_once 'vendor/autoload.php';

	$phpWord = new \PhpOffice\PhpWord\PhpWord();
	\PhpOffice\PhpWord\Settings::setPdfRendererPath('vendor/dompdf/dompdf');
	\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
	
	$document = $phpWord->loadTemplate($getDoc);
	$document->saveAs($temDoc);
	$phpWord = \PhpOffice\PhpWord\IOFactory::load($temDoc);
	$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'PDF');
	$xmlWriter->save($newPdf);  // Save to PDF
	unlink($temDoc);`

@github-actions
Copy link

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
If this is still an issue for you, please try to help by debugging it further and sharing your results.
Thank you for your contributions.

@github-actions github-actions bot added the Stale label Nov 18, 2022
@Progi1984 Progi1984 removed the Stale label Nov 18, 2022
@Aupire
Copy link

Aupire commented Jul 26, 2023

Wow ! It works so good !!! I have a word file with logo, images, text. I tested all (tcpdf, fpdf, libreoffice, mpdf, dompdf) and it's the only one who works perfectly, like a pdf with word directly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests