要将 Word 文档转换为 PDF,可以使用 OpenXml 库和 PdfSharp 库。以下是基本的代码示例:

  1. 安装 OpenXml 和 PdfSharp NuGet 包。

  2. 添加以下引用:

using DocumentFormat.OpenXml.Packaging;
using PdfSharp.Pdf;
using PdfSharp.WordProcessing;
  1. 创建一个 Word 文档并打开它:
string wordDocPath = @"C:\path\to\your\word\doc.docx";
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(wordDocPath, true))
{
    // 编写转换代码
}
  1. 创建一个 PDF 文档并打开它:
string pdfDocPath = @"C:\path\to\your\pdf\doc.pdf";
PdfDocument pdfDoc = new PdfDocument();
PdfPage pdfPage = pdfDoc.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
XTextFormatter tf = new XTextFormatter(gfx);
  1. 使用 OpenXml 库中的 DocumentFormat.OpenXml.Wordprocessing.Document 类将 Word 文档转换为 PDF 格式:
string wordDocPath = @"C:\path\to\your\word\doc.docx";
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(wordDocPath, true))
{
    // 获取 Word 文档的主体部分
    Body body = wordDoc.MainDocumentPart.Document.Body;

    // 在 PDF 页面上写入 Word 文档内容
    tf.DrawString(body.InnerText);
}
  1. 保存 PDF 文档:
pdfDoc.Save(pdfDocPath);
``
net core 使用 OpenXml 将 word 转 pdf

原文地址: https://www.cveoy.top/t/topic/fFP2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录