首页
/ Grim 使用与技术文档

Grim 使用与技术文档

2024-12-26 12:06:13作者:钟日瑜

1. 安装指南

在开始使用 Grim 之前,您需要确保已经安装了 ghostscript、imagemagick 和 xpdf。在 Mac (OSX) 系统上,推荐使用 Homebrew 来安装这些依赖项:

$ brew install ghostscript imagemagick xpdf

安装完依赖项后,您可以使用以下命令安装 Grim:

$ gem install grim

2. 项目使用说明

Grim 是一个简单的 Ruby gem,用于从 PDF 中提取页面并将其转换为图片,同时还可以提取页面上的文本内容。以下是基本的使用方法:

pdf = Grim.reap("/path/to/pdf") # 返回一个 Grim::Pdf 实例
count = pdf.count # 返回 PDF 中的页面数
png = pdf[3].save('/path/to/image.png') # 将页面 3 保存为图片,返回 true 或 false
text = pdf[3].text # 返回页面 3 的文本内容

pdf.each do |page|
  puts page.text
end

Grim 还支持使用其他处理器(默认使用系统路径中的 Imagemagick 和 Ghostscript 版本)。

# 指定一个处理器及其对应的 ImageMagick 和 Ghostscript 路径
Grim.processor = Grim::ImageMagickProcessor.new({:imagemagick_path => "/path/to/convert", :ghostscript_path => "/path/to/gs"})

# 指定多个处理器,如果第一个失败则使用备选处理器,适用于需要多个版本的 convert/gs
Grim.processor = Grim::MultiProcessor.new([
  Grim::ImageMagickProcessor.new({:imagemagick_path => "/path/to/6.7/convert", :ghostscript_path => "/path/to/9.04/gs"}),
  Grim::ImageMagickProcessor.new({:imagemagick_path => "/path/to/6.6/convert", :ghostscript_path => "/path/to/9.02/gs"})
])

3. 项目 API 使用文档

以下是 Grim 提供的 API 使用文档:

  • Grim.reap("/path/to/pdf"):从指定的 PDF 文件中提取页面并返回一个 Grim::Pdf 实例。
  • pdf.count:返回 PDF 中的页面数。
  • pdf[3].save('/path/to/image.png'):将指定的 PDF 页面保存为图片。
  • pdf[3].text:返回指定 PDF 页面的文本内容。

Grim::ImageMagickProcessor#save 支持以下选项:

pdf = Grim.reap("/path/to/pdf")
pdf[0].save('/path/to/image.png', {
  :width => 600,         # 默认为 1024
  :density => 72,        # 默认为 300
  :quality => 60,        # 默认为 90
  :colorspace => "CMYK", # 默认为 "RGB"
  :alpha => "Activate"   # 未设置时不使用
})

Grim 还支持日志记录功能,默认日志记录器为 Grim::NullLogger,但您可以设置自己的日志记录器:

require "logger"
Grim.logger = Logger.new($stdout).tap { |logger| logger.progname = 'Grim' }
Grim.processor = Grim::ImageMagickProcessor.new({:ghostscript_path => "/path/to/bin/gs"})
pdf = Grim.reap("/path/to/pdf")
pdf[3].save('/path/to/image.png')

4. 项目安装方式

Grim 的安装方式如下:

  • 确保 ghostscript、imagemagick 和 xpdf 已经安装。
  • 使用以下命令安装 Grim:
$ gem install grim
登录后查看全文
热门项目推荐