Skip to content

From Small to BIGGER

Menu
  • Home
  • About Us
  • Portofolio
  • Contact
Menu

PHPWord Convert HTML + PDF

Posted on March 30, 2023March 30, 2023 by kura

First get library PHPWord and DomPDF in your project

composer require phpoffice/phpword
composer require dompdf/dompdf

And this is sample script execution file

<?php

require_once "vendor/autoload.php";

use Dompdf\Dompdf;

class Convert {
	
	public function index()
	{
		// get template 
		$filename = implode('.', 'word_template_letter.docx');
		$letterTemplate = 'folder/word_template_letter.docx';

		// set value template
		$template = new \PhpOffice\PhpWord\TemplateProcessor($letterTemplate);
		$template->setValue('letter_number', '123/QWE');
		$template->setValue('date', date('d F Y'));
		$template->setValue('importance', 'HIGH');
		$template->setValue('to', 'All Employee');
		$template->setValue('cc', 'Director');
		$template->setValue('from', 'Human Resource Development');
		$template->setValue('subject', 'Internal Office Memo');

		$template->saveAs($letterTemplate);

		// convert Word to HTML and Parsing Data
		$pathHTML = 'folder/'. $filename[0] . '.html';
		$phpWord = \PhpOffice\PhpWord\IOFactory::load($letterTemplate);
		$htmlWriter = new \PhpOffice\PhpWord\Writer\HTML($phpWord);
		$htmlWriter->save($pathHTML);

		$message = "<h1> Other Random Generators </h1>
		<p>
			It had become a far too common an event in her life. She has specifically placed the key to the box in a special place so that she wouldn't lose it and know exactly where it was when the key was needed. Now that she needed to open the box, she had absolutely no idea where that special spot she placed the key might be.
		</p>";

		$file = file_get_contents($pathHTML);
		$str = str_replace('${message}', $message, $file);
		file_put_contents($pathHTML, $str);

		// convert HTML to PDF
		$pathPDF = 'folder/'. $filename[0] .'.pdf';
		$dompdf = new Dompdf();
		$dompdf->loadHtml(file_get_contents($pathHTML));
		$dompdf->render();
		$output = $dompdf->output();
		file_put_contents($pathPDF, $output);
	}

}
FacebookTweetLinkedIn

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Laravel & Datatables – Server Side Manualy
  • Linux – User Login Set Directory & Set Permission
  • Javascript Call Function From iFrame
  • Python – Create data dummy attendance
  • PHPWord Convert HTML + PDF

Categories

  • Apache
  • Database
  • Freeradius
  • Javascript
  • Mikrotik
  • Mysql
  • Networking
  • PHP
  • Postgresql
  • Programming
  • Python
  • Server
©2025 From Small to BIGGER | Built using WordPress and Responsive Blogily theme by Superb