Home >Backend Development >C++ >How Can I Programmatically Convert Word Documents to PDFs Using C# or VB.NET?

How Can I Programmatically Convert Word Documents to PDFs Using C# or VB.NET?

Barbara Streisand
Barbara StreisandOriginal
2025-01-26 13:46:09399browse

How Can I Programmatically Convert Word Documents to PDFs Using C# or VB.NET?

C# or VB.NET programming to convert Word documents to PDF

Programmatically converting Word files to PDF format can be challenging, especially when looking for open source or cheap solutions. This guide will walk you through the steps to perform this conversion using C# or VB.NET.

Method 1: Iterative Image Conversion

This method involves converting each page of the Word document into an image and then saving it in PNG format.

<code class="language-csharp">int j = 0;
foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages)
{
    var bits = p.EnhMetaFileBits;
    var target = path1 + j.ToString() + "_image.doc";
    try
    {
        using (var ms = new MemoryStream((byte[])(bits)))
        {
            var image = System.Drawing.Image.FromStream(ms);
            var pngTarget = Path.ChangeExtension(target, "png");
            image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png);
        }
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    j++;
}</code>

Method 2: Use Microsoft Word’s “Save As” function

If you have access to Microsoft Word with the "Save as PDF" add-in, you can trigger this process programmatically.

<code class="language-csharp">// 创建新的Microsoft Word应用程序对象
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

// C#没有可选参数,因此我们需要一个虚拟值
object oMissing = System.Reflection.Missing.Value;

// 获取指定目录中Word文件的列表
DirectoryInfo dirInfo = new DirectoryInfo(@"\server\folder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

foreach (FileInfo wordFile in wordFiles)
{
    // 作为Object强制转换为word Open方法
    Object filename = (Object)wordFile.FullName;

    // ...

    object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
    object fileFormat = WdSaveFormat.wdFormatPDF;

    // 将文档保存为PDF格式
    doc.SaveAs(ref outputFileName,
        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);

    // ...
}</code>

The above is the detailed content of How Can I Programmatically Convert Word Documents to PDFs Using C# or VB.NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn