【问题标题】:Convert Word to PDF in background process either via c# or IronPython通过 c# 或 IronPython 在后台进程中将 Word 转换为 PDF
【发布时间】:2016-11-29 12:34:42
【问题描述】:

我在网上找到了很多关于将 word (.docx) 文件转换为 .pdf 文件的示例。

当我从 UI 线程运行时,它工作正常。 但是当我在后台进程中执行它时。然后它失败了。 有没有办法通过后台进程执行将Word转换为PDF?

以下是在 UI 线程上工作的 IronPython 和 c# 代码。

IronPython:

import sys
import clr
import System
from System.Text import StringBuilder
from System.IO import DirectoryInfo, File, FileInfo, Path, StreamWriter

clr.AddReference("Microsoft.Office.Interop.Word")
import Microsoft.Office.Interop.Word as Word

def ConvertWordToPDF(wordDocFullPath):
    """
    <Script>
    <Author>SNI</Author>
    <Description>Converts Word document to PDF.</Description>
    <Parameters>
    <Parameter name="wordDocFullPath" type="string">Word document full path.</Parameter>
    </Parameters>
    <ReturnValue type="string">PDF full path</ReturnValue>
    </Script>
    """   
    wordDocInfo = FileInfo(wordDocFullPath)
    pdfFullPath = Path.Combine(wordDocInfo.DirectoryName, wordDocInfo.Name.TrimEnd(wordDocInfo.Extension.ToCharArray()) + '.pdf')

    word_application = Word.ApplicationClass()
    word_application.visible = False

    wordDocument = word_application.Documents.Open(wordDocFullPath);
    if wordDocument:
        wordDocument.ExportAsFixedFormat(pdfFullPath, Word.WdExportFormat.wdExportFormatPDF);
        wordDocument.Close()
        word_application.Quit()
        word_application = None
    else:
        print 'failed to initialize word document'

    print pdfFullPath
    return pdfFullPath`

c#代码:

public string Convert(string wordDocPath)
{
    string pdfPath = string.Empty;

    try
    {
        Microsoft.Office.Interop.Word.Application word = null;
        Document doc = null;

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

        try
        {
            word = new Microsoft.Office.Interop.Word.Application();

            Thread.Sleep(5000);

            word.Visible = false;
            word.ScreenUpdating = false;
            doc = word.Documents.Open(wordDocPath);
            pdfPath = wordDocPath.Replace(".docx", ".pdf");

            doc.ExportAsFixedFormat(
                        pdfPath,
                        Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF,
                        OptimizeFor: Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen,
                        BitmapMissingFonts: true, DocStructureTags: false);

            ((Microsoft.Office.Interop.Word._Document)doc).Close();
            ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
        }
        catch
        {
            if (doc != null)
            {
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
            }

            if (word != null)
            {
                ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
            }
            throw;
        }
    }
    catch (Exception ex)
    {
        var st = new StackTrace(ex, true);
        // Get the top stack frame
        var frame = st.GetFrame(0);
        // Get the line number from the stack frame
        var line = frame.GetFileLineNumber();

        throw new Exception("Line Number: " + line.ToString() + "  " + ex.ToString());
    }
    return pdfPath;
}

【问题讨论】:

  • 那么 c# 代码中的失败是什么?错误是否与“无法从其他线程访问对象然后创建它”有关?
  • 从 c# 它抛出 Object reference not set to an instance of the object 错误。进一步,当使用 python 进行测试时,我能够在它中断的行上归零,它无法在下面的行 doc = word.Documents.Open(wordDocPath); 处初始化文档对象;由于在没有 UI 线程的后台进程上运行。

标签: c# ms-word pdf-generation ironpython


【解决方案1】:

从我的同事安德斯那里知道了以下答案。

秒回答这里Open and modify Word Document 说微软不支持这种无人值守的自动化。 它还建议使用http://freeword.codeplex.com/​​

我刚刚验证了此脚本是否有效 - 也来自作业/后台进程:

虽然这不是一个免费软件,但它可以在后台进程中运行。 它也可以很容易地移植到 c#,因为它是一个 .net dll。

导入 clr

clr.AddReferenceToFileAndPath(r"C:\Program Files (x86)\e-iceblue\Spire.Doc-FE\Bin\NET4.0\Spire.Doc.dll")

从 Spire.Doc 导入 *

从 Spire.Doc.Documents 导入 *

从 System.IO 导入 DirectoryInfo、File、FileInfo、Path

def ConvertWordToPDFUsingSPIRE(wordDocFullPath):

"""

<Script>

<Author>SNI</Author>

<Description>Converts Word document to PDF.</Description>

<Parameters>

<Parameter name="wordDocFullPath" type="string">Word document full path.</Parameter>

</Parameters>

<ReturnValue type="string">PDF full path</ReturnValue>

</Script>

"""

wordDocInfo = FileInfo(wordDocFullPath)

pdfFullPath = Path.Combine(wordDocInfo.DirectoryName, wordDocInfo.Name.TrimEnd(wordDocInfo.Extension.ToCharArray()) + '.pdf')




document = Document();

document.LoadFromFile(wordDocFullPath);




# Convert Word to PDF



document.SaveToFile(pdfFullPath, FileFormat.PDF);

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 2013-09-25
    • 2013-03-27
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多