4

Currently Magento 2 is providing JSON and XML response in web REST API I want to include a custom response format PDF.

So if any third-party will call our API then we can sen them PDF in response.

0

Just my idea: We shouldn't do this. We can add the download link or generated link to API response. There are some additional points:

  • How about your server resource if serving PDF each time calling. Your server can be stress. We should consider about this case.
  • Should consider security in this case as well.
0

First define your route in etc/webapi.xml

<route url="/V1/invoices/:id/pdf/:template" method="GET">
    <service class="Thousandmonkeys\Restpdf\Api\PDFInterface" method="pdf"/>
    <resources>
        <resource ref="Magento_Sales::sales" />
    </resources>
</route>

Then in your Model class, which you've defined in di.xml as implementing your interface (in my case Thousandmonkeys\Restpdf\Model\PDFMaker) you can return the generated pdf easily. I've used eadesignro/module-pdfgenerator as my pdf engine (it's rather friendlier than than doing it manually).

public function pdf($invoiceId, $templateId){
    $templateModel = $this->pdfGeneratorRepository->getById($templateId);
    if (!$templateModel) {
        throw new \Magento\Sales\Exception(
                __('Could not find template.')
        );
    }
    $invoice = $this->invoiceRepository
        ->get($invoiceId);
    if (!$invoice) {
        throw new \Magento\Sales\Exception(
                __('Could not find invoice.')
        );
    }
    $helper = $this->helper;
    $helper->setInvoice($invoice);
    $helper->setTemplate($templateModel);
    $pdfFileData = $helper->template2Pdf();
    return new PDFResponse(base64_encode($pdfFileData['filestream']));
}

PDFResponse is just a class with one getter that magento uses to generate json or xml.

It is a bit heavy so consider load, but it's a trade off between that and using the file system, which is not always a great idea (problems with load balancers & clean up). A respectful client wont cause any more issues with this than anything else. A disrespectful client could just request the pdf over and over.

It would be a bit of a problem to open this up to customers however. You can't guarantee that they will be respectful.

Full implementation https://github.com/lingwooc/restpdf-magento2 or just install thousandmonkeys/m2-restpdf-module

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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