一、依赖wps插件
需求:不打算用office自带的组件实现word转pdf操作
环境:安装wps2016专业版
1.新建一个控制台应用程序
2.添加引用:在COM下 Kingsoft Add-In Designer和Upgrade Kingsoft WPS 3.0 Object Library(Beta)
3.引用中出现了Word引用图标,右键—属性—嵌入互操作类型 改为False
4.创建转换工具类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Word;
namespace wpswordtopdf
{
public class Wps2Pdf : IDisposable
{
dynamic wps;
public Wps2Pdf()
{
//这里创建wps实例不知道用了什么骚操作就没有报错过 本机安装的是wps2016
var 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($@"正在转换 [{wpsFilename}]-> [{pdfFilename}]");
dynamic doc = wps.Documents.Open(wpsFilename, Visible: false);//这句大概是用wps 打开 word 不显示界面
doc.ExportAsFixedFormat(pdfFilename, WdExportFormat.wdExportFormatPDF);//doc 转pdf
doc.Close();
}
public void Dispose()
{
throw new NotImplementedException();
}
}
}
实现:
static void Main(string[] args)
{
Wps2Pdf wps2 = new Wps2Pdf();
wps2.ToPdf(@"D://1.docx");
}
二、依赖Office
1、准备工作
安装Office
在项目中创建.Net 类库,从程序集中添加或者NuGet中搜索安装Microsoft.Office.Interop.Word
/// <summary>
/// word文档转pdf
/// </summary>
/// <param name="sourcePath">word文档路径</param>
/// <param name="targetPath">生成的pdf路径</param>
/// <returns></returns>
public static void WordToPDF(string sourcePath, string targetPath)
{
Application application = new Application();
Document document = null;
try
{
application.Visible = false;
document = application.Documents.Open(sourcePath);
document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
}
catch (Exception e)
{
throw e;
}
finally
{
if (document != null)
{
document.Close();
}
}
}
三、依赖.Net Aspose
1.使用Aspose需要从NuGet中搜索安装SkiaSharp(我使用的是VS2017)
2.添加引用 using Aspose.Words;
/// <summary>
/// Doc转Pdf
/// </summary>
/// <param name="docPath">word文档路径</param>
public static void ConverDocToPdf(string docPath)
{
//打开word文档,将doc文档转为pdf文档
Aspose.Words.Document doc = new Aspose.Words.Document(docPath);
bool isOk = false;
if (doc != null)
{
doc.Save("D:\\NewPdf.pdf", SaveFormat.Pdf);
}
}