【问题标题】:render PDF and attach to email (using DOMPDFModule and EmailZF2)呈现 PDF 并附加到电子邮件(使用 DOMPDFModule 和 EmailZF2)
【发布时间】:2013-08-22 08:27:26
【问题描述】:

ZF2 中,我尝试使用DOMPDFModule 生成PDF 并使用EmailZF2 发送电子邮件。

这是我在控制器中所做的:

// fetch data
$user = $this->getEntityManager()->getRepository('Application\Entity\Users')->find(1);
$address = $this->getEntityManager()->getRepository('Application\Entity\Addresses')->find(1);

// generate PDF
$pdf = new PdfModel();
$pdf->setOption('filename', 'Renter_application-report-' . date("Y_m_d"));
$pdf->setOption('paperSize', 'a4');
$pdf->setVariables(array(
    'User' => $user,
    'Address' => $address,
));

到目前为止一切都很好,但是DOMPDFModule 需要我到return $pdf 来提示生成的PDF,并且DOMPDF 似乎都不起作用(例如$pdf->render()$pdf->output())。

我也尝试自己不成功地渲染视图,如下所示(可能是标题生成问题?)

// Render PDF
$pdfView = new ViewModel($pdf);
$pdfView->setTerminal(true)
    ->setTemplate('Application/index/pdf')
    ->setVariables(array(
        'User' => $user,
        'Address' => $address,
    ));
$pdfOutput = $this->getServiceLocator()
    ->get('viewrenderer')
    ->render($pdfView);

最后,我们的目标是获取这个呈现的 PDF 并将其保存在某个地方以便能够附加或立即附加它 - 甚至像这样简单

// Save PDF to disk
$file_to_save = '/path/to/pdf/file.pdf';
file_put_contents($file_to_save, $pdfOutput);

// Send Email
$view = new ViewModel(array(
    'name' => $User->getName(),
));
$view->setTerminal(true);
$view->setTemplate('Application/view/emails/user');
$this->mailerZF2()->send(array(
    'to' => $User->getEmail(),
    'subject' => 'Test email'
), $view, $file_to_save);

我设法通过编辑文件\src\EmailZF2\Controller\Plugin\Mailer.php 来附加PDF:

...
public function send($data = array(), $viewModel, $pdf)
...
if($pdf && file_exists($pdf)) {
    $pdf = fopen($pdf, 'r');
    $MessageAttachment = new MimePart($pdf);
    $MessageAttachment->type = 'application/pdf';
    $MessageAttachment->filename = 'output.pdf';
    $MessageAttachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
    $MessageAttachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
}
...

$body_html = new MimeMessage();
$body_html->setParts(array($text, $html, $MessageAttachment));

感谢您的帮助,谢谢! :)

