简体   繁体   中英

Word Interop SaveAs2 as PDF

I'm trying to save files as a PDF. My original code works to save as a word document..

Imports Word = Microsoft.Office.Interop.Word
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim objDoc As Word.Document = objWordApp.Documents.Open(appPath & "\PackListTemplate.dotm", [ReadOnly]:=True)
        objDoc = objWordApp.ActiveDocument
        With objDoc

...

    .SaveAs2(FileName:=savepath & soNumber & "_" & localDateTimeFileName & ".doc", AddToRecentFiles:=True, ReadOnlyRecommended:=True)

This is what I am trying to change my code to...

.SaveAs2(savepath & "Packing Lists - " & soNumber & ".pdf", Word.WdSaveFormat.wdFormatPDF, AddToRecentFiles:=True, ReadOnlyRecommended:=True)

The problem is that the word application save as dialog box pops up. That's not ideal as this is supposed to be automated. When I use FileName:= everything works as I expect. But when I use that bit in the PDF save, for some reason it doesn't like my Word.WdSaveFormat.wdFormatPDF . It underlines the W in Word .

What am I missing here?Any help is appreciated!

Interop uses COM libraries registered at the time of installation of MS Office. This works as long as the machine, where you are trying to manipulate documents programmatically has MS Office installed. A better approach is to use a toolkit which can merge template document and data even without MS Office installed (eg on a server). You need to prepare a template Word document, format it and place placeholders in it where you want the data to appear in the final document. You then prepare the data in .NET application and call document generation, based on a template document and your data. Resulting document can be saved as docx, pdf or xps file or streamed in any of those formats to the client. You can see some examples here if you want to learn more. Eventually it takes only two lines of code to get the final document:

// Instancing report engine, by assigning the data source
DocumentGenerator dg = new DocumentGenerator(DataAccess.GetOrderById(7)); 
// Generating report by specifying the report template and the resulting report (as file paths) 
dg.GenerateDocument("example.docx", "example_output.docx");

When closing the document use:

.Close(Word.WdSaveOptions.wdDoNotSaveChanges);

It worked form me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM