如何以编程方式将Word文件转换为PDF?

时间:2009-03-03 19:03:26

标签: c# vb.net pdf ms-word

我找到了几个开源/免费软件程序,允许您将.doc文件转换为.pdf文件,但它们都是应用程序/打印机驱动程序的种类,没有附加SDK。

我发现有几个程序有一个SDK,允许你将.doc文件转换成.pdf文件,但它们都是专有类型,2000美元一个许可证或附近。

有没有人知道使用C#或VB.NET来解决我的问题的任何干净,廉价(最好免费)的程序化解决方案?

谢谢!

15 个答案:

答案 0 :(得分:197)

使用foreach循环而不是for循环 - 它解决了我的问题。

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++;
}

这是对我有用的程序的修改。它使用安装了Save As PDF add-in的Word 2007。它在目录中搜索.doc文件,在Word中打开它们,然后将它们另存为PDF。请注意,您需要将Microsoft.Office.Interop.Word的引用添加到解决方案中。

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

...

// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;

// Get list of Word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

word.Visible = false;
word.ScreenUpdating = false;

foreach (FileInfo wordFile in wordFiles)
{
    // Cast as Object for word Open method
    Object filename = (Object)wordFile.FullName;

    // Use the dummy value as a placeholder for optional arguments
    Document doc = word.Documents.Open(ref filename, 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();

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

    // Save document into PDF Format
    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);

    // Close the Word document, but leave the Word application open.
    // doc has to be cast to type _Document so that it will find the
    // correct Close method.                
    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
    ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
    doc = null;
}

// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;

答案 1 :(得分:32)

总结一下vb.net用户,免费选项(必须安装办公室):

Microsoft office assembies download:

VB.NET示例:

        Dim word As Application = New Application()
        Dim doc As Document = word.Documents.Open("c:\document.docx")
        doc.Activate()
        doc.SaveAs2("c:\document.pdf", WdSaveFormat.wdFormatPDF)
        doc.Close()

答案 2 :(得分:14)

PDFCreator有一个COM组件,可以从.NET或VBScript调用(下载中包含的示例)。

但是,在我看来,打印机正是您所需要的 - 只需将其与Word's automation混合使用,您应该很高兴。

答案 3 :(得分:7)

答案 4 :(得分:7)

只是想补充说我使用的是Microsoft.Interop库,特别是我在这个帖子中没有看到的ExportAsFixedFormat函数。

using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Office.Core;Application app;

public string CreatePDF(string path, string exportDir)
{
    Application app = new Application();
    app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
    app.Visible = true;

    var objPresSet = app.Documents;
    var objPres = objPresSet.Open(path, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);

    var pdfFileName = Path.ChangeExtension(path, ".pdf");
    var pdfPath = Path.Combine(exportDir, pdfFileName);

    try
    {
        objPres.ExportAsFixedFormat(
            pdfPath,
            WdExportFormat.wdExportFormatPDF,
            false,
            WdExportOptimizeFor.wdExportOptimizeForPrint,
            WdExportRange.wdExportAllDocument
        );
    }
    catch
    {
        pdfPath = null;
    }
    finally
    {
        objPres.Close();
    }
    return pdfPath;
}

答案 5 :(得分:5)

当有人用10000个单词文件转换为PDF以转换为PDF时,我经历了Word的痛苦。现在我用C#做了它并且使用了Word互操作但是如果我试图使用PC那么它很慢并且崩溃了......非常令人沮丧。

这让我发现我可以转储interops和它们的缓慢.....对于我使用的Excel(EPPLUS)然后我发现你可以获得一个名为Spire的免费工具,允许转换为PDF ...有限制!

http://www.e-iceblue.com/Introduce/free-doc-component.html#.VtAg4PmLRhE

答案 6 :(得分:4)

