使用C#将Word文件(.docx和.doc)转换为.pdf

6

我如何在c#中将word文件(.docx & doc)转换为.pdf,而不使用SaveAs()Save()方法?或者不上传到服务器?


9
可能是如何在C#中将.docx转换为.pdf的重复问题。 - Chawin
7个回答

6

你可以试试这个,我用过了觉得很有效:

using Microsoft.Office.Interop.Word;

var appWord = new Application();
if (appWord.Documents != null)
{
    //yourDoc is your word document
    var wordDocument = appWord.Documents.Open(yourDoc);
    string pdfDocName = "pdfDocument.pdf";
    if (wordDocument != null)
    {                                         
       wordDocument.ExportAsFixedFormat(pdfDocName,   
       WdExportFormat.wdExportFormatPDF);
       wordDocument.Close();
    }
       appWord.Quit();
}

我该如何下载这个转换后的文件? - Shahida
1
完成此步骤后,它将保存为pdfDocument.pdf,您需要在文件中找到它。 - Human
1
在我的网站上,我想添加一个选项,将.doc或.doxc文件转换为.pdf格式。现在用户如何下载此文件,因为我不想将用户的文件保存在服务器上? - Shahida
5
似乎在服务器环境下不支持这个功能。建议使用OpenXML,但貌似没有明显的方法可以将文件保存为PDF格式,这也是我遇到这个问题的原因。 - user875234
1
@user875234 不仅不受支持,而且这只是一个非常糟糕的想法 - 您需要为每个浏览器用户获取许可证,并且每个请求都将启动Word的新实例。即使您使用using块来杀死实例,繁忙的站点也可能同时启动10或20个Word实例。 - Panagiotis Kanavos

5

如果您能购买许可证,Aspose.Words 是处理此类任务的非常好的解决方案。免费版本会向输出PDF添加警告消息。

如果您正在寻找免费的解决方案,则可以使用FreeSpire.Doc。 免费版本有以下限制:

免费版仅限500个段落和25个表格。当读取或写入文件时将强制执行此限制。将 Word 文档转换为 PDF 和 XPS 文件时,您只能获取前3页的 PDF 文件。请升级到Spire.Doc商业版。

不需要使用 MS Office、Office.Interop 或 Office自动化。

通过 NuGet 安装:

Install-Package FreeSpire.Doc -Version 7.11.0

代码示例:

using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace DoctoPDF
{
    class toPDF
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\documents\TestSample.docx");

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);

            //Launch Document
            System.Diagnostics.Process.Start("toPDF.PDF");
        }
    }
}

点击此处访问NuGet包页面


1

如果您的计算机上安装了 MS Office Word,则无需进行任何额外的编译器配置,可以尝试以下方法:

using System;
using System.IO;
using System.Reflection;

namespace KUtil
{
    public class Word2PDF
    {
        static void Main(string[] args)
        {
            var word = Type.GetTypeFromProgID("word.application");
            dynamic app = Activator.CreateInstance(word);
            if (args.Length < 1)
            {
                return;
            }
            var path = args[0];
            var outPath = Path.ChangeExtension(path, "pdf");
            dynamic doc = app.Documents.Open(path);
            doc.ExportAsFixedFormat(outPath,
                    ExportFormat:17/*pdf*/);
            doc.Close(0/*DoNotSaveChanges*/);
            app.Quit();
        }
    }
}

1
试试这个。在我看来,这是最有用和简单的方法。只需跟随Spire.Doc for .NET的帮助,您就可以轻松完成这个任务,只需要三个简单的步骤。
要查看完整的技术博客文章,请点击此链接
using Spire.Doc;

namespace ToPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Load a sample Word document
            document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");

            //Save the document to PDF
            document.SaveToFile("ToPDF.pdf", FileFormat.PDF);
        }
    }
}

0

您可以使用这段代码来使用Aspose将MS Word文档转换为PDF格式

    
public class Program
    {
        public static void Main(string[] args)
        {
            var content = File.ReadAllBytes("response.doc");
            var document = new Document(new MemoryStream(content));

            ClearFormat(document);

            var options = SaveOptions.CreateSaveOptions(SaveFormat.Pdf);

            options.PrettyFormat = true;
            options.UseAntiAliasing = true;
            options.UseHighQualityRendering = true;

            document.Save("response.pdf", options);
        }

        private static void ClearFormat(Document doc)
        {
            for (var i = 0; i < doc.Sections.Count; i++)
            {
                var nodes = doc.Sections[i].GetChildNodes(NodeType.Run, true);
                if (nodes == null || nodes.Count <= 0) continue;
                foreach (var item in (from Run item in nodes
                                      where item.Font.Name.ToLower().Contains("nastaliq")
                                      select item).ToList())
                {
                    item.Font.Name = "Times New Roman";
                    item.Font.Size = item.Font.Size > 12 ? 12 : item.Font.Size;
                }
            }
        }
    }

