Module: VivlioStarter::CLI::Build::QpdfJson

Defined in:
lib/vivlio_starter/cli/build/qpdf_json.rb

Class Method Summary collapse

Class Method Details

.apply!(pdf_path, header, updates) ⇒ Boolean

差分更新を適用し、元ファイルを置き換える。

Parameters:

  • pdf_path (String)

    更新対象(成功時に上書きされる)

  • header (Hash)

    read で得たヘッダ(maxobjectid 等)

  • updates (Hash)

    "obj:N G R" => => … のマップ

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/vivlio_starter/cli/build/qpdf_json.rb', line 62

def apply!(pdf_path, header, updates)
  Tempfile.create(['vs-qpdf-update', '.json']) do |json|
    json.write(JSON.generate({ 'version' => 2, 'qpdf' => [header, updates] }))
    json.flush

    updated = "#{pdf_path}.qpdf.tmp.pdf"
    success = system('qpdf', pdf_path, updated, "--update-from-json=#{json.path}",
                     out: File::NULL, err: File::NULL)

    if success && File.exist?(updated)
      FileUtils.mv(updated, pdf_path)
      true
    else
      FileUtils.rm_f(updated)
      Common.log_warn('[qpdf] --update-from-json の適用に失敗しました')
      false
    end
  end
end

.read(pdf_path) ⇒ Array(Hash, Hash, Array<Hash>)?

PDF の構造を読む(ストリーム本体は読まないので大きな PDF でも軽い)。

Parameters:

  • pdf_path (String)

Returns:

  • (Array(Hash, Hash, Array<Hash>), nil)

    [header, objects, pages]。失敗時 nil



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/vivlio_starter/cli/build/qpdf_json.rb', line 35

def read(pdf_path)
  unless File.exist?(pdf_path)
    Common.log_warn("[qpdf] PDF が見つかりません: #{pdf_path}")
    return nil
  end

  out, status = Open3.capture2('qpdf', pdf_path, '--json=2', '--json-key=qpdf',
                               '--json-key=pages', '--json-stream-data=none')
  unless status.success?
    Common.log_warn("[qpdf] PDF 構造を読み取れませんでした: #{pdf_path}")
    return nil
  end

  document = JSON.parse(out)
  header, objects = document['qpdf']
  [header, objects, document['pages']]
rescue StandardError => e
  Common.log_warn("[qpdf] PDF 構造の取得に失敗: #{e.message}")
  nil
end