【问题讨论】:

    标签: pdf-generation zend-framework2 dompdf


    【解决方案1】:

    我不知道这个 id 是否正确,但我设法让它工作,所以我会发布我们是如何做到的,以防其他人遇到同样的问题。

    我使用 DOMPDFModule 作为基础引擎,然后在控制器中,在生成 PDF 的操作中,我通过 Viewmodel 渲染 PDF 以使用视图脚本作为模板

    use Zend\View\Model\ViewModel,
        DOMPDFModule\View\Model\PdfModel;
    
    ...
    
    public function indexAction()
    {
    
        $User = $this->getEntityManager()->getRepository('Application\Entity\Users')->find(1);
    
        // generate PDF
        $pdf = new PdfModel();
        $pdf->setOption('filename', 'user_details-' . date("Y_m_d"));
        $pdf->setOption('paperSize', 'a4');
        $pdf->setVariables(array(
            'User' => $User,
        ));
    
        // Render PDF
        $pdfView = new ViewModel($pdf);
        $pdfView->setTerminal(true)
            ->setTemplate('Application/index/pdf.phtml')
            ->setVariables(array(
                'User' => $User,
            ));
        $html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdfView);
        $eng = $this->getServiceLocator()->get('viewpdfrenderer')->getEngine();
    
        $eng->load_html($html);
        $eng->render();
        $pdfCode = $eng->output();
    
        // Send the email
        $mailer->sendEmail($User->getId(), $pdfCode);
    
    }
    

    emailzf2 模块也已被弃用,自定义邮件模块现在管理电子邮件的附件和发送。为此,在Mailer/config/module.config.php 中注册了一个新服务:

    'view_manager' => array(
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
    'service_manager' => array(       
        'factories' => array(
             __NAMESPACE__ . '\Service\MailerService' => __NAMESPACE__ . '\Service\MailerServiceFactory',
        ),
    ),
    

    哪些引用了文件Mailer/src/Mailer/Service/MailerServiceFactory.php:

    <?php
    namespace Mailer\Service;
    
    use Mailer\Service\MailerService;
    use Zend\ServiceManager\FactoryInterface;
    use Zend\ServiceManager\ServiceLocatorInterface;
    
    class MailerServiceFactory implements FactoryInterface
    {
        public function createService(ServiceLocatorInterface $serviceLocator)
        {
            $entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
            $viewRenderer = $serviceLocator->get('ViewRenderer');
            $config = $serviceLocator->get('config');
            return new MailerService($entityManager, $viewRenderer, $config);
        }
    }
    

    还有Mailer/src/Mailer/Service/MailerService.php:

    use Zend\Mime\Message as MimeMessage; 
    use Zend\View\Model\ViewModel;
    
    class MailerService
    {
        protected $em;
        protected $view;
        protected $config;
        protected $options;
        protected $senderName;
        protected $senderEmail;
    
         public function __construct(\Doctrine\ORM\EntityManager $entityManager, $viewRenderer, $config) 
         {
            $this->em = $entityManager;
            $this->view = $viewRenderer;
            $this->config = $config;
    
            $this->options = array(
                                        'name' => $config['mailer']['smtp_host'],
                                );
            $this->senderName = $config['mailer']['sender']['from_name'];
            $this->senderEmail = $config['mailer']['sender']['from_address'];
         }
    
    
         protected function send($fromAddress, $fromName, $toAddress, $toName, $subject, $bodyParts)
        {
            // setup SMTP options
            $options = new Mail\Transport\SmtpOptions($this->options);
    
            $mail = new Mail\Message();
            $mail->setBody($bodyParts);
            $mail->setFrom($fromAddress, $fromName);
            $mail->setTo($toAddress, $toName);
            $mail->setSubject($subject);
    
            $transport = new Mail\Transport\Smtp($options);
            $transport->send($mail);
        }
    
        protected function setBodyHtml($content, $pdf = null, $pdfFilename = null) {
    
            $html = new MimePart($content);
            $html->type = "text/html";
    
            $body = new MimeMessage();
    
            if ($pdf != '') {
                $pdfAttach = new MimePart($pdf);
                $pdfAttach->type = 'application/pdf';
                $pdfAttach->filename = $pdfFilename;
                $pdfAttach->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
                $pdfAttach->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
    
                $body->setParts(array($html, $pdfAttach));
    
            } else {
    
                $body->setParts(array($html));
            }
    
            return $body;
        }
    
        public function sendEmail($UserId)
        {
            $User = $this->em->getRepository('Application\Entity\Users')->find($UserId);
            $vars = array(  'firstname'     => $User->getFirstname(),
                            'lastname'         => $User->getLastname());
            $content = $this->view->render('emails/user-profile', $vars);
    
            $body = $this->setBodyHtml($content);
    
            $sendToName = $User->getOaFirstname() .' '. $User->getLastname();
    
            $this->send($this->senderEmail, $this->senderName, $User->getEmailAddress(), $sendToName, 'User profile', $body);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2017-11-01
      • 2018-06-24
      • 2012-05-23
      相关资源
      最近更新 更多