HTML 内容如何作为附件响应返回以下载 pdf 和 docx

时间:2020-12-30 16:07:44

标签: php symfony phpword

在我的 php symphony 项目中,我想将 html 模板下载为 pdf 和 docx。

docx 使用 - PhpOffice\PhpWord\PhpWord;

pdf 使用 - PDFBuilder;

步骤

  1. 使用模板 ID 将 HTML 保存在表格中。
  2. 获取带有模板 ID 的 html 内容。
  3. 相同的 html 模板应该能够导出为 docx 和 pdf。
  4. 将文档内容作为附件响应返回给控制器。

了解流程的 1&2 个步骤,我的问题与 3&4 相关

我有

  • 父类 - DocumentExporter
  • 子类是 - DocxExporter 和 PDFExporter

在子类中有3个函数

  • DocxExporter -> getDocxBuilder、getDocx、exportDocument

  • PDFExporter -> getPdfBuilder、getPDF、exportDocument

    在DocxExporter中;

    const DEFAULT_HEADER = 'application/octet-stream';
    
    protected function getDocx($content, array $sectionStyle) {
    
      $section = $this->getDocxBuilder()->addSection($sectionStyle);
      $content = preg_replace("/<table\s(.+?)>(.+?)<\/table>/is",
          "<table style=\"border: 6px #000000 solid;\">$2</table>", $content);
      $content = str_replace("<p><div style=' page-break-after:always !important;'></div></p>",
          "<pagebreak></pagebreak>", $content);
      $content = str_replace("&nbsp", " ", $content);
    
      Html::addHtml($section, $content, false, false);
    
      header('Content-Type: ' . self::DEFAULT_HEADER);
      header('Content-Disposition: attachment;filename="' . $this->getExportFileName() . '.docx"');
    
      $objWriter = IOFactory::createWriter($this->docxBuilder, 'Word2007');
      $objWriter->save('php://output');}
    

在 PDFExporter 中;

   const DEFAULT_HEADER = 'application/pdf';

   protected function getPDF($content, $pageParamArray): AttachmentResponse {
    $this->pdfBuilder = $this->getPdfBuilder();
    $this->pdfBuilder->setPageOptions($pageParamArray);
    $pdf = $this->pdfBuilder->createPDFData(null, null, $content);
    $response = new AttachmentResponse(['data' => $pdf]);
    $response->setContentType(self::DEFAULT_HEADER);
    $response->setAttachmentName(parent::getExportFileName() . '.pdf');

    return $response;   }

我试图让 getDocx 函数也像 PDFExporterclass 一样返回一个 AttachmentResponse。但无法确定获得相同响应的正确方法。现在在端点我得到一个附件响应和 null 分别为 pdf 和 docx。如何更改 docx 函数以返回附件响应。

0 个答案:

没有答案
相关问题