1

I've been trying to generate a multiple pdfs. How can I do it?

I have tried to use a for loop, but I have no idea how to continue.

for ($i = 0; $i < 10; $i++) {
    $mpdf = new mPDF();
    $mpdf->WriteHTML('<p>Only test$i</p>');
    $mpdf->Output("Document_name$i.pdf", "D");
}

exit;    

I expect 10 documents that will be downloaded by this script.

1 Answers1

5

While HTTP technically does support multiple files in a single response through MIME-Multipart, browser support is mostly non-existent.

A possible course of action would be to add each generated PDF to a ZIP archive, and serve the ZIP file as the response instead:

    $zip = new ZipArchive();
    $zipFile = tempnam('/tmp', 'zip');
    $zip->open($zipFile, ZipArchive::CREATE);

    for ($i = 0; $i < 10; $i++) {
        $mpdf = new mPDF();
        $mpdf->WriteHTML('<p>Only test$i</p>');
        $pdfData = $mpdf->Output("", \Mpdf\Output\Destination::STRING_RETURN);
        $zip->addFromString("Document_name{$i}.pdf", $pdfData);
    }

    $zip->close();

    header("Content-type: application/zip");
    header('Content-Disposition: attachment; filename=Documents.zip'); 
    readfile($zipFile);

    unlink($zipFile);
    exit;
crishoj
  • 5,660
  • 4
  • 32
  • 31
  • Could you please show me how to do it? I have really no idea, I'm standing on this step more then 1 week. – Lukáš Kosejk Feb 04 '19 at 22:50
  • Thank you sir, you saved my life! – Lukáš Kosejk Feb 05 '19 at 09:15
  • I'm sorry for spaming.. The zip was successfully downloaded but I can't open the archive. Could you please help me? The mpdf was downloaded by composer so I think that here is not problem, I have the latest version of library. – Lukáš Kosejk Feb 07 '19 at 19:26
  • My mistake — there was an error in the line `readfile($zipData)`. `readfile` needs the `$zipFile` variable. Now fixed. – crishoj Feb 08 '19 at 06:38
  • For further debugging, I suggest temporarily commenting out the call to `unlink` and inspecting the ZIP file on the server. – crishoj Feb 08 '19 at 06:39
  • I'm really sorry but could you please help me again? Everything was ok than I upload app at hosting. The zip was successfully downloaded but I can't open the archive again. On the localhost in laptop was script alright. Have I to install mpdf via composer on hosting, if I must, it's quite a problem, because my hosting does not support a SSH? I only copied the downloaded data of mpdf library that was downloaded by composer. Please, Please help me :D – Lukáš Kosejk Feb 10 '19 at 19:51
  • Is the ZIP PHP extension available on the server? Also, look in your server logs for error messages, or as a fallback, try opening the downloaded ZIP file with your text editor and look for any error messages. – crishoj Feb 11 '19 at 07:36