PHPOffice / PHPWord

A pure PHP library for reading and writing word processing documents
https://phpoffice.github.io/PHPWord/
Other
7.27k stars 2.69k forks source link

DomPDF not working with TemplateProcessor docs, I Try to convert template docs to pdf. #2568

Closed BahaaEldeenOsama closed 8 months ago

BahaaEldeenOsama commented 9 months ago

Describe the Bug

TemplateProcessor not working with IOFactory::createWriter().

PhpOffice\PhpWord\IOFactory::createWriter(): Argument 1 ($phpWord) must be of type PhpOffice\PhpWord\PhpWord, PhpOffice\PhpWord\TemplateProcessor

Steps to Reproduce

Please provide a code sample that reproduces the issue.

<?php
  $templateProcessor = new TemplateProcessor('temp.docx');
  $FullFileName  = 'NewTemp.pdf' ;

  // Save the document to a temporary file
  $filename = tempnam(sys_get_temp_dir(), 'NewTemp' ) . '.docx';
  $templateProcessor->saveAs($filename);

  // Convert Word document to HTML
  $htmlWriter = IOFactory::createWriter($templateProcessor, 'HTML');
  $htmlContent = $htmlWriter->saveToString();

  // Initialize DomPDF
  $options = new Options();
  $options->set('isHtml5ParserEnabled', true);
  $options->set('isPhpEnabled', true);
  $dompdf = new Dompdf($options);

  // Load HTML content into DomPDF
  $dompdf->loadHtml($htmlContent);

  // Set paper size (optional)
  $dompdf->setPaper('A4', 'portrait');

  // Render PDF (output)
  $dompdf->render();

  // Set headers for a PDF download
  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment; filename='.$FullFileName);

  // Output the PDF content to the browser
  echo $dompdf->output();

  // Delete the temporary Word document
  unlink($wordFilePath);     

Context

Please fill in your environment information:

oleibman commented 9 months ago

I don't think the template processor was designed to work with anything other than Word2007 format. However, since you've saved the output file, you should be able to read it back in:

  // Convert Word document to HTML
  $reader = new \PhpOffice\PhpWord\Reader\Word2007();
  $phpWord = $reader->load($filename);
  $htmlWriter = new \PhpOffice\PhpWord\Writer\HTML($phpWord)
  $htmlContent = $htmlWriter->saveToString();