How To Generate PDF programmatically in Magento 2

I would like to create a PDF file, how can I generate PDF programmatically in Magento 2

To create a PDF file in Magento 2

Step 1Define Zend_Pdf object and set page size
Step 2Set style and font for new Magento 2 PDF file
Step 3Draw content by called drawText, drawRectangle or other methods
Step 4Call class FileFactory and saving the content as Magento PDF file

Here is the example to creating a PDF file in Magento 2

$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 = 40;
$pageTopalign = 850; //default PDF page height
$y = $pageTopalign - 50;
$style->setFont($font,16);
$page->setStyle($style);
$page->drawText(__("Text Text"), $x + 5, $y+50, 'UTF-8');
$fileName = 'test.pdf';

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$fileFactory = $objectManager->get('Magento\Framework\App\Response\Http\FileFactory');

$fileFactory->create($fileName,$pdf->render(),\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR,'application/pdf');
3.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments