Laravel DOMPDF 超出内存限制

如何解决Laravel DOMPDF 超出内存限制

我有 Laravel DOMPDF 包的问题。 我已将 php.ini 内存限制设置为 2G,并使用 --timeout=3600 启动了一个队列。 该脚本是一个 foreach,每次都会调用一个辅助函数,它生成 pdfs 7/8 分钟,然后停止执行,10 分钟后返回终端

Symfony\Component\ErrorHandler\Error\FatalError 

 Allowed memory size of 2147483648 bytes exhausted (tried to allocate 20480 bytes)

 at vendor/dompdf/dompdf/src/Css/Style.php:577
   573▕             //Early check on cache,before converting $length to array
   574▕             if (isset($cache[$key])) {
   575▕                 return $cache[$key];
   576▕             }
 ➜ 577▕             $length = [$length];
   578▕         } else {
   579▕             $key = implode("@",$length) . "/$ref_size";
   580▕             if (isset($cache[$key])) {
   581▕                 return $cache[$key];


  Whoops\Exception\ErrorException 

 Allowed memory size of 2147483648 bytes exhausted (tried to allocate 20480 bytes)

 at vendor/dompdf/dompdf/src/Css/Style.php:577
   573▕             //Early check on cache,$length) . "/$ref_size";
   580▕             if (isset($cache[$key])) {
   581▕                 return $cache[$key];

     +1 vendor frames 
 2   [internal]:0
     Whoops\Run::handleShutdown()

我正在使用表格,我读到可能是因为这个原因。 感谢任何可以帮助我的人。

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
//helper
use App\Helpers\GeneratePdfHelper;

//models
use App\Models\Province;
use App\Models\Process;
use App\Models\Movement;
//others
use PDF;
use Illuminate\Support\Facades\Storage;

class GeneratePdfFiles implements ShouldQueue
{
    use Dispatchable,InteractsWithQueue,Queueable,SerializesModels;
    public $process_id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($process_id)
    {
        $this->process_id = $process_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        
        $process = Process::find($this->process_id);
      //look for all provinces
      $provinces = Province::all();
      //cicle them
      foreach($provinces as $province)
      {
          //questa query mi dà una collection con tutti i movimenti per quel mese/anno/provincia
          $movements = Movement::where('process_id','=',$process->id)->where('district',$province['code'])->get();
          $movements = $movements->toArray();

          if(!empty($movements))
          {
              //passo il risultato alla funzione che fa il pdf
              //GENERATEPDFHELPER

              $test = new GeneratePdfHelper($movements);
              $test->create_pdf();
              
          }         
      }
      //Update the record in DB
        $process->update(['is_pdf_generated' => 1]);
    }
}

<?php
namespace app\Helpers; // Your helpers namespace 

use PDF;
use Illuminate\Support\Facades\Storage;


if(!class_exists('GeneratePdfHelper')){

    class GeneratePdfHelper
    {
        public $movements;

        public function __construct(array $movements){
            $this->movements = $movements;
        }

        public function create_pdf(){
        
        //contatore per vedere quanti record ci sono per i movimenti di quel processo per quella provincia
        $count = count($this->movements);
        //totale ritenute e ruolo
        $amount = 0; // ritenute
        $roles = array(); //ruoli

            foreach($this->movements as $key => $movement){
                $amount = $amount + $movement['amount'];
                if(!array_key_exists($movement['position'],$roles)){
                    $roles[$movement['position']] = 0;
                    $roles[$movement['position']] = $roles[$movement['position']] + 1;
                } else {
                    $roles[$movement['position']] = $roles[$movement['position']] + 1;
                }
            }

            $summary = array();
            $summary['amount'] = $amount;
            $summary['count'] = $count;
            $summary['roles'] = $roles;

            $pdf = PDF::loadView('pdf.index',['movements' => $this->movements,'summary' => $summary])->setPaper('a4','landscape');
            $content = $pdf->download()->getOriginalContent();
            Storage::put("processes/{$this->movements[0]['process_id']}/{$this->movements[0]['district']}.pdf",$content);
     
          }        

        }
    }


<!DOCTYPE html>
<html lang="it-IT">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Titolo</title>
<style>
    @page{size:29.7cm 21cm; margin:0px}
    body{margin:0px}
    table {
        table-layout: fixed;
    }
    
</style>
</head>
<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0" style="padding: 0;">
        <div id="wrapper" style="background-color: #ffffff; margin: 0; padding: 10px 0; width: 100%; -webkit-text-size-adjust: none;">
            <div cellpadding="0" cellspacing="0" width="100%">
                <!-- Header -->
                <table cellpadding="0" cellspacing="0" width="100%" id="template_header" style='display: inline-table; background-color: #d4d4d4; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",Helvetica,Roboto,Arial,sans-serif; border-radius: 3px;'>
                    <tr>
                        <td style="padding: 25px;">
                            <h1 style='font-family: "Helvetica Neue",sans-serif; font-size: 35px; line-height: 100%; margin: 0; text-align: left; color: #000; background-color: inherit;'><strong>{{$movements[0]['district']}}</strong></h1>
                        </td>
                        <td style="padding: 25px;">
                            <div style='font-family: "Helvetica Neue",sans-serif; font-size: 25px; line-height: 100%; margin: 0; text-align: right; color: #6b6b6b; background-color: inherit; font-style: italic;'>(Mese di confronto: {{$movements[0]['month_payment']}}/{{$movements[0]['year_payment']}})</div>
                        </td>
                    </tr>
                </table>
                <!-- End Header -->


                <!-- Middle -->
                <table cellpadding="0" cellspacing="0" width="100%" id="template_middle" style='display: inline-table; background-color: #ffffff; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px;'>
                    <tr>
                        <td style="padding: 25px; width: 50%;  vertical-align: top;">
                            <div style='font-family: "Helvetica Neue",sans-serif; font-size: 20px; line-height: 100%; margin: 0; text-align: left; color: #000; background-color: inherit;'>
                                <div style="padding: 8px 0;">
                                    <strong>Iscritti:</strong> {{$summary['count']}}
                                </div>
                                <div style="padding: 8px 0;">
                                    <strong>Nuove iscrizioni:</strong> ?
                                </div>
                            </div>

                            <table cellpadding="0" cellspacing="0" width="100%" style='display: inline-table; background-color: #eaeaea; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px; margin-top: 10px;'>
                                <tr>
                                    <td style="padding: 15px;">
                                        <strong>Ritenute nel mese:</strong> ?
                                    </td>
                                    <td style="padding: 15px;">
                                        <strong>Riattivazioni:</strong> ?
                                    </td>
                                    <td style="padding: 15px;">
                                        <strong>Cessazioni:</strong> ?
                                    </td>
                                </tr>
                            </table>

                            <table cellpadding="0" cellspacing="0" width="100%" style='display: inline-table; background-color: #ffffff; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px; margin-top: 10px;'>
                                <tr>
                                    <td style="width: 70%; padding-right: 5px;">
                                        <table cellpadding="0" cellspacing="0" width="100%" style='display: inline-table; background-color: #eaeaea; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px; padding: 15px;'>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>TOTALE (ritenute rimborsi):</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    {{$summary['amount']}}
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>Quota al Nazionale:</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    ?
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>NETTO per la Sede prov.:</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    €355,62
                                                </td>
                                            </tr>
                                            
                                        </table>
                                    </td>
                                    <td style="width: 30%; padding-left: 5px; vertical-align: top;">
                                        <table cellpadding="0" cellspacing="0" width="100%" style='display: inline-table; background-color: #eaeaea; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px; padding: 15px;'>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>ATA:</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    16
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>DOCENTI:</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    33
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>ITP:</strong>
                                                </td>
                                                <td style="padding: 0; text-align: right;">
                                                    0
                                                </td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" width="100%" style='display: inline-table; background-color: #eaeaea; color: #000; border-bottom: 0; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px; padding: 15px; margin-top: 10px;'>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>Precari:</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    5
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 0 0 10px;">
                                                    <strong>Pensionandi:</strong>
                                                </td>
                                                <td style="padding: 0 0 10px; text-align: right;">
                                                    0
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        <td style="padding: 25px; width: 50%; vertical-align: top;">
                            <div style='font-family: "Helvetica Neue",sans-serif; font-size: 16px; line-height: 120%; margin: 0; text-align: left; color: #000; background-color: inherit; font-style: italic; border: 1px solid; padding: 15px;'>
                                <p style="margin: 0 0 20px;">
                                    Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum.
                                </p>
                                <p style="margin: 0 0 20px;">
                                    Lorem ipsum dolor sit amet,sunt in culpa qui officia deserunt mollit anim id est laborum.
                                </p>
                            </div>
                        </td>
                    </tr>
                </table>
                <!-- End Middle -->


                    <!-- Righe nominativi -->
                    <div style='font-family: "Helvetica Neue",sans-serif; font-size: 20px; line-height: 100%; margin: 0; text-align: left; color: #000; background-color: inherit;'>
                    <strong>1 - RITENUTE NEL Mese</strong>
                    </div>
                            <table cellpadding="0" cellspacing="0" width="100%" id="template_middle" style='display: inline-table; background-color: #ffffff; color: #000; line-height: 100%; vertical-align: middle; font-family: "Helvetica Neue",sans-serif; border-radius: 3px; font-size: 11px; text-transform: uppercase; text-align: left;'>
                                <tr style="background-color: #ffffff; font-style: italic;">
                                    <th style="padding: 10px; border-bottom: 1px solid;  width: 10px;">
                                        Partita
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        SS
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Eta'
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Nominativo
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Qualifica
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Sede di servizio
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Tel sede
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Fax sede
                                    </th>
                                    <th style="padding: 10px; border-bottom: 1px solid;">
                                        Scadenze
                                    </th>
                                </tr>
                                @foreach ($movements as $movement)
                                            <tr style="background-color: #ffffff;">
                                                <td style="padding: 10px;">
                                                    {{$movement['receipt_id']}}
                                                </td>
                                                <td style="padding: 10px;">
                                                    M
                                                </td>
                                                <td style="padding: 10px;">
                                                    54
                                                </td>
                                                <td style="padding: 10px;">
                                                    {{$movement['name_lastname']}}
                                                </td>
                                                <td style="padding: 10px;">
                                                    {{$movement['position']}}
                                                </td>
                                                <td style="padding: 10px;">
                                                    ANIC83300cc Senigallia Marchetti
                                                </td>
                                                <td style="padding: 10px;">
                                                    0717922289
                                                </td>
                                                <td style="padding: 10px;">
                                                    07165487
                                                </td>
                                                <td style="padding: 10px;">
                                                    202106 scadenza contratto
                                                </td>
                                            </tr>
                                            @endforeach
                            </table>
                    <!-- End Righe nominativi -->
            </div>
        </div>
</body>
</html>

解决方法

总的来说,就工作实际实现的目标而言,您的方法似乎是错误的或有点被误解。作业是短期运行的作业,它执行的代码可防止 Http 服务器响应缓慢,并且是一种更具可扩展性的解决方案。这不是非黑即白,但总的来说,长时间运行的任务更适合命令。

您使用了 2000 mb 的内存,这是很多,只要您继续添加模型,它就会更高。而是创建多个执行相同操作的小作业,每个作业将在其自身之后进行清理,因此永远不会超过内存限制,同时还能够同时执行多个 pdf's

为单个 Movement 创建作业。

class GeneratePdfFile implements ShouldQueue
{
    use Dispatchable,InteractsWithQueue,Queueable,SerializesModels;

    public $province;

    public $process_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Province $province,$process_id)
    {
        $this->province = $province;
        $this->process_id = $process_id;
    }

    public function handle() {
      $movements = Movement::where('process_id','=',$process->id)->where('district',$this->province['code'])->get();
      $movements = $movements->toArray();

      if(!empty($movements))
      {
          //passo il risultato alla funzione che fa il pdf
          //GENERATEPDFHELPER

          $test = new GeneratePdfHelper($movements);
          $test->create_pdf();
      }    
    }
}

然后在创建作业时将您的 Province 循环到那里。

foreach($provinces as $province)
{
    dispatch(new GeneratePdfFile($province,$process_id));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-