将 PDF 文件转换为 HTML 格式并保存至 Drupal 节点字段

浅磊吖_5519

浅磊吖_5519

2026-09-03

194人浏览

原创

将 PDF 文件转换为 HTML 格式并保存至 Drupal 节点字段

本文介绍如何在 Drupal 自定义模块中,通过系统命令 pdftohtml 将用户上传的 PDF 文件精准转换为保留排版结构的 HTML,并存入 field_decision_text 字段,实现格式无损的内容迁移。

本文介绍如何在 drupal 自定义模块中,通过系统命令 `pdftohtml` 将用户上传的 pdf 文件精准转换为保留排版结构的 html,并存入 `field_decision_text` 字段,实现格式无损的内容迁移。

在 Drupal 中直接将 PDF 转为高质量 HTML(而非纯文本),关键在于利用成熟的命令行工具链,而非纯 PHP 库(如 TCPDF/Dompdf —— 它们主要用于「生成」PDF,而非「解析」PDF)。pdftohtml(来自 Xpdf 工具集)是业界广泛验证的开源方案,能准确还原 PDF 中的字体、段落、列表、表格及图文混排结构,并输出语义化 HTML + 内联 CSS。

✅ 推荐方案:集成 pdftohtml 命令行工具

首先确保服务器已安装 pdftohtml

# Ubuntu/Debian
sudo apt-get install poppler-utils  # pdftohtml 已包含在 poppler-utils 中

# CentOS/RHEL
sudo yum install poppler-utils

# macOS (via Homebrew)
brew install poppler

✅ 验证安装:运行 which pdftohtmlpdftohtml -v,确认命令可执行。

? 在 Drupal 模块中安全调用转换函数

将以下函数加入你的自定义模块(例如 src/Utility/PdfConverter.php),并确保其可被表单提交处理器调用:

html-ppt-to-pdf
html-ppt-to-pdf

将使用 `

` 约定的 HTML 幻灯片转换为高保真、矢量文本 PDF(使用 Playwright + Chromium 原生 PDF 功能)。

下载
<?php namespace Drupal\your_module\Utility;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use RuntimeException;

class PdfConverter {

  /**
   * Converts a PDF file to HTML using the system 'pdftohtml' command.
   *
   * @param string $pdfFilePath Absolute path to the local PDF file.
   * @return string HTML content (UTF-8 encoded).
   * @throws RuntimeException On command failure or missing binary.
   */
  public static function convertToHtml(string $pdfFilePath): string {
    // Build command with safe argument escaping (array form avoids shell injection)
    $cmd = [
      'pdftohtml',
      '-i',       // ignore images (optional; omit if you need embedded images)
      '-s',       // single HTML file (not split by pages)
      '-noframes',// avoid frame-based layout (better for CMS fields)
      '-stdout',  // output HTML to stdout
      $pdfFilePath,
    ];

    $descriptorspec = [
      1 => ['pipe', 'w'], // stdout → HTML output
      2 => ['pipe', 'w'], // stderr → error logs
    ];

    $process = proc_open($cmd, $descriptorspec, $pipes);
    if (!$process) {
      throw new RuntimeException('Failed to start pdftohtml process.');
    }

    $html = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);

    fclose($pipes[1]);
    fclose($pipes[2]);

    $returnCode = proc_close($process);

    if ($returnCode !== 0) {
      $errorMap = [
        1 => 'Error opening PDF file',
        2 => 'Error writing output',
        3 => 'PDF permission denied',
        98 => 'Out of memory',
        99 => 'Generic conversion error',
      ];
      $message = $errorMap[$returnCode] ?? "pdftohtml exited with code {$returnCode}";
      throw new RuntimeException("{$message}\nSTDERR: {$stderr}");
    }

    // Ensure UTF-8 encoding (pdftohtml usually outputs UTF-8, but normalize)
    if (!mb_check_encoding($html, 'UTF-8')) {
      $html = mb_convert_encoding($html, 'UTF-8', 'auto');
    }

    return $html;
  }

}

