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仅仅替换了空格,还须要改进。