Magento 2: Show whole HTML code(phtml file code) into PDF file and Download with the use of DOM PDF?
I have tried to do it with zend pdf but i am not able to show whole html content with the use of zend pdf.
If i want to display content of cms block , then i am not able to do it with Zend PDF. I have tried to find out class reference which can draw html with its tag.
If i pass html content in $page1->drawText($html, $x, $y); then it will display with all html tag. So i have noticed that we can do it with DOM PDF. But i am not aware about exact logic for it.
Is any other way to do it?
- 
 you can use this for dom pdf github.com/weprovide/magento2-module-dompdfPradip Garchar– Pradip Garchar2021年01月21日 08:35:04 +00:00Commented Jan 21, 2021 at 8:35
- 
 @PradipGarchar had checked this module but need to do so much customisation according to my need so i have developed it in my own way. After that i have posted my working code here.ZealousWeb– ZealousWeb2021年01月22日 06:53:36 +00:00Commented Jan 22, 2021 at 6:53
1 Answer 1
I have found the way for it.
First we need to install DOMpdf library. For that you can install it with the use of composer by below command.
composer require dompdf/dompdf
Create one phtml file where we can put our html code. I have used it for product page pdf.
Set download button wherever you want. We have created one new phtml file to show "Download as pdf" button on product page
Below is the code of button and ajax call
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
 $urlInterface = $objectManager->get('\Magento\Framework\UrlInterface');
 $currentUrl = $urlInterface->getCurrentUrl();
?>
<div class="print-btn-wrap">
 <button type="button" class="print-btn action primary print-product-pdf" id="print-product-pdf"><i class="fa fa-file-pdf-o" aria-hidden="true"></i> <?= $block->escapeHtml(__('Download As PDF ')) ?></button>
