Techioz Blog

Ruby: REST API 経由で PDF 請求書をダウンロード (電子経済)

概要

会計ポータルの e-conomic から Ruby スクリプトを使用して PDF 請求書をダウンロードしようとしています。 REST API を使用しているので、請求書の PDF の URL を見つけることができます。

ただし、どうやってダウンロードすればよいのかわかりません。 PDF URL を使用して「GET」ステートメントを直接参照すると、大量の意味のないデータ (Ruby 出力で表される PDF 自体である可能性があります) を出力できます。

PDF ファイルを PC のローカル フォルダーにダウンロードする方法はありますか?

ありがとう、

マーティン

RUBY コード: 以下を使用すると、前述のような無意味な出力が出力されます。

hHeader = {"X-AppSecretToken" => '[TOKEN]', "X-AgreementGrantToken" => '[TOKEN]', "Content-Type" => 'application/json'}
puts hTest = RestClient.get("https://restapi.e-conomic.com/invoices/booked/10000/pdf", hHeader)

解決策

おっと、間違った質問に答えてしまいました。次のように PDF ファイルをダウンロードしてローカル ファイルに書き込むことができます。

File.open('some_name.pdf', 'wb') do |local_f|
  open('http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf', 'rb') do |pdf|
    local_f << pdf.read
  end
end

========

はい、PDF ファイルはプレーンテキスト ファイルのように読むことができません。 pdfファイルは特殊な形式のファイルです。 pdf-reader gem を使用して PDF ファイルをデコードできます。

require 'pdf-reader'
require 'open-uri'
require 'pp'

open('http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf') do |f|
  p f.read(100)  #Gibberish

  reader = PDF::Reader.new(f)
  pp reader.info  #A hash

  reader.pages.each do |page|
    puts page.text
  end

end

--output:--
"%PDF-1.3\r%\xE2\xE3\xCF\xD3\r\n7 0 obj\r<</Linearized 1/L 7945/O 9/E 3524/N 1/T 7656/H [ 451 137]>>\rendobj\r         "

{:Author=>"cdaily",
 :CreationDate=>"D:20000629102108+11'00'",
 :Creator=>"Microsoft Word 8.0",
 :ModDate=>"D:20131028152413-04'00'",
 :Producer=>"Acrobat Distiller 4.0 for Windows",
 :Title=>"This is a test PDF file"}


                         Adobe Acrobat PDF Files

Adobe® Portable Document Format (PDF) is a universal file format that preserves all
of the fonts, formatting, colours and graphics of any source document, regardless of
the application and platform used to create it.


Adobe PDF is an ideal format for electronic document distribution as it overcomes the
problems commonly encountered with electronic file sharing.

•   Anyone, anywhere can open a PDF file. All you need is the free Adobe Acrobat
    Reader. Recipients of other file formats sometimes can't open files because they
    don't have the applications used to create the documents.


•   PDF files always print correctly on any printing device.

•   PDF files always display exactly as created, regardless of fonts, software, and
    operating systems. Fonts, and graphics are not lost due to platform, software, and
    version incompatibilities.


•   The free Acrobat Reader is easy to download and can be freely distributed by
    anyone.

•   Compact PDF files are smaller than their source files and download a
    page at a time for fast display on the Web.