Linux下,能夠藉助: unoconv # Converter between LibreOffice document formats
來自小西山子【http://www.cnblogs.com/xesam/】 linux
因爲linux上處理word和ppt比較麻煩,並且有文件格式專利的問題,因此如下操做所有在Windows下面進行。 shell
首先須要安裝Microsoft Save as PDF加載項,官方下載地址:http://www.microsoft.com/zh-cn/download/details.aspx?id=7 ui
安裝成功後能夠手工將文檔另存爲pdf。 spa
須要引用「Win32::OLE」模塊 code
use Win32::OLE; use Win32::OLE::Const 'Microsoft Word'; use Win32::OLE::Const 'Microsoft PowerPoint';
word轉pdf: orm
sub word2pdf{ my $word_file = $_[0]; my $word = CreateObject Win32::OLE 'Word.Application' or die $!; $word->{'Visible'} = 0; my $document = $word->Documents->Open($word_file) || die("Unable to open document ") ; my $pdffile = $word_file.".pdf"; $document->saveas({FileName=>$pdffile,FileFormat=>wdExportFormatPDF}); $document -> close ({SaveChanges=>wdDoNotSaveChanges}); $word->quit(); }
ppt轉pdf blog
sub ppt2pdf{ my $word_file = $_[0]; my $word = CreateObject Win32::OLE 'PowerPoint.Application' or die $!; $word->{'Visible'} = 1; my $document = $word->Presentations->Open($word_file) || die("Unable to open document ") ; my $pdffile = $word_file.".pdf"; $document->saveas($pdffile,32); $document -> close ({SaveChanges=>wdDoNotSaveChanges}); $word->quit(); }
注意事項: 文檔
一、PPT轉換中若是設置powerpoint不顯示,即$word->{'Visible'} = 0,會致使轉換失敗。 get
二、若是使用完整的路徑,路徑名中不能有空格以及「%」等特殊符號,否則沒法打開文檔。 it
轉換當前文件夾下的文件:
use Cwd; my $dirname = getcwd(); @files = glob "*.doc"; foreach (@files){ print $dirname.'/'.$_, "\n"; word2pdf($dirname.'/'.$_); }
若是要同時轉換子文件夾的文件,能夠先遍歷,而後再轉換:
use File::Find; find(sub { word2pdf($File::Find::name) if /\.(doc|docx)/; ppt2pdf($File::Find::name) if /\.(ppt|pptx)/; }, "D:/test");
爲了不屢次重複打開word,能夠先獲取全部須要轉換的文檔,集中轉換:
find(sub { push(@file_word, $File::Find::name) if /\.(doc|docx)/; }, "D:/test"); word2pdf(@file_word); sub deleteSpace{ my $filename = $_[0]; my @temp = split(/\//, $filename); my $filename_without_path = pop(@temp); $filename_without_path =~ s/\s+//g; join('/', @temp).'/'.$filename_without_path; } sub word2pdf{ my @files = @_; my $word = CreateObject Win32::OLE 'Word.Application' or die $!; $word->{'Visible'} = 0; foreach (@files){ my $new_name = deleteSpace($_); rename($_, $new_name); print $new_name, "\n"; my $document = $word->Documents->Open($new_name) || die "can not open document"; my $pdffile = $new_name.".pdf"; $document->saveas({FileName=>$pdffile,FileFormat=>wdExportFormatPDF}); $document -> close ({SaveChanges=>wdDoNotSaveChanges}); } $word->quit(); }
也能夠換一種實現,先調用chdir到子目錄中,而後在子目錄中進行轉換,能夠避免目錄有不合法字符致使的轉換失敗,不過文件名的不合法字符致使的失敗也不可避免,因此以上的各類轉換,都須要先提出空格以及特殊字符才行,deleteSpace僅僅替換了空格,還須要改進。