2

I am already created Custom email from admin panel with attachment of sample pdf file, But now i want to create .phtml file to .pdf file & which is attach in my custom email.

4 Answers 4

1

Step 1) Download TCPDF library from https://github.com/tecnickcom/tcpdf and place at magento2.0/lib/internal/TCPDF

Step 2) Rename tcpdf.php to TCPDF.php

Step 3) Open TCPDF.php and change class name to class TCPDF_TCPDF

Step 4) Create Controller magento2.0/app/code/Namespace/Module_Name/Controller/Generatepdf/createpdf.php

< ? php

namespace Namespace\Module_Name\Controller\Generatepdf;

use TCPDF_TCPDF;

use Magento\Framework\App\Filesystem\DirectoryList;

class Createpdf extends \Magento\Backend\App\Action  {

    public function execute() {
 $baseDir = DirectoryList::MEDIA;

$tcpdf = new TCPDF_TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information

        $tcpdf->SetCreator(PDF_CREATOR);

        $tcpdf->SetAuthor('Nicola Asuni');

        $tcpdf->SetTitle('TCPDF Example 001');

        $tcpdf->SetSubject('TCPDF Tutorial');

        $tcpdf->SetKeywords('TCPDF, PDF, example, test, guide');


// set default header data

        $Header_title = 'Sample PDF';

        $tcpdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . $Header_title, PDF_HEADER_STRING, array(0, 64, 255), array(0, 64, 128));

        $tcpdf->setFooterData(array(0, 64, 0), array(0, 64, 128));


// set header and footer fonts

        $tcpdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));

        $tcpdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));


// set default monospaced font

        $tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);


// set margins

        $tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

        $tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);

        $tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER);


// set auto page breaks

        $tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);


// set image scale factor

        $tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


// set some language-dependent strings (optional)

        if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {

            require_once(dirname(__FILE__) . '/lang/eng.php');

            $tcpdf->setLanguageArray($l);

        }


// ---------------------------------------------------------

// set default font subsetting mode

        $tcpdf->setFontSubsetting(true);

//your htmls here

$html = **For PDF file Write Your HTML Code here** ;

// set some language dependent data:

        $lg = Array();

        $lg['a_meta_charset'] = 'UTF-8';


        $tcpdf->setLanguageArray($lg);


// set font

//dejavusans & freesans For Indian Rupees symbol

        $tcpdf->SetFont('freesans', '', 12);

        // remove default header/footer

//$tcpdf->setPrintHeader(false);

        $tcpdf->setPrintFooter(false);


        $tcpdf->AddPage();


        $tcpdf->writeHTML($html, true, false, true, false, '');


        $tcpdf->lastPage();



//$tcpdf->Output('report_per_route.pdf', 'I');

        $this->logger->debug('report_per_route');

        $filename = $baseurl . '/Sample_pdf'. time().'.pdf';

        $tcpdf->Output($filename, 'F');




   }

}


? >

Step 5) After click Call your controller in your phtml file


< a href="< ? php 
**echo $block->getUrl('namespace_modulename/generatepdf/createpdf');** ? > " > 
< button class="action-default scalable action-secondary" title=" < ? php echo __('Create Pdf') ? > " type="button" >< span >< span >< span >< ? php echo __('Create Pdf') ?></ span></ span ></ span ></ button >
</ a>
2
  • 1
    It is working fine upto Magento2.1.9. But not working with Magento2.2 version. Do you have any idea about it?
    – Ajay
    Oct 31, 2017 at 7:03
  • Hi @Ajay , Did u get any solution for Magento 2.2 version? Oct 20, 2019 at 8:25
0

You can user some pdf library library like tcpdf to achieve your task. Here some pre defined function available like writehtml() which convert whole html into pdf.

1
0

You can use this library which convert HTLM to PDF :

http://www.html2pdf.fr/

But you need to create a custom module for your feature.

4
  • worst plugin ever
    – Avesh Naik
    Feb 26, 2019 at 17:34
  • Please comment why it is worst. It is useful for common task. Mar 1, 2019 at 7:32
  • html5 and css3 doesn't work
    – Avesh Naik
    Mar 1, 2019 at 8:48
  • Indeed it is an old library, but for basic usage, I think it is ok. Mar 4, 2019 at 6:33
0

Try This Code

<?php

namespace VendoreName\ModuleName\Controller\Index;

use Magento\Framework\App\Action\Action;
use Zend_Loader;

