I would like to generate a custom pdf upon sale and attach it to the sales email all within a custom module.

I think I need to extend Magento\Sales\Model\Order\Pdf\AbstractPdf to generate the pdf but I am not certain.

Has anyone done this before or has any idea if I'm on the right track?

// edit:

As per the comments, here is a basic layout as to how I included http://www.fpdf.org/ into my custom module:

First I downloaded the fpdf package. I extracted the files and placed them all into my Modules Helper folder, which now looks like this:

- Helper -- font (folder) -- makefont (folder) -- FPDF.php -- Data.php

Data.php is the only file I already had in this folder as it contains my helper Data class.

Next I edited the FPDF.php and added my modules namespace to it.

I edited my helper Data.php file and use my namespaces FPDF class:

use Company\ModuleName\Helper\FPDF as FPDF;

I defined any pdf infos I need in the data Class - you do not need this:

protected $pdfFileDir = 'someDir/someSubDir/';
protected $logo1 = 'myLogo.jpg';
protected $logo2 = 'myExtraLogo.jpg';

 * @var \Company\ModuleName\Helper\FPDF
protected $_pdf;

and construct it

 * @param \Company\ModuleName\Helper\FPDF $pdf
 * @param array $data
public function __construct(
    FPDF $pdf,
    array $data = []
) {
    $this->_pdf = $pdf;

I then created my method and generate the pdf:

public function generatePdf($productId, $someOtherVars)
    #start the pdf
    $pdf = new FPDF();

    $pdf->SetAutoPageBreak(0, 5);
    $pdf->SetFont('Arial', 'B', 16);

    // do your FPDF stuff here
    // eg: $pdf->Cell('', '', iconv('UTF-8', 'windows-1252', 'Page Header Title'), 0, 1);

    // $pdf->Ln(8);
    // $pdf->Cell('', '', $today, 0, 1, 'L');
    // and so forth .. see the FPDF documentation

    // render pdf
    $filename = 'somename' . $productId . '.pdf';
    $pdf->Output($this->getPdfBaseDir() . $filename, 'F');

    return $this->getPdfBaseDir() . $filename;

Then you call your method in your controller via your helper (which you need to include of course):


  • Did you get anywhere with this? Commented Jul 6, 2016 at 9:41
  • 1
    I didn't go that route after all. I tried but in the end it seemed too complex to try and use the AbstractPdf class. I ended up including FPDF with my module (in the Helper) and used it to generate the pdf files. fpdf.org
    – tecjam
    Commented Jul 6, 2016 at 10:21
  • 1
    Brilliant. Did you consider dompdf? github.com/dompdf/dompdf Commented Jul 6, 2016 at 10:25
  • 1
    I did, but one reason as to why I didn't use it was that I didn't want to have to render the html first and then have to render the html into the pdf. There were other reasons too, but I can not recall what they were. For your use it may be better, but only you can decide that.
    – tecjam
    Commented Jul 6, 2016 at 11:39
  • Hello, any updates on this question. I am trying to generate PFD for my custom module- Magento2.
    – Dev
    Commented Nov 14, 2016 at 7:09

4 Answers 4


You can use FPDF or TCPDF for creating PDF.

Try to run one of the following command from M2 root directory

composer require setasign/fpdf:1.8.1

It will add fpdf library in vendor folder as setasign/fpdf. Once fpdf install you can use FPDF in you custom module for creating PDF.

$pdf= new \FPDF();


composer require tecnickcom/tcpdf

It will add tcpdf library in vendor folder as tecnickcom/tcpdf. Once tcpdf install you can use TCPDF in you custom module for creating PDF.



Try This Code


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;

     * @inheritdoc
    public function execute()
        $pdfData = [];
        $pdfData["body_data"] = "<h1><b>TEST Data</b></h1>";
        $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);
        $outputData = $pdf->Output('test.pdf', 'I'); // D , F , S

     * Initialization of mpdf library
    protected function initializePDF()

        $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);



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


Magento2: How to create a PDF in a custom module

public function execute()
    $file = $this->getRequest()->getParam('file');

    if(isset($file) && !empty($file)) {

        $pdf = \Zend_Pdf::load($this->directory_list->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . $file);
        $fileName = test.pdf;
        str_replace('/Annot /Subtype /Link', '/Annot /Subtype /Link /Border[0 0 0]', $pdf->render()),

You Can Check Below Link






namespace VendoreName\RmaPdfPrint\Controller\Rma;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Registry;
use VendoreName\Rma\Api\Repository\RmaRepositoryInterface;
use VendoreName\Rma\Api\Service\Rma\RmaManagement\SaveInterface;
use VendoreName\Rma\Helper\Controller\Rma\GuestStrategy;
use VendoreName\Rma\Helper\Controller\Rma\StrategyFactory;
use VendoreName\Rma\Service\Config\FrontendConfig;
use VendoreName\RmaPdfPrint\Block\DownloadRmaPdf;

class PrintAction extends \Magento\Framework\App\Action\Action;
    protected $rmaData;

    private $guestStrategy;
    private $rmaRepository;
    private $rmaSaveManagement;
    private $registry;

    public function __construct(
        Context $context,
        GuestStrategy $guestStrategy,
        RmaRepositoryInterface $rmaRepository,
        SaveInterface $rmaSaveManagement,
        Registry $registry,
        StrategyFactory $strategyFactory,
        Session $customerSession,
        FrontendConfig $frontendConfig,
        DownloadRmaPdf $rmaData
    ) {
        $this->guestStrategy     = $guestStrategy;
        $this->rmaRepository     = $rmaRepository;
        $this->rmaSaveManagement = $rmaSaveManagement;
        $this->registry          = $registry;
        $this->rmaData           = $rmaData;

    public function execute()
        $rma = $this->getRequest()->getPost();
        $this->registry->register('current_rma', $rma);
        $pdf = $this->rmaData->getPdf($rma); // Here We set RMA Data
        $pdfData = $pdf->render();

        header('Content-type: application/pdf');
        header('Content-Disposition: inline; filename=result.pdf');
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');

        echo $pdfData;

Must Open link whole code are in the file

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.