ruby + Win32ole + officeを使用して、officeファイルを印刷する
(Word, Excel, PowerPointでそれぞれ、メソッド名が違うのはOffice仕様。。。)
試した環境
- Windows2008
- Office2010 standard
- ruby2.0.0
Word
# -*- coding: utf-8 -*-
require 'win32ole'
wd = WIN32OLE.new('Word.Application')
wd.DisplayAlerts = false
# Wordファイルを開く
doc = wd.Documents.Open(:FileName => "C:\\hoge.doc")
wd.Options.PrintBackground = false
# プリンタ設定
wd.WordBASIC.FilePrintSetup(:Printer => "Printer1", :DoNotSetAsSysDefault => 1)
# 印刷
doc.PrintOut
# ファイルclose
doc.Close(false)
wd.Quit
Excel
# -*- coding: utf-8 -*-
require 'win32ole'
xl = WIN32OLE.new('Excel.Application')
xl.DisplayAlerts = false
# Excelファイルを開く
book = xl.Workbooks.Open(:Filename => "C:\\hoge.xls")
# 印刷
book.ActiveSheet.PrintOut(:ActivePrinter => "Printer1")
# ファイルclose
book.Close
xl.Workbooks.Close
xl.Quit
PowerPoint
# -*- coding: utf-8 -*-
require 'win32ole'
pp = WIN32OLE.new('PowerPoint.Application')
pp.Visible = true
pp.DisplayAlerts = false
# PowerPointファイルを開く
prs = pp.Presentations.Open(:FileName => "C:\\hoge.ppt", :WithWindow => false)
prs.PrintOptions.PrintInBackground = false
# プリンタ設定
prs.PrintOptions.ActivePrinter = "Printer1"
# 印刷
prs.PrintOut
# ファイルclose
prs.close
pp.Quit
注意点
- 途中でエラーとかになり、close処理が行われないと、officeプロセス(WORD.exe, EXCEL.exe, POWERPNT.exe)が残る
- ファイルを開く・印刷途中でエラー or 確認ダイアログが出たりすると、そこで処理が止まる(誰もボタンを押せないので)。また、
DisplayAlerts = falseにしても、完全にメッセージの抑止はできない