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

落芳姑娘_6447

落芳姑娘_6447

2026-09-01

256人浏览

原创

将 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 解析」,因此无法满足从 PDF 提取带样式 HTML 的需求。真正可行的方案是借助成熟的命令行工具 pdftohtml(Xpdf 工具集的一部分),它能将 PDF 转换为语义化 HTML(含内联 CSS、div 布局、字体声明等),最大程度还原原始排版。

✅ 前置依赖:安装 pdftohtml

确保服务器已安装 pdftohtml(非 PHP 扩展):

# Ubuntu/Debian
sudo apt-get install xpdf

# CentOS/RHEL
sudo yum install xpdf

# macOS (Homebrew)
brew install xpdf

验证安装:

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

将使用 `

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

下载
pdftohtml -v
# 应输出版本信息,如:pdftohtml version 4.04

✅ 核心转换函数(安全、可调试、符合 Drupal 8+/9+ PSR-4 规范)

将以下函数放入您的模块服务类或工具类中(推荐 src/Utility/PdfToHtmlConverter.php):

<?php namespace Drupal\your_module\Utility;

use RuntimeException;

class PdfToHtmlConverter {

  /**
   * Converts a local PDF file to HTML using the system pdftohtml binary.
   *
   * @param string $pdfFilePath Absolute path to the PDF file on disk.
   * @return string HTML content with embedded styles and structure.
   * @throws RuntimeException If conversion fails or binary is missing.
   */
  public static function convert(string $pdfFilePath): string {
    // Use array syntax for automatic shell escaping (PHP 7.4+, safer than string concat).
    $cmd = [
      'pdftohtml',
      '-i',        // ignore images (optional; omit if you need img tags)
      '-s',        // generate single HTML file (not split by pages)
      '-noframes', // avoid <frameset> — better for Drupal WYSIWYG compatibility
      '-stdout',   // output HTML to stdout (no temp files)
      $pdfFilePath,
    ];

    $descriptorspec = [
      1 => ['pipe', 'w'], // stdout → capture HTML
      2 => ['pipe', 'w'], // stderr → capture errors
    ];

    $process = proc_open($cmd, $descriptorspec, $pipes);
    if (!$process) {
      throw new RuntimeException('Failed to launch 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 permissions error',
        98 => 'Out of memory',
        99 => 'General conversion error',
      ];
      $message = $errorMap[$returnCode] ?? "pdftohtml exited with code {$returnCode}";
      throw new RuntimeException("{$message}. Stderr: {$stderr}");
    }

    // Optional: sanitize output (remove DOCTYPE, html/body tags if field expects fragment)
    $html = preg_replace('/^^>]*>\s*]*>\s*]*>\s*|\s*\s*\s*$/is', '', $html);
    return trim($html);
  }

}

✅ 集成到表单提交逻辑(替换原 submitForm 方法)

在您的表单类 submitForm() 中,替换原有文本提取逻辑,改用 HTML 转换:

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

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

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

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

    try {
      // ✅ Convert PDF → HTML (preserves fonts, tables, spacing, headings)
      $html_content = PdfToHtmlConverter::convert($pdf_path);

      // Create node with HTML in formatted text field
      $node = Node::create([
        'type' => 'decision',
        'title' => $uploaded_file->getFilename(),
        'field_attachment' => [
          'target_id' => $uploaded_file->id(),
        ],
        'field_decision_text' => [
          'value' => $html_content,
          'format' => 'full_html', // ⚠️ Ensure this format allows <div>, <style>, etc.
        ],
      ]);
      $node->save();

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

    } catch (\Exception $e) {
      $this->messenger()->addError(t('PDF to HTML conversion failed: @msg', ['@msg' => $e->getMessage()]));
      $form_state->setRebuild(TRUE);
    }

  } else {
    $form_state->setErrorByName('pdf_file', $this->t('Please upload a valid PDF file.'));
  }
}<h3>⚠️ 关键注意事项<ul><li><strong>文本格式配置:确保 <code>field_decision_text 字段的「文本处理」设置为 <code>full_html 或自定义允许 <code><div><span><style> 等标签的格式,否则 HTML 将被过滤。<li><strong>权限与路径:<code>pdftohtml 必须对 Web 服务器用户(如 <code>www-data)可执行;若报 <code>command not found,请改用绝对路径(如 <code>/usr/bin/pdftohtml)。<li><strong>安全性提醒:仅对可信来源的 PDF 使用此功能;生产环境建议添加文件大小限制(<code>file_validate_size)和超时控制(<code>proc_open 可配合 <code>stream_set_timeout)。<li><strong>替代方案提示:若无法安装系统工具,可考虑 <a href="https://www.php.cn/link/bee8b66bf9167983003870d045f2acb1" rel="nofollow" target="_blank">pdf2htmlEX(更现代,支持 CSS3/HTML5),调用方式类似,仅需替换命令名与参数。<p>通过该方案,您将获得结构完整、样式内联、语义清晰的 HTML 内容,完美嵌入 Drupal 节点字段,真正实现「PDF 原样复刻为网页内容」的目标。
</style>
</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人学习