class GetPdfData extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Framework\Filesystem\DirectoryList
     */
    protected $dir;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Filesystem\DirectoryList $dir,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->dir = $dir;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
        $this->initializePDF();
    }

    /**
     * @inheritdoc
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();

        $block = $resultPage->getLayout()
            ->createBlock(\VendoreName\ModuleName\Block\YouBlockName::class)
            ->setTemplate("VendoreName_ModuleName::YourFileName.phtml");

        $pdfData = [];
        $pdfData["body_data"] = $block->toHtml();
        $config = [
            'mode' => 'utf-8',
            'format' => 'A4',
            'default_font_size' => 10,
            'default_font' => "dejavusans",
            'margin_left' => 1.5,
            'margin_right' => 1.5,
            'margin_top' => 1.5,
            'margin_bottom' => 1.5,
            'allow_charset_conversion' => true,
            'orientation' => 'P',
            'showBarcodeNumbers' => false,
            'tempDir' => $this->dir->getPath('var'),
        ];
        $pdf = new \Mpdf\Mpdf($config);
        $pdf->WriteHTML(html_entity_decode($pdfData["body_data"]));
        $outputData = $pdf->Output('test.pdf', 'D'); // D , F , S
    }

    /**
     * Initialization of mpdf library
     */
    protected function initializePDF()
    {
        error_reporting(0);

        $path = $this->dir->getRoot() . "/vendor/mpdf/mpdf/src/";

        $this->pdf = $path . 'Mpdf.php';

        //include_once $this->pdf;
        Zend_Loader::loadFile($this->pdf, null, true);

        $this->config = $path . 'Config/ConfigVariables.php';

        // require_once $this->config;
        Zend_Loader::loadFile($this->config, null, true);

        $this->ucdn = $path . 'Ucdn.php';

        // require_once $this->ucdn;
        Zend_Loader::loadFile($this->ucdn, null, true);

        $this->defaultCss = $path . 'Css/DefaultCss.php';

        // require_once $this->defaultCss;
        Zend_Loader::loadFile($this->defaultCss, null, true);

        $this->sizeConvertor = $path . 'SizeConverter.php';

        // require_once $this->sizeConvertor;
        Zend_Loader::loadFile($this->sizeConvertor, null, true);

        $this->colorconverter = $path . 'Color/ColorConverter.php';

        // require_once $this->colorconverter;
        Zend_Loader::loadFile($this->colorconverter, null, true);

        $this->gradient = $path . 'Gradient.php';

        // require_once $this->gradient;
        Zend_Loader::loadFile($this->gradient, null, true);

        $this->tableOfContents = $path . 'TableOfContents.php';

        // require_once $this->tableOfContents;
        Zend_Loader::loadFile($this->tableOfContents, null, true);

        $this->cache = $path . 'Cache.php';

        // require_once $this->cache;
        Zend_Loader::loadFile($this->cache, null, true);

        $this->fontCache = $path . 'Fonts/FontCache.php';

        // require_once $this->fontCache;
        Zend_Loader::loadFile($this->fontCache, null, true);

        $this->fontsFileFinder = $path . 'Fonts/FontFileFinder.php';

        // require_once $this->fontsFileFinder;
        Zend_Loader::loadFile($this->fontsFileFinder, null, true);

        $this->cssManager = $path . 'CssManager.php';

        // require_once $this->cssManager;
        Zend_Loader::loadFile($this->cssManager, null, true);

        $this->otl = $path . 'Otl.php';

        // require_once $this->otl;
        Zend_Loader::loadFile($this->otl, null, true);

        $this->form = $path . 'Form.php';

        // require_once $this->form;
        Zend_Loader::loadFile($this->form, null, true);

        $this->hyphenator = $path . 'Hyphenator.php';

        // require_once $this->hyphenator;
        Zend_Loader::loadFile($this->hyphenator, null, true);

        $this->tag = $path . 'Tag.php';

        // require_once $this->tag;
        Zend_Loader::loadFile($this->tag, null, true);

        $this->namedcolors = $path . 'Color/NamedColors.php';

        // require_once $this->namedcolors;
        Zend_Loader::loadFile($this->namedcolors, null, true);

        $this->pageformat = $path . 'PageFormat.php';

        // require_once $this->pageformat;
        Zend_Loader::loadFile($this->pageformat, null, true);

        $this->fontVariables = $path . 'Config/FontVariables.php';

        // require_once $this->fontVariables;
        Zend_Loader::loadFile($this->fontVariables, null, true);

        $this->textvars = $path . 'Css/TextVars.php';

        // require_once $this->textvars;
        Zend_Loader::loadFile($this->textvars, null, true);

        $this->border = $path . 'Css/Border.php';

        // require_once $this->border;
        Zend_Loader::loadFile($this->border, null, true);

        $this->logcontext = $path . 'Log/Context.php';

        // require_once $this->logcontext;
        Zend_Loader::loadFile($this->logcontext, null, true);

        $this->ttfontfile = $path . 'TTFontFile.php';

        // require_once $this->ttfontfile;
        Zend_Loader::loadFile($this->ttfontfile, null, true);

        $this->destination = $path . 'Output/Destination.php';

        // require_once $this->destination;
        Zend_Loader::loadFile($this->destination, null, true);

        $this->mpdfexception = $path . 'MpdfException.php';

        // require_once $this->mpdfexception;
        Zend_Loader::loadFile($this->mpdfexception, null, true);

        $this->metricsgenerator = $path . 'Fonts/MetricsGenerator.php';

        // require_once $this->metricsgenerator;
        Zend_Loader::loadFile($this->metricsgenerator, null, true);

        $this->GlyphOperator = $path . 'Fonts/GlyphOperator.php';

        // require_once $this->GlyphOperator;
        Zend_Loader::loadFile($this->GlyphOperator, null, true);

        $this->barcode = $path . 'Barcode.php';

        // require_once $this->barcode;
        Zend_Loader::loadFile($this->barcode, null, true);

    }

}

Here get your phtml file content using createBlock() and store data into $pdfData["body_data"] variable.

Note: MPdf is installing via composer require mpdf/mpdf command which placed into the vendor directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.