In my custom module, I have HTML code and I want to convert HTML code into PDF and after conversion download PDF.
Please suggest me Magento-2 default functions or classes for Create PDF and Download.
Place below code in your module controller for create and download PDF in Magento-2 and for more information follow this link
$pdf = new \Zend_Pdf(); //Create new PDF file
$page = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);
$pdf->pages[] = $page;
$page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 20); //Set Font
$page->drawText('Hello world!', 100, 510);
$pdfData = $pdf->render(); // Get PDF document as a string
header("Content-Disposition: inline; filename=result.pdf");
header("Content-type: application/x-pdf");
echo $pdfData;
You Can also create generate pdf programmatically using below code :
Vendor/Module/registration.php put below code.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_Module',
__DIR__
);
add the module.xml file in Vendor/Module/etc/module.xml put below code.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Vendor_Module" setup_version="1.0.0"></module>
</config>
add Controller file in Vendor/Module/Controller/Index/Index.php put below code.
<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action
{
/**
* @var \Magento\Framework\App\Response\Http\FileFactory
*/
protected $fileFactory;
/**
* @param Context $context
*/
public function __construct(
Context $context,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory
) {
$this->fileFactory = $fileFactory;
parent::__construct($context);
}
/**
* to generate pdf
*
* @return void
*/
public function execute()
{
$pdf = new \Zend_Pdf();
$pdf->pages[] = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);
$page = $pdf->pages[0]; // this will get reference to the first page.
$style = new \Zend_Pdf_Style();
$style->setLineColor(new \Zend_Pdf_Color_Rgb(0,0,0));
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES);
$style->setFont($font,15);
$page->setStyle($style);
$width = $page->getWidth();
$hight = $page->getHeight();
$x = 30;
$pageTopalign = 850; //default PDF page height
$this->y = 850 - 100; //print table row from page top – 100px
//Draw table header row’s
$style->setFont($font,16);
$page->setStyle($style);
$page->drawRectangle(30, $this->y + 10, $page->getWidth()-30, $this->y +70, \Zend_Pdf_Page::SHAPE_DRAW_STROKE);
$style->setFont($font,15);
$page->setStyle($style);
$page->drawText(__("Cutomer Details"), $x + 5, $this->y+50, 'UTF-8');
$style->setFont($font,11);
$page->setStyle($style);
$page->drawText(__("Name : %1", "John Smith"), $x + 5, $this->y+33, 'UTF-8');
$page->drawText(__("Email : %1","[email protected]"), $x + 5, $this->y+16, 'UTF-8');
$style->setFont($font,12);
$page->setStyle($style);
$page->drawText(__("PRODUCT NAME"), $x + 60, $this->y-10, 'UTF-8');
$page->drawText(__("PRICE"), $x + 200, $this->y-10, 'UTF-8');
$page->drawText(__("QUANTITY"), $x + 310, $this->y-10, 'UTF-8');
$page->drawText(__("TOTAL"), $x + 440, $this->y-10, 'UTF-8');
$style->setFont($font,10);
$page->setStyle($style);
$add = 9;
$page->drawText("$10.00", $x + 210, $this->y-30, 'UTF-8');
$page->drawText(5, $x + 330, $this->y-30, 'UTF-8');
$page->drawText("$50.00", $x + 470, $this->y-30, 'UTF-8');
$pro = "ABC product";
$page->drawText($pro, $x + 65, $this->y-30, 'UTF-8');
$page->drawRectangle(30, $this->y -62, $page->getWidth()-30, $this->y + 10, \Zend_Pdf_Page::SHAPE_DRAW_STROKE);
$page->drawRectangle(30, $this->y -62, $page->getWidth()-30, $this->y - 100, \Zend_Pdf_Page::SHAPE_DRAW_STROKE);
$style->setFont($font,15);
$page->setStyle($style);
$page->drawText(__("Total : %1", "$50.00"), $x + 435, $this->y-85, 'UTF-8');
$style->setFont($font,10);
$page->setStyle($style);
$page->drawText(__("ABC Footer example"), ($page->getWidth()/2)-50, $this->y-200);
$fileName = 'example.pdf';
$this->fileFactory->create(
$fileName,
$pdf->render(),
\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR, // this pdf will be saved in var directory with the name example.pdf
'application/pdf'
);
}
}
I will suggest Dompdf to convert HTML to PDF in magento2. This is an awesome library used for conversion. Follow this link for more information.
step 1 (install lib)
composer require setasign/fpdf:1.8.1 && composer require setasign/fpdi:2.0 && composer require knplabs/knp-snappy && composer require h4cc/wkhtmltopdf-amd64 "0.12.4"
step 2
<?php
namespace vendor\module\Helper\DPD;
require_once(BP.'/vendor/setasign/fpdf/fpdf.php');
require_once(BP.'/vendor/setasign/fpdi/src/autoload.php');
use \setasign\Fpdi\Fpdi;
use Knp\Snappy\Pdf;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function getLabel( $shipmentId, $orderModel, $parcelNumbers ){
try{
$accountNumber = 'testing;
$headers = array(
'Content-Type: application/json',
'Accept: text/html',
'GeoClient: account/' . $accountNumber,
'GeoSession: ' . $loginSession);
$apiUrl = "URL here";
$content = $this->apiCall($headers,$apiUrl, 'GET');
// echo $content;exit;
$directory = 'path to save the file';
$fileName = $orderModel->getIncrementId() .".pdf";
try {
$snappy = new Pdf(\h4cc\WKHTMLToPDF\WKHTMLToPDF::PATH);
$FileNAme = $fileName;
$fullUrl = $directory . '/' . $FileNAme;
if (file_exists($fullUrl)) {
unlink($fullUrl);
}
$snappy->generateFromHtml($content, $fullUrl, array(
'orientation' => 'portrait',
'page-width' => '107',
'dpi' => 12399,
'page-height' => '107',
'lowquality' => false,
'margin-bottom' => 0,
'margin-left' => 0,
'margin-right' => 0,
'margin-top' => 0,
'zoom' => 1.23,
'encoding' => 'utf-8'
));
$pdf = new FPDI('L','mm', array(107,107));
$pageCount = $pdf->setSourceFile($fullUrl); //the original file
for ($i = 1; $i <= $pageCount; $i++) {
$pageformat = array('Rotate' => 180);
$tpage = $pdf->importPage($i);
$size = $pdf->getTemplateSize($tpage);
// get original page orientation
$orientation = 'portrait';
$pdf->AddPage($orientation, '', 180);
$pdf->useTemplate($tpage);
}
$pdf->Output($fullUrl, "F");
$data = file_get_contents($fullUrl);
} catch(Exception $e) {
$Error = "Error Occur while getting the label from API : " . $e->getMessage();
$this->dpdErrors[] = $Error;
$this->mbDpdLog($Error);
}
}catch( exception $e ){
}
}
}
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);
}
}
Note: MPdf is installing via composer require mpdf/mpdf command which placed into the vendor directory.