使用symfony4为文件pdf创建URL

时间:2019-01-18 12:54:04

标签: symfony4

我正在尝试使用API​​响应JSON从PDF文件创建下载链接,但是我所做的没有任何效果。我的功能是生成PDF并创建URL:

/**
 * @Route(
 *     name="api_orders_orly",
 *     path="/orders/{id}/stamp",
 *     methods={"PUT"},
 *     defaults={
 *         "_api_resource_class"=Order::class,
 *         "_api_item_operation_name"="put"
 *     }
 * )
 */
public function createStampOrly(Order $data, EntityManagerInterface $entityManager)
{
    $hote = $_SERVER['HTTP_HOST'];
    $merchant = $data->getCustomer();

    $pdfOptions = new Options();
    $pdfOptions->set('defaultFont', 'Arial');

    $pdfFilepath = $this->kernel->getProjectDir() . '/public/pdf/' . $data->getIdTrackingAkaz() . '.pdf';

    if (!file_exists($pdfFilepath)) {
        // Instantiate Dompdf with our options
        $dompdf = new Dompdf($pdfOptions);

        $qrCode = $this->qrCodeGenerate($data);
        $codeBarre = $this->codeBarreGenerator($data);

        // Retrieve the HTML generated in our twig file
        $html = $this->renderView('pdf/orly.html.twig', [
            'logo' => $hote . '/' . getenv('LOGO_AKAZ'),
            'finalCustomer' => $data,
            'barCode' => $codeBarre->getContent(),
            'qrCode' => $qrCode->getContent(),
            'nameMerchant' => $merchant,
            'title' => "A-KAZ"
        ]);

        // Load HTML to Dompdf
        $dompdf->loadHtml($html);

        // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
        $dompdf->setPaper('10x15', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();

        // Store PDF Binary Data
        $output = $dompdf->output();

        $data->setDateStampAkaz(new \DateTime());
        $data->setDateUpd(new \DateTime());
        $data->setUrlTrackingAkaz($pdfFilepath);

        $entityManager->persist($data);
        $entityManager->flush();

        file_put_contents($pdfFilepath, $output);

        $response = new BinaryFileResponse($pdfFilepath);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $data->getIdTrackingAkaz().'.pdf');

        return new JsonResponse($response);
    } else {
        return new JsonResponse([
            'status' => 'error',
            'errors' => 'Etiquette déjà générer !'
        ],
            JsonResponse::HTTP_BAD_REQUEST
        );
    }
}

我在公用文件夹的特定目录中生成文件,我希望URL看起来像http://domain.fr/pdf/AF465465JD.pdf

谢谢您的帮助。

0 个答案:

没有答案