C Converts Word to PDF Method Summary of Based on Office and WPS

  • 2021-12-13 09:02:06
  • OfStack

Sometimes, we need to preview word documents online. Of course, we can extract the text and tables from Word with NPOI and display them on the web page, but this will lose the original format and pictures from Word. A better way is to convert word into pdf, and then let customers preview it. Let's look at two solutions based on Office and WPS.

1. Solution based on Office

As the title says, Office-based requires Office to be installed on the server. We use the C # code to call the COM interface to convert Word into PDF. Let's take a look at the concrete implementation under 1. First refer to Microsoft. Office. Interop. Word. dll, and then write the following code:


public bool WordToPDF(string sourcePath, string targetPath)
    {
      bool result = false;
      Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
      Document document = null;
      try
      {
       application.Visible = false;
       document = application.Documents.Open(sourcePath);
       document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
       result = true;
      }
      catch (Exception e)
      {
       Console.WriteLine(e.Message);
       result = false;
      }
      finally
      {
       document.Close();
      }
      return result;
    }

2. Solution based on WPS

The biggest advantage of WPS is of course free and small in size. To realize the conversion from Word to PDF, of course, this requires that WPS must be installed on the server, and we still call the COM interface, and then write the following code:


public bool WordToPdfWithWPS(string sourcePath, string targetPath)
    {
      WPS.ApplicationClass app = new WPS.ApplicationClass();
      WPS.Document doc = null;
      try
      {
       doc = app.Documents.Open(sourcePath, true, true, false, null, null, false, "", null, 100, 0, true, true, 0, true);
       doc.ExportPdf(targetPath, "", "");
      }
      catch (Exception ex)
      {
       Console.WriteLine(ex.Message);
       return false;
      }
      finally
      {
       doc.Close();
      }
      return true;
    }

3. Enterprise Solutions

For large enterprises, there are often multiple servers, so it is impossible to install office or WPS on each server, or the company doesn't want to install these useless software on the server at all. What should I do at this time? After all, installing these software on the server is a waste of resources.

Of course, the function still needs to be realized, so how to solve it? In fact, we can install ofiice or WPS software on one server, and then deploy WCF service or remoting and other WebService, which can be called by other servers to realize the conversion from Word to PDF.


Related articles: