'How can I generate a pdf from web URL with Symfony 4?

I try to generate a pdf from webURL with the snappy bundle:

class PagesController extends AbstractController
{
 /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request)
  {
    $snappy = $this->get("knp_snappy.pdf");
    $snappy->setOption("encoding","UTF-8");

    $filename = "mypdf";
    $webSiteURL = "http://www.stackoverflow.com";
    return new Response(
      $snappy->getOutput($webSiteURL),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
  }

But when I try to open the pdf I get the error message:

Service "knp_snappy.pdf" not found: even though it exists in the app's container, the container inside "App\Controller\PagesController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead

This is my config/packages/knp_snappy.yaml file:

knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage
        options:    []

One approach to solve this was, I tried to add use Knp\Component\Pager\PaginatorInterface; to my Controller, but then I get the error message:

Cannot determine controller argument for "App\Controller\PagesController::pdf()": the $paginator argument is type-hinted with the non-existent class or interface: "Knp\Component\Pager\PaginatorInterface".

Another approach to solve this was adding to my controller:

  public static function getSubscribedServices(): array
{
    $services = parent::getSubscribedServices();
    $services['fos_elastica.manager'] = RepositoryManagerInterface::class;
    $services['knp_paginator'] = PaginatorInterface::class;

    return $services;
}

But then I get the error message:

The service "App\Controller\PagesController" has a dependency on a non-existent service "App\Controller\RepositoryManagerInterface".



Solution 1:[1]

When a Controller extends the AbstractController it doesn’t have access to container which is responsible to contains services. Try to extends the Controller (note that this class will be removed in Symfony 5) or inject the snappy services in the Controller in the services.yaml file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smaïne