我们不产生代码只是代码的搬运工
我们先来看一段跑不起来的代码 ..各种未将对象应用到实例..
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(); }
}
}
}