.net用PDFsharp 把word文件转为pdf的代码
时间: 2024-03-21 17:38:48 浏览: 19
以下是使用PDFsharp将Word文件转换为PDF的代码示例:
```csharp
using System;
using System.Diagnostics;
using System.IO;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.WordProcessing;
namespace WordToPdfConverter
{
class Program
{
static void Main(string[] args)
{
// Word文件路径
string wordFilePath = @"C:\example\example.docx";
// PDF文件路径
string pdfFilePath = @"C:\example\example.pdf";
// 创建PDF文档
PdfDocument pdfDoc = new PdfDocument();
PdfPage pdfPage = pdfDoc.AddPage();
XGraphics pdfGraphics = XGraphics.FromPdfPage(pdfPage);
// 读取Word文档
using (var stream = new FileStream(wordFilePath, FileMode.Open))
{
// 将Word文档转换为PDF
PdfConverter.ConvertToPdf(stream, pdfDoc, pdfPage);
}
// 保存PDF文件
pdfDoc.Save(pdfFilePath);
// 打开PDF文件
Process.Start(pdfFilePath);
}
}
}
```
请注意,这里使用的是PDFsharp的`PdfConverter`类来将Word文件转换为PDF,因此需要在项目中添加对`PdfSharp.WordProcessing`命名空间的引用。此外,还需要添加对`PdfSharp`和`PdfSharp.Drawing`命名空间的引用。