Home >Backend Development >C++ >How to Programmatically Convert Word (.doc) Files to PDF Files in C# or VB.NET Using Affordable Methods?
Programmatically Converting Word (.doc) Files to PDF in C# or VB.NET: Affordable Solutions
Many free or open-source tools convert .doc to .pdf, but they often function as printer drivers lacking SDKs for programmatic use. Conversely, SDKs with this functionality frequently come with substantial licensing costs. This article explores cost-effective, programmatic solutions in C# or VB.NET.
Method 1: Leveraging Microsoft Word's "Save As" Functionality
This approach utilizes the built-in functionality of Microsoft Word, assuming the "Save As PDF" add-in is installed. It's generally more reliable and efficient than alternative methods.
Here's the C# code:
<code class="language-csharp">using Microsoft.Office.Interop.Word; using System; using System.IO; // ... other using statements ... // ... other code ... // Create a Word application object Application word = new Application(); object oMissing = System.Reflection.Missing.Value; // Placeholder for optional arguments // Specify the directory containing .doc files string docDirectory = @"\server\folder"; // Get a list of .doc files string[] wordFiles = Directory.GetFiles(docDirectory, "*.doc"); word.Visible = false; // Keep Word hidden word.ScreenUpdating = false; // Prevent screen flickering foreach (string wordFile in wordFiles) { Document doc = word.Documents.Open(wordFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); string pdfFile = wordFile.Replace(".doc", ".pdf"); object fileFormat = WdSaveFormat.wdFormatPDF; doc.SaveAs(pdfFile, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null;</code>
Remember to add a reference to Microsoft.Office.Interop.Word
in your project. This method requires Microsoft Word to be installed on the system where the code runs.
Important Considerations:
try-catch
blocks to handle potential exceptions (e.g., file not found, Word application errors).This improved approach offers a practical and relatively inexpensive solution for programmatic .doc to .pdf conversion using readily available tools. Remember to adapt the code to your specific needs and environment.
The above is the detailed content of How to Programmatically Convert Word (.doc) Files to PDF Files in C# or VB.NET Using Affordable Methods?. For more information, please follow other related articles on the PHP Chinese website!