Generate pdfs programmatically

The below is an example php script which will write a pdf file for a given order id.

<?php

use Fooman\PdfCustomiser\Model\PdfRenderer\OrderAdapter;
use Magento\Framework\App\AreaList;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\State;
use Magento\Sales\Model\Order;
use Magento\Store\Model\App\Emulation;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$om = $bootstrap->getObjectManager();
$state = $om->get(State::class);
$state->setAreaCode('frontend');
$areaList = $om->get(AreaList::class);
$emulation = $om->get(Emulation::class);
$order = $om->get(Order::class)->load(83);

$emulation->startEnvironmentEmulation($order->getStoreId(), 'frontend', true);
$orderAdapter = $om->get(OrderAdapter::class);
$areaList->getArea('frontend')->load('translate');
$pdfString = $orderAdapter->getPdfAsString([$order]);
$fileName = $orderAdapter->getFileName([$order]);
file_put_contents($fileName, $pdfString);
$emulation->stopEnvironmentEmulation();

Still need help? Contact Us Contact Us