我对Gembox(http://www.gemboxsoftware.com/)印象深刻,他提供有限的免费版文档管理(包括pdf转换)。他们还为电子表格做图书馆。 1开发人员许可证,如果你超过他们的限制(我想你会),但大约是580美元(http://www.gemboxsoftware.com/document/pricelist)。好吧,它不是免费的(或者在我看来相对便宜),但它比2000美元便宜很多。据我所知,从价目表中可以看出服务器部署没有版税。可能值得接近他们,看看如果你不想自己动手,他们是否会做一笔交易。

答案 7 :(得分:3)

我将此作为发布流程的一部分 - 将Word文档转换为PDF。

http://www.suodenjoki.dk/us/productions/articles/word2pdf.htmhttp://www.oooforum.org/forum/viewtopic.phtml?t=3772&highlight=pdf+form

不完全以编程方式,但可以帮助您。

答案 8 :(得分:3)

当我偶然发现服务器端局自动化的一些问题时,我们研究了here on codeproject所描述的技术。 它使用OpenOffice的可移植版本(可以通过xcopy部署)与宏结合使用。 虽然我们还没有自己做过切换,但它看起来很有意义。

答案 9 :(得分:1)

这里似乎是一些相关的信息:

Converting MS Word Documents to PDF in ASP.NET

此外,由于Office 2007具有发布到PDF功能,我想您可以使用办公自动化在Word 2007中打开* .DOC文件并另存为PDF。我不太热衷于办公自动化,因为它很慢而且容易挂起,但只是扔掉那里......

答案 10 :(得分:1)

我使用了ABCpdf,这是一个程序化的选项,并不是太贵,300美元/许可证。它适用于OpenOffice,或者如果OpenOffice不可用则退回到Word。使用OpenOffice COM权限设置有点棘手,但绝对值得将应用程序的这一部分外包。

答案 11 :(得分:1)

单词的Microsoft PDF加载项似乎是目前最好的解决方案,但您应该考虑到它没有正确地将所有word文档转换为pdf,在某些情况下,您会看到单词和输出之间的巨大差异PDF格式。不幸的是我找不到任何能正确转换所有word文档的api。 我发现确保转换100%正确的唯一解决方案是通过打印机驱动程序转换文档。缺点是文档排队并逐个转换,但您可以确定生成的pdf与word文档布局完全相同。 我个人更喜欢使用UDC(通用文档转换器)并在服务器上安装福昕阅读器(免费版),然后通过启动“处理”并将其动词属性设置为“打印”来打印文档。您还可以使用FileSystemWatcher在转换完成后设置信号。

答案 12 :(得分:1)

只要安装了Word 2010或更高版本,就可以使用DocTo来提供命令行应用程序来执行此操作。

答案 13 :(得分:0)

对于无法在其服务器上安装Office或在某些云环境中运行的情况下的程序员,Api2Pdf是其他答案的一种廉价替代方案,它支持将Word文件转换为PDF以及任何其他MS Office文件。这是一个Web API,在后台使用LibreOffice。

答案 14 :(得分:0)

使用Microsoft.Office.Interop.Word轻松转换WORD和PDF格式的代码和解决方案

using Word = Microsoft.Office.Interop.Word;

private void convertDOCtoPDF()
{

  object misValue = System.Reflection.Missing.Value;
  String  PATH_APP_PDF = @"c:\..\MY_WORD_DOCUMENT.pdf"

  var WORD = new Word.Application();

  Word.Document doc   = WORD.Documents.Open(@"c:\..\MY_WORD_DOCUMENT.docx");
  doc.Activate();

  doc.SaveAs2(@PATH_APP_PDF, Word.WdSaveFormat.wdFormatPDF, misValue, misValue, misValue, 
  misValue, misValue, misValue, misValue, misValue, misValue, misValue);

  doc.Close();
  WORD.Quit();


  releaseObject(doc);
  releaseObject(WORD);

}

添加此过程以释放内存:

private void releaseObject(object obj)
{
  try
  {
      System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
      obj = null;
  }
  catch (Exception ex)
  {
      //TODO
  }
  finally
  {
     GC.Collect();
  }
}
相关问题