我們不產生代碼只是代碼的搬運工
我們先來看一段跑不起來的代碼 ..各種未將對象應用到實例..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace word2PdfWithWps
{
internal class Program
{
private static void Main(string[] args)
{
var word = @"D:\C#小工具\word2PdfWithWps\word2PdfWithWps\76C309855C1E240242693FD7D7C74D7E.docx";
var pdf = @"D:\C#小工具\1.pdf";
WordExportAsPdf(word, pdf);
Console.ReadKey();
}
public static bool WordToPdfWithWps(string sourcePath, string targetPath)
{
Word.ApplicationClass app = new Word.ApplicationClass();
Word.Document doc = null;
try
{
doc = app.Documents.Open(sourcePath, true, true, false, null, null, false, "", null, 100, 0, true, true, 0, true);
doc.SaveAs(targetPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
finally
{
// doc.Close();
}
return true;
}
public static string WordExportAsPdf(string fileName, string outputFileName)
{
string isSucceed = "OK";
Word.WdExportFormat fileFormat = Word.WdExportFormat.wdExportFormatPDF;
Word.Application wordApp = null;
if (wordApp == null) wordApp = new Word.Application();
Word._Document wordDoc = null;
try
{
wordDoc = wordApp.Documents.Open(fileName, false, true);
wordDoc.ExportAsFixedFormat(outputFileName, fileFormat);
}
catch (Exception ex)
{
isSucceed = ex.Message;
}
finally
{
//if (wordDoc != null)
//{
// wordDoc.Close(false);
// wordDoc = null;
//}
//if (wordApp != null)
//{
// wordApp.Quit(false);
// wordApp = null;
//}
}
return isSucceed;
}
}
}
然后 到wps 官方論壇下載了一個別人寫好的 發現只要裝了wps 就可以直接使用
地址: http://bbs.wps.cn/forum.php?mod=viewthread&tid=22434594&highlight=C%23
主要轉換代碼
using System;
using System.IO;
using Word;
namespace WpsToPdf
{
class Wps2Pdf : IDisposable
{
dynamic wps;
public Wps2Pdf()
{
//這里創建wps實例不知道用了什么騷操作就沒有報錯過 本機安裝的是wps2016
Type type = Type.GetTypeFromProgID("KWps.Application");
wps = Activator.CreateInstance(type);
}
public void ToPdf(string wpsFilename, string pdfFilename = null)
{
if (wpsFilename == null) { throw new ArgumentNullException("wpsFilename"); }
if (pdfFilename == null)
{
pdfFilename = Path.ChangeExtension(wpsFilename, "pdf");
}
Console.WriteLine(string.Format(@"正在轉換 [{0}]
-> [{1}]", wpsFilename, pdfFilename));
//到處都是dynamic 看的我一臉懵逼
dynamic doc = wps.Documents.Open(wpsFilename, Visible: false);//這句大概是用wps 打開 word 不顯示界面
doc.ExportAsFixedFormat(pdfFilename, WdExportFormat.wdExportFormatPDF);//doc 轉pdf
doc.Close();
}
public void Dispose()
{
if (wps != null) { wps.Quit(); }
}
}
}