使用C#将.doc转换为.docx

我使用PDFFocus.net dll将PDF文件转换为word文件。 但对于我的系统,我想要.docx文件。 我尝试了不同的方法。 有一些图书馆可用。 但那些并不是免费的。 这是我的pdf to doc转换代码。

Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Using System.Threading.Tasks; Using iTextSharp.text; Using iTextSharp.text.pdf; namespace ConsoleApplication { class Program { static void main(String[] args) { SautinSoft.PdfFocus f=new SautinSoft.PdfFocus(); f.OpenPdf(@"E:\input.pdf"); t.ToWord(@"E:\input.doc"); } } } 

这项工作成功了。 然后我尝试使用下面的代码将.doc转换为.docx。 但它给了我错误。

 //Open a Document. Document doc=new Document("input.doc"); //Save Document. doc.save("output.docx"); 

任何人都可以帮助我。

是的,像Erop说。 您可以使用Microsoft Word 14.0 Object Library 。 然后,从doc转换为docx非常容易。 例如,使用这样的函数:

  public void ConvertDocToDocx(string path) { Application word = new Application(); if (path.ToLower().EndsWith(".doc")) { var sourceFile = new FileInfo(path); var document = word.Documents.Open(sourceFile.FullName); string newFileName = sourceFile.FullName.Replace(".doc", ".docx"); document.SaveAs2(newFileName,WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: WdCompatibilityMode.wdWord2010); word.ActiveDocument.Close(); word.Quit(); File.Delete(path); } } 

确保添加CompatibilityMode: WdCompatibilityMode.wdWord2010否则文件将保持兼容模式。 并确保在要运行该应用程序的计算机上安装了Microsoft Office。

另一件事,我不知道PDFFocus.net但你尝试过直接从pdf转换到docx。 像这样:

  static void main(String[] args) { SautinSoft.PdfFocus f=new SautinSoft.PdfFocus(); f.OpenPdf(@"E:\input.pdf"); t.ToWord(@"E:\input.docx"); } 

我认为这是有效的,但这只是一个假设。

尝试使用Microsoft.Office.Interop.Word程序集。

可以在此处找到MSDN文章

在项目中包含引用,并通过上面显示的链接中的示例在代码模块中启用它们

 using System.Collections.Generic; using Word = Microsoft.Office.Interop.Word;