</div>
<script type="text/javascript">
require(['jquery','domReady!'], function ($) {
 jQuery(document).ready(function(){
 jQuery(".print-product-pdf").on('click',function(){
 var url = '<?php echo $this->getUrl("productpdf/index/index"); ?>';
 jQuery.ajax({
 url: url,
 type: "POST",
 data: {product_id:"<?php echo $product->getId(); ?>",product_url:"<?php echo $currentUrl; ?>"},
 showLoader: true,
 success: function(response){
 if(response) {
 var a = document.createElement('a');
 var url = response;
 a.href = url;
 a.download = 'product.pdf';
 document.body.append(a);
 a.click();
 a.remove();
 }
 }
 });
 });
 });
});
</script>
Please create one block file
PackageName/Productpdf/Block/View.php
<?php
namespace PackageName\Productpdf\Block;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\View\Element\Template;
class View extends Template
{
 /**
 * Product Model
 *
 * @var \Magento\Catalog\Model\ProductFactory
 */
 protected $_productFactory;
 protected $_registry;
 /**
 * @param \Magento\Catalog\Model\ProductFactory $productFactory
 * @param array $data
 */
 public function __construct(
 Context $context,
 \Magento\Catalog\Model\ProductFactory $productFactory,
 \Magento\Framework\Registry $registry,
 array $data = []
 ){
 $this->_registry = $registry;
 $this->_productFactory = $productFactory;
 parent::__construct($context, $data);
 }
 public function getCurrentProduct()
 { 
 return $this->_registry->registry('current_product');
 }
}
PackageName/Productpdf/view/frontend/templates/product/view/productpdf.phtml
We have passed product object from controller file
<?php $_product = $this->getProduct(); ?>
<?php $product_url = $this->getProductUrl(); ?>
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$priceHelper = $objectManager->create('Magento\Catalog\Helper\Data');
$currencyFormate = $objectManager->create('\Magento\Framework\Pricing\Helper\Data');
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
?>
<!DOCTYPE html>
<html>
<head>
 <style>
 @page { margin: 90px 0; padding-bottom: 90px; }
 header { position: fixed; top: -70px; left: 0px; right: 0px; height: 100px; color: white; text-align: left; line-height: 35px; margin: 0 30px; }
 footer {position: fixed; bottom: 70px; padding: 5px 20px 40px 20px; background: #62bace; }
 a {color: #62bace;}
 </style>
</head> 
<body>
 <header>
 <img src="<?= $mediaUrl.'/logo/logo.png'; ?>"> 
 </header>
 <footer>
 <table width="100%" class="footer-section">
 <tbody>
 <tr>
 <td class="left-td"> 
 <div class="left-part">
 <table width="100%" align="top">
 <tbody>
 <tr>
 <td class="general-tab" align="top">
 <p>
 <span class="semi-bold"><?= __("General enquiries"); ?><br></span>
 <?= __("5454554 6880112"); ?><br>
 <span class="semi-bold"><?= __("Email"); ?><br></span>
 <?= __("[email protected]") ?> 
 </p>
 </td>
 </tr>
 </tbody>
 </table>
 </div>
 </td>
 </tr>
 </tbody>
 </table>
 </footer>
 <div class="productpdf-sec">
 <p class="pdf-product-name bold"><?= $_product->getName(); ?></p>
 <div class="product-add-form" align="top">
 <p class="border-bottom semi-bold detail-section">
 <span><?= __("Details"); ?></span> 
 </p>
 <div class="product-description">
 <?php echo $_product->getDescription(); ?>
 </div>
 <div style="margin:0;padding-top: 10;">
 <a href="<?php echo $product_url ?>" style="color: #62bace;"><?php echo $product_url ?></a>
 </div>
 </div>
 </div>
</body>
</html>
Create controller file where we can pass whole html in DOM pdf.
PackageName/Productpdf/Controller/Index/Index.php
<?php
namespace PackageName\Productpdf\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Dompdf\Dompdf;
class Index extends \Magento\Framework\App\Action\Action {
 /**
 * @var \Magento\Framework\Registry
 */
 protected $_registry;
 /**
 * @var Magento\Catalog\Api\ProductRepositoryInterface
 */
 protected $productRepository;
 /**
 * @var \Magento\Framework\View\LayoutInterface
 */
 protected $layout;
 protected $filesystem;
 protected $_storeManager;
 /**
 * @param Action\Context $context
 */
 public function __construct(
 \Magento\Framework\App\Action\Context $context,
 \Magento\Framework\Registry $registry,
 ProductRepositoryInterface $productRepository,
 \Magento\Framework\View\LayoutInterface $layout,
 \Magento\Framework\Filesystem $filesystem,
 \Magento\Store\Model\StoreManagerInterface $storeManager,
 \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
 ) {
 parent::__construct($context);
 $this->_registry = $registry;
 $this->productRepository = $productRepository;
 $this->layout = $layout;
 $this->filesystem = $filesystem;
 $this->_storeManager = $storeManager;
 $this->resultJsonFactory = $resultJsonFactory;
 }
 /**
 * Create PDF for product page.
 */
 public function execute()
 {
 $mediaPath = $this->filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('exportpdf');
 $files = glob($mediaPath.'/*');
 foreach($files as $file) { 
 unlink($file); 
 } 
 if($params = $this->getRequest()->getParams())
 {
 $productId = $params['product_id'];
 $product_url = $params['product_url'];
 if (!$this->_registry->registry('product') && $productId) {
 $product = $this->productRepository->getById($productId);
 $this->_registry->register('product', $product);
 } else {
 $product = null;
 }
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $productpdf = $this->layout->createBlock('\PackageName\Productpdf\Block\View',"",['data' => ['product' => $product,'product_url' => $product_url]])->setData('area','frontend')->setTemplate('PackageName_Productpdf::product/view/productpdf.phtml')->toHtml();
 $processor = $objectManager->create('Magento\Cms\Model\Template\FilterProvider');
 $finalpdf = $processor->getBlockFilter()->filter($productpdf);
 $dompdf = new Dompdf();
 
 $dompdf->load_html($finalpdf);
 $dompdf->set_option('isRemoteEnabled', TRUE);
 $dompdf->setPaper('A4', 'portrait');
 $dompdf->render();
 $output = $dompdf->output();
 $pdfFile = file_put_contents($mediaPath . "/product.pdf", $output);
 $result = $this->resultJsonFactory->create();
 $mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
 $downloadPath = $mediaUrl.'exportpdf/product.pdf';
 return $result->setData($downloadPath);
 }
 $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
 $resultRedirect->setUrl($this->_redirect->getRefererUrl());
 return $resultRedirect;
 }
}
- 
 is this work properly ?Pradip Garchar– Pradip Garchar2021年01月21日 10:57:56 +00:00Commented Jan 21, 2021 at 10:57
- 
 @PradipGarchar Yes, it is working. You can tryZealousWeb– ZealousWeb2021年01月21日 14:21:20 +00:00Commented Jan 21, 2021 at 14:21
- 
 is it working for you @PradipGarcharDevidas– Devidas2022年05月30日 08:05:46 +00:00Commented May 30, 2022 at 8:05
- 
 Yes working @DevidasPradip Garchar– Pradip Garchar2022年08月03日 14:12:14 +00:00Commented Aug 3, 2022 at 14:12