為什麼要寫第二個版本呢,當時再完成項目時,比較趕,沒有多考慮,就借用cscript方式寫了個腳本,現在該項目已經開完評審會,有時間重新将該程式重寫,直接使用純C#來完成.
當時由于在使用ACRODISTXLib.PdfDistillerClass發生錯誤,主要是轉換一篇文檔後,無法釋放,再次調用時發生錯誤.
同第一版一樣,安裝需要的環境,注意其中提到的安裝列印機.以下代碼并沒有提供目前的列印機,而是使用系統預設的,即設定的"MS Publisher Color Printer".
注意必須添加引用Acrobat Distiller與WORD,本人使用的是WORD2003
using oWord = Microsoft.Office.Interop.Word;
private void WordConvert()
{
oWord.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
Type wordType= word.GetType();
//打開WORD文檔
/*對應腳本中的
var word = new ActiveXObject("Word.Application");
var doc = word.Documents.Open(docfile);
*/
oWord.Documents docs = word.Documents;
Type docsType = docs.GetType();
object objDocName = @"c:\test.doc";
oWord.Document doc = (oWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] {objDocName, true, true});
//列印輸出到指定檔案
//你可以使用 doc.PrintOut();方法,次方法調用中的參數設定較繁瑣,建議使用 Type.InvokeMember 來調用時可以不用将PrintOut的參數設定全,隻設定4個主要參數
Type docType = doc.GetType();
object printFileName = @"c:\test.ps";
docType.InvokeMember("PrintOut",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{false,false,oWord.WdPrintOutRange.wdPrintAllDocument,printFileName});
//new object[]{false,false,oWord.WdPrintOutRange.wdPrintAllDocument,printFileName}
//對應腳本中的word.PrintOut(false, false, 0, psfile);的參數
//退出WORD
//對應腳本中的word.Quit();
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,null, word, null);
object o1= "c:\\test.ps";
object o2= "c:\\test.pdf";
object o3= "";
//引用将PS轉換成PDF的對象
//try catch之間對應的是腳本中的 PDF.FileToPDF(psfile,pdffile,""); //你可以使用 pdfConvert.FileToPDF("c:\\test.ps","c:\\test.pdf","");這樣的轉換方法,本人隻是為了保持與WORD相同的調用方式
try
{
ACRODISTXLib.PdfDistillerClass pdf = new ACRODISTXLib.PdfDistillerClass();
Type pdfType = pdfConvert.GetType();
pdfType.InvokeMember("FileToPDF",System.Reflection.BindingFlags.InvokeMethod,null,pdf,new object[]{o1,o2,o3});
pdf = null;
}
catch{} //讀者自己補寫錯誤處理
//為防止本方法調用多次時發生錯誤,必須停止acrodist.exe程序
foreach(Process proc in System.Diagnostics.Process.GetProcesses())
{
int begpos;
int endpos;
string sProcName = proc.ToString();
begpos = sProcName.IndexOf("(")+1;
endpos = sProcName.IndexOf(")");
sProcName=sProcName.Substring(begpos,endpos-begpos);
if(sProcName.ToLower().CompareTo("acrodist")==0)
{
try
{
proc.Kill(); //停止程序
}
catch{} //讀者自己補寫錯誤處理
break;
}
}
}
本文轉自快樂就好部落格園部落格,原文連結:http://www.cnblogs.com/happyday56/archive/2008/01/04/1026020.html,如需轉載請自行聯系原作者