Home>Article>Backend Development> Summary of methods on how to convert Word to PDF in C#
This article mainly summarizes theC# method of converting Wordinto PDF, two solutions based on Office and WPS, which have certain reference value. Interested readers Friends, please refer to
Sometimes, we need to preview word documents online. Of course, we can use NPOI to extract text andtablesfrom Word, and then display them on the web page, but this will The original formatting andpicturesin Word are lost. A better way is to convert word to pdf and then let customers preview it. Let's take a look at two solutions based on Office and WPS.
1. Office-based solution
As the title says, Office-based requiresinstallationof Office on the server . We call the COMinterfacethrough C# code to convert Word into PDF. Let’s take a look at the specific implementation. FirstreferenceMicrosoft.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. Based on WPS solution
#The biggest advantage of WPS is of course that it is free and it is small in size. To convert Word to PDF, of course, this requires WPS to be installed on the server. 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-level solution
For large enterprises, there are often multiple servers, and it is impossible to install Office or WPS on each server, or the company simply does not want to install these useless software on the server. . What should we 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 implemented, so how to solve it? In fact, we can install ofiice or WPS software on a server, and then deploy WebService such as WCF service or remoting. Other servers can call this service to convert Word to PDF.
The above is the detailed content of Summary of methods on how to convert Word to PDF in C#. For more information, please follow other related articles on the PHP Chinese website!