
本文介绍如何在 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 pdftohtml或pdftohtml -v,确认命令可执行。
? 在 Drupal 模块中安全调用转换函数
将以下函数加入你的自定义模块(例如 src/Utility/PdfConverter.php),并确保其可被表单提交处理器调用:
<?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实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











