Monday, August 08, 2005

How to Set Measurement Unit of MS Word Print Dialog Programatically

In a recent project that I'm working for at my current work place, We were using Office Interop for printing some word documents from HTML files and we wanted to set the measurement unit of the page to print (Inches, Millimeters, Centimiters etc...) . We were struggling over this issue for a while; Since the Word API was not so easy to be familiar with. At last I found the way to set it. I give below a sample of the code we came up with. I hope this will someday could be used by many.
N.B: Code is in VB.Net

Public objWord As Word.Application ' Word Application Object

Private Function printHTML(ByVal document As String, ByVal nums As Int32, ByVal orientation As Int32, ByVal leftMargin As Int32, ByVal topMargin As Int32, ByVal rightMargin As Int32, ByVal bottomMargin As Int32, ByVal pageSize As Int32, ByVal printdest As String) As Boolean

Const ForWriting = 2 ' Input OutPut mode
Const Create = True


Dim MyFile As String
Dim FSO As File 'Variable to deal with parameters to the Word Interop that we don't need to pass
Dim NoParam As Object
NoParam = Type.Missing

MyFile = Path & document & ".html" ' HTML File to Print

If FSO.Exists(MyFile) Then
objWord.Documents.Open(MyFile, False, True, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam)

' Setting destination printer
With objWord.Application.Dialogs.Item(Word.WdWordDialog.wdDialogFilePrintSetup)
.Printer = printdest
.DoNotSetAsSysDefault = True
.Execute()
End With


' setting up Page Orientation
If orientation = 2 Then
objWord.ActiveDocument.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape
Else
objWord.ActiveDocument.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait
End If


' Setting pages Measurement Unit to Millimeters
With objWord
.Application.Options.MeasurementUnit = Word.WdMeasurementUnits.wdMillimeters
End With


'Setting the Page Size
objWord.ActiveDocument.PageSetup.PaperSize = pageSize

' Setting the Margins
objWord.ActiveDocument.PageSetup.LeftMargin = leftMargin
objWord.ActiveDocument.PageSetup.RightMargin = rightMargin
objWord.ActiveDocument.PageSetup.TopMargin = topMargin
objWord.ActiveDocument.PageSetup.BottomMargin = bottomMargin



objWord.Options.PrintBackground = False 'Do not print the background
'Call the Print method
objWord.ActiveDocument.PrintOut(False, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, CStr(nums), NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam, NoParam)


'Closing the File
objWord.ActiveDocument.Close(False)

' clean up files
If (FSO.Exists(MyFile)) Then FSO.Delete(MyFile)


End Function

0 Comments:

Post a Comment

<< Home