?️ 修改表单提交逻辑(整合进 submitForm()

替换你原有代码中 $text = $pdf->getText(); 及后续节点创建部分,如下所示:

use Drupal\node\Entity\Node;
use Drupal\your_module\Utility\PdfConverter;

public function submitForm(array &$form, FormStateInterface $form_state) {
  $file = $form_state->getValue('pdf_file');

  $validators = ['file_validate_extensions' => ['pdf']];
  $new_file = file_save_upload('pdf_file', $validators);

  if ($new_file) {
    $pdf_uri = $new_file[0]->getFileUri();
    $pdf_path = \Drupal::service('file_system')->realpath($pdf_uri);

    try {
      // ✅ Convert PDF → HTML (preserves formatting!)
      $html_content = PdfConverter::convertToHtml($pdf_path);

      // Create node with HTML in field_decision_text
      $node = Node::create([
        'type' => 'decision',
        'title' => $new_file[0]->getFilename(),
        'field_attachment' => [
          'target_id' => $new_file[0]->id(),
        ],
        // ⚠️ Critical: Set format to 'full_html' or your trusted text format
        'field_decision_text' => [
          'value' => $html_content,
          'format' => 'full_html', // ← ensure this format allows <div>, <table>, inline styles, etc.
        ],
      ]);
      $node->save();

      $form_state->setRedirectUrl($node->toUrl());

    } catch (\Exception $e) {
      \Drupal::logger('your_module')->error('PDF to HTML conversion failed: @msg', ['@msg' => $e->getMessage()]);
      $form_state->setErrorByName('pdf_file', $this->t('PDF conversion failed: @error', ['@error' => $e->getMessage()]));
    }

  } else {
    $form_state->setErrorByName('pdf_file', $this->t('Please upload a valid PDF file.'));
  }
}<h3>⚠️ 关键注意事项</h3>
<ul><li>
<strong>文本格式配置</strong>:务必在后台(<code>/admin/config/content/formats/full_html</code>)启用 <code><div>, <code><table>, <code><span></span></code>, <code>style</code> 属性等 HTML 标签与属性,否则 Drupal 会过滤掉 <code>pdftohtml</code> 输出的关键样式和结构。<li>
<strong>文件路径安全</strong>:<code>$pdf_path</code> 必须是<strong>本地绝对路径</strong>(<code>realpath()</code> 已保证),<code>pdftohtml</code> 不支持 URI(如 <code>public://xxx.pdf</code>)。</li>
<li>
<strong>权限与环境</strong>:Web 服务器用户(如 <code>www-data</code>)需有执行 <code>pdftohtml</code> 的权限;若部署在容器或托管环境,请确认该二进制可用且路径在 <code>$PATH</code> 中。</li>
<li>
<strong>性能与大文件</strong>:对超大 PDF(>50MB),建议添加超时控制或异步队列(如 Drupal Queue API),避免请求阻塞。</li>
<li>
<strong>替代方案提示</strong>:若无法安装系统工具,可考虑云 API(如 Adobe PDF Services、PDF.co),但涉及网络调用与密钥管理,不推荐内网/高敏感场景。</li>
<p>通过以上集成,你即可在 Drupal 节点中真实复现 PDF 的视觉层次与语义结构——告别纯文本丢失格式的痛点,迈向专业级文档内容管理。</p>
</table></code>
</div></code>
</li></ul>
</table>
</div>

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!

相关文章

HTML速学教程(入门课程)
HTML速学教程(入门课程)

HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

html

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
html版权符号
html版权符号

html版权符号是“©”,可以在html源文件中直接输入或者从word中复制粘贴过来,php中文网还为大家带来html的相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

2023.06.14

4915

7

html在线编辑器
html在线编辑器

html在线编辑器是用于在线编辑的工具,编辑的内容是基于HTML的文档。它经常被应用于留言板留言、论坛发贴、Blog编写日志或等需要用户输入普通HTML的地方,是Web应用的常用模块之一。php中文网为大家带来了html在线编辑器的相关教程、以及相关文章等内容,供大家免费下载使用。

2023.06.21

2872

4

html网页制作
html网页制作

html网页制作是指使用超文本标记语言来设计和创建网页的过程,html是一种标记语言,它使用标记来描述文档结构和语义,并定义了网页中的各种元素和内容的呈现方式。本专题为大家提供html网页制作的相关的文章、下载、课程内容,供大家免费下载体验。

2023.07.31

2530

5

html空格
html空格

html空格是一种用于在网页中添加间隔和对齐文本的特殊字符,被用于在网页中插入额外的空间,以改变元素之间的排列和对齐方式。本专题为大家提供html空格的相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.01

2559

5

html是什么
html是什么

HTML是一种标准标记语言,用于创建和呈现网页的结构和内容,是互联网发展的基石,为网页开发提供了丰富的功能和灵活性。本专题为大家提供html相关的各种文章、以及下载和课程。

2023.08.11

4539

6

html字体大小怎么设置
html字体大小怎么设置

在网页设计中,字体大小的选择是至关重要的。合理的字体大小不仅可以提升网页的可读性,还能够影响用户对网页整体布局的感知。php中文网将介绍一些常用的方法和技巧,帮助您在HTML中设置合适的字体大小。

2023.08.11

2521

3

html转txt
html转txt

html转txt的方法有使用文本编辑器、使用在线转换工具和使用Python编程。本专题为大家提供html转txt相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.31

2289

3

html文本框代码怎么写
html文本框代码怎么写

html文本框代码:1、单行文本框【<input type="text" style="height:..;width:..;" />】;2、多行文本框【textarea style=";height:;"></textare】。

2023.09.01

2108

6

HTML嵌入CSS样式的方法
HTML嵌入CSS样式的方法

HTML嵌入CSS样式的方法有内联样式、内部样式表和外部样式表。本专题为大家提供CSS样式相关的文章、下载、课程内容,供大家免费下载体验。

2023.09.20

2068

5

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
GDB 17.2 官方文档集合
GDB 17.2 官方文档集合

共0课时 | 0人学习

Bootstrap 入门安装配置
Bootstrap 入门安装配置

共0课时 | 0人学习

38+ PhpStorm 提示和技巧
38+ PhpStorm 提示和技巧

共1课时 | 204人学习