使用PDFSharpCore和OpenXML将word文档转为PDF
时间: 2024-05-13 12:15:59 浏览: 9
可以使用以下步骤将Word文档转换为PDF:
1. 首先,使用OpenXML将Word文档加载到内存中。您可以使用以下代码:
```csharp
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("document.docx", false))
{
// Access the main document part
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
// Get the document settings part
DocumentSettingsPart settingsPart = mainPart.DocumentSettingsPart;
if (settingsPart != null)
{
// Disable proofing errors
settingsPart.Settings.Append(new ProofState() { Spelling = new DocumentFormat.OpenXml.OnOffValue(false), Grammar = new DocumentFormat.OpenXml.OnOffValue(false) });
settingsPart.Settings.Save();
}
// Convert the document to a PDF stream
using (MemoryStream pdfStream = new MemoryStream())
{
PdfConverter.Convert(wordDoc, pdfStream);
// Save the PDF stream to a file
File.WriteAllBytes("document.pdf", pdfStream.ToArray());
}
}
```
2. 然后,使用PDFSharpCore将Word文档转换为PDF。您可以使用以下代码:
```csharp
using (var stream = new MemoryStream())
{
// Load the Word document into a PDFsharp document
var document = PdfSharpCore.Pdf.IO.PdfReader.Open(stream, PdfSharpCore.Pdf.IO.PdfDocumentOpenMode.Import);
// Save the PDF document to a file
document.Save("document.pdf");
}
```
请注意,您需要将PDFSharpCore添加到项目中,并在代码中引用它。