你好,答案不能只是代码。你应该加上一些解释,说明它是如何解决问题的以及为什么这样做。 - XouDo

0
我还没有看到使用LibreOffice的例子。所需的只是便携式可执行文件,你可以在.NET Core的C#中轻松实现这一点。我在this writeup中写了一个关于如何使用LibreOffice解决这个问题的工作中的.NET Core应用程序的链接。
using System.Diagnostics;

namespace ConvertDOCXToPDF
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create LibreOfficeWriter CLI process
            var commandArgs = new List<string>
            {
                "--convert-to", //a flag that will be followed by the file type we want to convert to
                "pdf:writer_pdf_Export", // the [output file type]:[OutputFilterName] we are requesting the output to be; more details are here (https://help.libreoffice.org/latest/en-US/text/shared/guide/convertfilters.html)
                "C:\\Users\\zachary\\Downloads\\Letter.docx", // input file
                "--norestore", // disables restart and file recovery after a system crash
                "--headless", // allows using the application without user interface
                "--outdir", // a flag that will be followed by the output directory where we want our new pdf file to be created
                "C:\\Users\\zachary\\Downloads" // output directory
            };

            // The path to LibreOfficeWriterPortable.exe
            ProcessStartInfo processStartInfo = new ProcessStartInfo("C:\\Users\\zachary\\Downloads\\LibreOfficePortablePrevious\\LibreOfficeWriterPortable.exe"); 
            foreach (string arg in commandArgs)
                processStartInfo.ArgumentList.Add(arg);

            Process process = new Process
            {
                StartInfo = processStartInfo
            };

            // Only 1 instance of LibreOfficeWriter can be running at a given time
            Process[] existingProcesses = Process.GetProcessesByName("soffice");
            while (existingProcesses.Length > 0)
            {
                Thread.Sleep(1000);
                existingProcesses = Process.GetProcessesByName("soffice");
            }

            // Start the process
            process.Start();
            process.WaitForExit();

            // Check for failed exit code.
            if (process.ExitCode != 0)
                throw new Exception("Failed to convert file");
            else
            {
                int totalChecks = 10;
                int currentCheck = 1;

                string originalFileName = Path.GetFileNameWithoutExtension(commandArgs[2]);
                string newFilePath = Path.Combine(commandArgs[6], $"{originalFileName}.pdf");

                while (currentCheck <= totalChecks)
                {
                    if (File.Exists(newFilePath))
                    {
                        // File conversion was successful

                        break;
                    }

                    Thread.Sleep(500); // LibreOffice doesn't immediately create PDF output once the command is run
                }
            }
        }
    }
}

1
你没有理解这个愚蠢问题的要点,就像许多其他人一样。OP的评论是:“我想提供一个选项,将.doc或.docx文件转换为.pdf文件,现在用户如何下载这个文件呢?因为我不想在服务器上保存用户文件。”换句话说,他们想要一个免费的无需磁盘服务。 - undefined

0

根据wangkaibule的回答,可以使用标题书签进行PDF转换。它也适用于.NET 7(类似于链接的帖子)。

public static void Convert(string inputFileName, string outputFileName)
{
  // Microsoft.Office.Interop.Word.WdSaveFormat enum
  const int wdFormatPDF = 17;
  // Microsoft.Office.Interop.Word.WdExportCreateBookmarks enum
  const int wdExportCreateHeadingBookmarks = 1;
  // Microsoft.Office.Interop.Word.WdSaveOptions enum
  const int wdDoNotSaveChanges = 0;

  var word = Type.GetTypeFromProgID("word.application");
  if (word == null)
  {
    throw new ArgumentException("Microsoft Word is not installed on the system.");
  }

  dynamic app = Activator.CreateInstance(word);
  try
  {
    dynamic doc = app.Documents.Open(inputFileName);
    doc.ExportAsFixedFormat(outputFileName, ExportFormat: wdFormatPDF, CreateBookmarks: wdExportCreateHeadingBookmarks);
    doc.Close(wdDoNotSaveChanges);
  }
  finally
  {
    app.Quit();
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接