You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails中修改现有PDF的标题/标签标题(元数据)?

在Rails中修改现有PDF的标题/页眉方案

一、修改浏览器标签显示的标题(PDF文档元数据标题)

浏览器打开PDF时标签显示的标题,对应PDF文件的文档元数据标题,可通过Ruby PDF处理库修改:

方法1:使用HexaPDF库

  1. 在Gemfile添加依赖:
gem 'hexapdf'

执行bundle install完成安装。

  1. 编写修改逻辑:
def update_pdf_metadata_title(existing_pdf_path, new_title, output_pdf_path)
  HexaPDF::Document.open(existing_pdf_path) do |doc|
    doc.info['Title'] = new_title
    doc.write(output_pdf_path)
  end
end

调用该方法修改现有PDF的元数据后,返回修改后的文件给用户,浏览器标签将显示新标题。

方法2:使用Prawn库(适配生成/修改场景)

如果是Prawn生成的PDF,或需要重新渲染内容:

require 'prawn'
require 'prawn/templates'

def render_pdf_with_custom_title(existing_pdf_path, new_title)
  Prawn::Document.new do |pdf|
    pdf.template_pages = existing_pdf_path
    pdf.info[:Title] = new_title
  end.render
end

在控制器中返回时:

send_data render_pdf_with_custom_title('path/to/target.pdf', '自定义PDF标题'),
          filename: 'custom_title.pdf',
          type: 'application/pdf'

二、修改PDF内部的页眉内容

若要修改PDF页面顶部的页眉文本(PDF内容区域内的页眉),可结合读取与重绘操作实现:

使用HexaPDF添加/替换页眉

def update_pdf_header(existing_pdf_path, header_text, output_pdf_path)
  HexaPDF::Document.open(existing_pdf_path) do |doc|
    doc.pages.each do |page|
      # 在页面顶部叠加页眉文本,可调整坐标、字体、对齐方式
      canvas = page.canvas(type: :overlay)
      canvas.font('Helvetica', size: 12)
      canvas.text(header_text, at: [page.box.width/2 - 60, page.box.height - 20], align: :center)
    end
    doc.write(output_pdf_path)
  end
end

注:若需精确替换原有页眉,需结合pdf-reader分析原有页眉的文本位置与区域,再进行覆盖清除操作。

三、通过响应头快速调整浏览器显示名称

若无需修改PDF元数据,仅需让浏览器标签显示自定义名称,可设置响应头的Content-Disposition:

def display_pdf
  target_pdf = Rails.root.join('public', 'original.pdf')
  send_file target_pdf,
            filename: '自定义显示名称.pdf',
            type: 'application/pdf',
            disposition: 'inline' # inline为浏览器打开,attachment为下载
end

部分浏览器会以此文件名作为标签显示的补充,但修改PDF元数据标题的方式更稳定通用。

内容的提问来源于stack exchange,提问作者Salman Saeed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:45:21