GUIからPDFファイルを開きたい
IronPythonで作ったGUI上のボタンを押すと、PDFファイルを開くようにしたい。PDFファイルを開くためにはどうすればいいのかというところがポイントになるが、Process.Startを使うと、指定した文書を関連づけられた外部プログラムで起動できるようなので、このまま使ってみる。
ソースコードは以下の通り。
ボタンが一つ置かれており、それを押すとAcrobat readerが起動して内部でパスが指定されているPDFファイルが開く。
import clr clr.AddReference('System.Windows.Forms') clr.AddReference('System.Drawing') clr.AddReference('System') import System.Drawing import System.Windows.Forms import System.Diagnostics from System.Drawing import * from System.Windows.Forms import * from System.Diagnostics import Process from System.Windows.Forms import Application class MainForm(Form): def __init__(self): self.InitializeComponent() def InitializeComponent(self): self._button1 = System.Windows.Forms.Button() self.SuspendLayout() # # button1 # self._button1.Location = System.Drawing.Point(53, 83) self._button1.Name = "button1" self._button1.Size = System.Drawing.Size(175, 56) self._button1.TabIndex = 0 self._button1.Text = "button1" self._button1.UseVisualStyleBackColor = True self._button1.Click += self.Button1Click # # MainForm # self.ClientSize = System.Drawing.Size(284, 262) self.Controls.Add(self._button1) self.Name = "MainForm" self.Text = "test4" self.ResumeLayout(False) def Button1Click(self, sender, e): filename = "D:/Temp/test.pdf" Process.Start(filename); Application.EnableVisualStyles() form = MainForm() Application.Run(form)
Process.Startメソッドを使うために、最初、
clr.AddReference('System.Diagnostics')
としていたが、これだとエラーで動かない。この代わりに
clr.AddReference('System')
としなければいけなかった。
この場合はPDFファイルを開いたが、PDFに限らずどんな文書でもProcess.Startで開けるはずだ。指定したファイル拡張子に関連づけられたプログラムが自動的に起動する。