WordファイルやExcelファイルを一括でPDFに変換するRubyスクリプト
年度末ですね!年度末といえば納品の時期です。
おれが現在担当しているお客さんは資料一式をPDFで欲しいという希望なので
大量のWordファイルやExcelファイルを一括でPDFに変換したかったのですが
軽く調べてみても、有料のソフトを使う方法しか見つけることができませんでした。
というわけで、Win32OLE経由でOffice2007のPDF保存アドインを叩き、一括でWord/ExcelファイルをPDFに変換するRubyスクリプトを書いてみました。
少し調べてみた感じでは、多少の需要はありそうでしたので公開しておきます。
仕組み上、Office2007とPDF保存アドインが必要です。
必要なもの
- Office 2007
- PDF保存アドイン
- Rubyインタプリタ
Wordファイルを一括でPDFに変換する
#!ruby -Ks require "win32ole" word = WIN32OLE.new("Word.Application") begin Dir.glob("*.doc") do |fn| doc_fullpath = File.expand_path(fn) pdf_fullpath = doc_fullpath.gsub(/\.doc$/, ".pdf") begin doc = word.Documents.Open(doc_fullpath) doc.ExportAsFixedFormat({ "OutputFileName" => pdf_fullpath, "ExportFormat" => 17, "OpenAfterExport" => false }) puts "success: #{fn}" rescue puts "fail: #{fn}" ensure doc.Close end end ensure word.Quit end
Excelファイルを一括でPDFに変換する
#!ruby -Ks require "win32ole" excel = WIN32OLE.new("Excel.Application") begin Dir.glob("*.xls") do |fn| xls_fullpath = File.expand_path(fn) pdf_fullpath = xls_fullpath.gsub(/\.xls$/, ".pdf") begin book = excel.Workbooks.Open(xls_fullpath) book.ExportAsFixedFormat({ "FileName" => pdf_fullpath, "Type" => 0, "OpenAfterPublish" => false }) puts "success: #{fn}" rescue puts "fail: #{fn}" ensure book.Close end end ensure excel.Quit end