使用 VB net 通过自动化 word 打印 pdf 而不显示对话框

Printing pdf through automating word with VB net without showing dialog

我终于遇到了一个问题,我在这里或网络上的任何其他地方都找不到答案:

我的程序从仪器上抓取一些测量值(我不能直接控制它,所以我必须等到用户完成测量并解析报告),计算出一些导出值并将这些值放回pdf报告,由仪器控制软件自动生成。

一切正常,直到我到达开始打印输出的那一行。它总是打开 word 打印对话框,而不是默默地覆盖我的文件。我实际上不明白我在调用 PrintOut 时做错了什么。

示例代码如下:

Imports Microsoft.Office.Interop
Module Example
Private Sub PrintReport()
    Dim intAnswer As Integer
    Dim strReportFileName As String = ""
    Dim appWord As New Word.Application
    Dim wdDoc As Word.Document
    dim strPPF as string = "0.5" 'For testing, normally a parameter
    dim strFolder as string = "C:\UVVis-Data" 'For testing, normally a parameter

'Find and open the PDF file of the report:
    strReportFileName = (From fi As IO.FileInfo In (New IO.DirectoryInfo(strFolder.GetFiles("*.pdf")) Order By fi.LastWriteTime Descending Select fi)(0).FullName 'It will be always the newest file in that folder
    appWord.Visible = False 'hide word from the user
    wdDoc = appWord.Documents.Open(strReportFileName) 'open the PDF report
'Replace the placeholders which were defined in the report template earlier:
    With appWord.Selection.Find
        .Text = "#PPF#"
        .Replacement.ClearFormatting()
        .Replacement.Text = strPPF
        .Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
    End With

'Print out the modified report:
    'wdDoc.PrintOut(False, False,, strReportFileName,,,,,,, True) 'this was my first approach
    wdDoc.PrintOut(Background:=False, Append:=False, OutputFileName:=strReportFileName, PrintToFile:=True) 'this also doesn't work as intended

'Close the file and restore word to it's normal state:
    wdDoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges)
    appWord.Visible = True 
    appWord.Quit()
End Sub
end Module

使用 Document.ExportAsFixedFormat 方法将文档另存为 PDF 或 XPS 格式。

Public Sub ExportAsFixedFormat_Example()  
 wdDoc.ExportAsFixedFormat pbFixedFormatTypePDF, "pathandfilename.pdf"  
End Sub

感谢您的意见。 我在代码中发现了第二个问题:在word中打开后无法覆盖原始文档。

我解决这个问题的方法是先将 pdf 移动到一个临时文件夹,然后在 word 中打开该临时文件,然后在 word 关闭后将其删除。