OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

OO Basic: advanced printing macro

 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets
View previous topic :: View next topic  
Author Message
zenlord
Power User
Power User


Joined: 24 Nov 2006
Posts: 53

PostPosted: Mon Sep 05, 2011 8:30 am    Post subject: OO Basic: advanced printing macro Reply with quote

Hi,

During the past years I have elaborated more and more on my printing macro, and that was only possible through some excellent answers I received in these forums. At this point I can say I have a perfectly working set of macro's and I would like to share them with the community.

Usecase: You use printed stationary and you have more than 1 printertray (2 or 3). There are different ways of sending your letter to the recipient: regular mail, recommended mail, fax or email. You want to be able to print a 'stamp with date and time' to the version of the document that you keep in your own file. You want to be able to generate a PDF of the document with or without a background picture.

Solution: Make a document with an image for a background that resembles the stationary. Make a new toolbar with at least 4 buttons and bind each button to one of the macro's listed below. The macro will do whatever necessary and then close the document. The macro's are clean and commented, so they should be self-explanatory. There is only 1 place to set your printername (mine is 'MFC8880DN') and you can set the options to which printertray to print inside the functions print_plain(), print_stat_first() and print_stat_rest(). You might need to set the dimensions and placement of the stamp that can be inserted, according to your template.

Known problems:
1. I set the printertray hardcoded for 2 pagestyles - if someone knows how to accomplish this dynamically, I'd be interested to hear that Smile - around the three lines that are commented out in 'printPage()'
2. I would like to automate the fax-process so that I don't need to print, get up and fax manually, but that could be inserted rather easily once the fax-procedure is known.

Macro:
Code:

Removed because newer version down below


Last edited by zenlord on Mon Oct 15, 2012 2:23 am; edited 1 time in total
Back to top
View user's profile Send private message
zenlord
Power User
Power User


Joined: 24 Nov 2006
Posts: 53

PostPosted: Mon Oct 15, 2012 2:18 am    Post subject: Reply with quote

Version 2.0.1: now with error handling, explicit data types and dynamic fetching of pagestyles.

Still looking for a way to send the document to my faxmachine!

Code:
REM ** VERSIONING **
'Version 2.0.1 (12 okt 2012)
' Thanks To Bernard Marcelly, I have added explicit declarations everywhere
'  and simplified the loops
'Version 2.0 (11 okt 2012)
' Added simple ErrorHandler and rewrote comments

REM  *****  BASIC  *****
Option Explicit

Sub Main
   REM Set backgroundImage-option in DocumentSettings to True
   DIM oDoc AS Object, oSettings AS Object
   oSettings = oDoc.createInstance("com.sun.star.text.DocumentSettings")
   oSettings.PrintPageBackground = TRUE
End Sub


REM ** GENERAL HELPERS **

' ------------------------------
' This macro closes the current document
'
' Written by Andrew Pitonyak (2010)
' Adapted by Vincent Van Houtte (2011)
' ------------------------------
Sub closeDocument(oDoc AS Object)
   REM Check if the document exists
   If IsNull(oDoc) Then
      Exit Sub
   End If

   REM Store the document if it was modified
   If (oDoc.isModified) Then
     If (oDoc.hasLocation AND (Not oDoc.isReadOnly)) Then
       oDoc.store()
     Else
       oDoc.setModified(False)
     End If
   End If

   REM Close the document
   oDoc.close(true)
End Sub

' ------------------------------
' Written by Andrew Pitonyak the Great
' Used in the Date-time-functions
' ------------------------------
Function FindCreateNumberFormatStyle ( sFormat As String, Optional doc, Optional locale)
   Dim oDoc As Object
   Dim aLocale As New com.sun.star.lang.Locale
   Dim oFormats As Object
   Dim formatNum As Integer
   oDoc = IIf(IsMissing(doc), ThisComponent, doc)
   oFormats = oDoc.getNumberFormats()
   'If you choose to query on types, you need to use the type
   'com.sun.star.util.NumberFormat.DATE
   'I could set the locale from values stored at
   'http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
   'http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
   'I use a NULL locale and let it use whatever it likes.
   'First, see if the number format exists
   If ( Not IsMissing(locale)) Then
   aLocale = locale
   End If
   formatNum = oFormats.queryKey (sFormat, aLocale, TRUE)
   'MsgBox "Current Format number is" & formatNum
   'If the number format does not exist then add it
   If (formatNum = -1) Then
   formatNum = oFormats.addNew(sFormat, aLocale)
   If (formatNum = -1) Then formatNum = 0
   '   MsgBox "new Format number is " & formatNum
   End If
   FindCreateNumberFormatStyle = formatNum
End Function


REM ** HELPER MACRO'S TO INSERT / REMOVE A DATESTAMP**

' ------------------------------
' This macro inserts a 'DATE/TIME'-stamp with sActionText
' like 'Printed' or 'Sent'
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub InsertDTstampFirstPage(sActionText AS String)
   DIM oCursor AS Object, oText AS Object, oDoc AS Object
   oDoc = ThisComponent
   oText = oDoc.getText()
   oCursor = oText.createTextCursor()
   oCursor.goToStart(FALSE)

   REM Create the date and time objects
   DIM oDate AS Object, oTime AS Object
   oDate = oDoc.createInstance("com.sun.star.text.TextField.DateTime")
   oDate.IsFixed = TRUE
   oDate.IsDate = TRUE
   oDate.NumberFormat = FindCreateNumberFormatStyle("D MMMM JJJJ", oDoc)
   
   oTime = oDoc.createInstance("com.sun.star.text.TextField.DateTime")
   oTime.IsFixed = True
   oTime.IsDate = False
   oTime.NumberFormat = FindCreateNumberFormatStyle("UU:MM", oDoc)

   REM Create the frame
   DIM oFrameDT AS Object
   oFrameDT = oDoc.createInstance("com.sun.star.text.TextFrame")
   With oFrameDT
   .setName("FrameDT")
   .AnchorType = com.sun.star.text.TextContentAnchorType.AT_PAGE
   .HoriOrient = com.sun.star.text.HoriOrientation.NONE
   .VertOrient = com.sun.star.text.VertOrientation.NONE
   .HoriOrientPosition = -4200
   .VertOrientPosition = -4000
   .width = 4000
   .height = 1500
   .BorderDistance = 100
   End With

   REM Insert the frame into the text document
   oText.insertTextContent( oCursor, oFrameDT, True )

   REM Write the text inside the frame
   DIM oCursor2 AS Object
   oCursor2 = oFrameDT.createTextCursor()
   With oCursor2
   .charHeight = 13
   .charWeight = com.sun.star.awt.FontWeight.BOLD
   .paraAdjust = com.sun.star.style.ParagraphAdjust.CENTER
   End With

   oFrameDT.insertString( oCursor2, sActionText, False )

   With oCursor2
   .charHeight = 9
   .charWeight = com.sun.star.awt.FontWeight.NORMAL
   .paraAdjust = com.sun.star.style.ParagraphAdjust.CENTER
   End With

   oFrameDT.insertControlCharacter( oCursor2, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   oFrameDT.insertTextContent( oCursor2, oDate, False )

   oFrameDT.insertControlCharacter( oCursor2, com.sun.star.text.ControlCharacter.LINE_BREAK, False )
   oFrameDT.insertTextContent( oCursor2, oTime, False )
End Sub


' ------------------------------
' This macro inserts a 'DATE/TIME'-stamp with sActionText
' like 'Printed', 'Copy', 'Books' or 'Sent'
'
' Written by Vincent Van Houtte (2012)
' ------------------------------
Sub InsertDTstampLastPage(sActionText AS String)
   DIM oCursor AS Object, oText AS Object, oDoc AS Object
   oDoc = ThisComponent
   oText = oDoc.getText()
   oCursor = oText.createTextCursor()
   oCursor.goToEnd(FALSE)

   REM Create the date and time objects
   DIM oDate AS Object, oTime AS Object
   oDate = oDoc.createInstance("com.sun.star.text.TextField.DateTime")
   oDate.IsFixed = TRUE
   oDate.IsDate = TRUE
   oDate.NumberFormat = FindCreateNumberFormatStyle("D MMMM JJJJ", oDoc)
   
   oTime = oDoc.createInstance("com.sun.star.text.TextField.DateTime")
   oTime.IsFixed = True
   oTime.IsDate = False
   oTime.NumberFormat = FindCreateNumberFormatStyle("UU:MM", oDoc)

   REM Create the frame
   DIM oFrameDT AS Object
   oFrameDT = oDoc.createInstance("com.sun.star.text.TextFrame")
   With oFrameDT
   .setName("FrameDT")
   .AnchorType = com.sun.star.text.TextContentAnchorType.AT_PAGE
   .HoriOrient = com.sun.star.text.HoriOrientation.NONE
   .VertOrient = com.sun.star.text.VertOrientation.NONE
   .HoriOrientPosition = -4200
   .VertOrientPosition = -4000
   .width = 4000
   .height = 1500
   .BorderDistance = 100
   End With

   REM Insert the frame into the text document
   oText.insertTextContent( oCursor, oFrameDT, True )

   REM Write the text inside the frame
   DIM oCursor2 AS Object
   oCursor2 = oFrameDT.createTextCursor()
   With oCursor2
   .charHeight = 13
   .charWeight = com.sun.star.awt.FontWeight.BOLD
   .paraAdjust = com.sun.star.style.ParagraphAdjust.CENTER
   End With

   oFrameDT.insertString( oCursor2, sActionText, False )

   With oCursor2
   .charHeight = 9
   .charWeight = com.sun.star.awt.FontWeight.NORMAL
   .paraAdjust = com.sun.star.style.ParagraphAdjust.CENTER
   End With

   oFrameDT.insertControlCharacter( oCursor2, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   oFrameDT.insertTextContent( oCursor2, oDate, False )

   oFrameDT.insertControlCharacter( oCursor2, com.sun.star.text.ControlCharacter.LINE_BREAK, False )
   oFrameDT.insertTextContent( oCursor2, oTime, False )
End Sub



' ------------------------------
' This macro removes the 'DATE/TIME'-stamp created with
' the previous macro
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub RemoveDTstamp()
   DIM oDoc AS Object, oTextFrames AS Object, oFrameDT AS Object
   oDoc = ThisComponent

   REM Look for the datetimestamp-frame and remove it
   oTextFrames = oDoc.getTextFrames
   If oTextFrames.hasByName("FrameDT") Then
      oFrameDT = oTextFrames.getByName("FrameDT")
      oFrameDT.dispose()
   EndIf
End Sub


REM ** HELPER PRINTING FUNCTIONS **

' ------------------------------
' This macro shows a dialog with a list of all installed printers on your system.
' Ideally, the dialog closes after a selection has been made
'
' Written by Vincent Van Houtte (2012)
' ------------------------------
Function ShowListPrinters
   DIM aPrinterNames(10)
   DIM d AS Object, l AS Object, list AS Object, result(10)

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   aPrinterNames = GetAllPrinterNames()

   DialogLibraries.loadLibrary("Standard")
   d = CreateUnoDialog(DialogLibraries.Standard.dlgListPrinters)
      d.setTitle("Selecteer printer")
      l = d.getControl("ListPrinters")
      l.getModel().StringItemList = aPrinterNames
      l.selectItemPos( 0, true )
   d.execute()
      list = d.getModel().getByName("ListPrinters")
      result = list.StringItemList(list.SelectedItems(0))
   d.dispose()
   ShowListPrinters = result

'ErrorHandler
Exit Function
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Function


' ------------------------------
' This macro returns an array with a list of all installed printers. It is possible
' that it doesn't work on older (pre OOo3.5) versions of OOo / LO
'
' Written by Niklas Nebel (cited by Andrew Pitonyak)
' Adapted very slightly by Vincent Van Houtte (2012)
' ------------------------------
Function GetAllPrinterNames()
   DIM oPrintServer AS Object ' The print server service.
   DIM oCore AS Object        ' Get classes and other objects by name.
   DIM oClass AS Object       ' XPrinterServer class object.
   DIM oMethod AS Object      ' getPrinterNames method from the XPrinterServer class.

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   ' Create the object that will not be directly usable until OOo 3.5.
   oPrintServer = CreateUnoService("com.sun.star.awt.PrinterServer")
   oCore = CreateUnoService("com.sun.star.reflection.CoreReflection")

   ' Get the class object for the XPrinterServer interface.
   oClass = oCore.forName("com.sun.star.awt.XPrinterServer")

   ' Get the getPrinterNames method for the XPrinterServer class.
   oMethod = oClass.getMethod("getPrinterNames")

   ' Call the getPrinterNames method on the PrinterServer object.
   GetAllPrinterNames = oMethod.invoke(oPrintServer, Array())

'ErrorHandler
Exit Function
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Function


REM ** HELPER PRINTING MACRO'S **

' ------------------------------
' This macro prints a given page without the background(-image) to the
' papertray holding the pre-printed (first-page-)stationary:
' you can set an image as a background, that you don't want to print,
' but that you want to show up when converted to PDF.
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Print_stat_first(iPageNr AS Integer, sPrinter AS String)
   DIM sTray AS String
   DIM bBg AS Boolean
   sTray = "Tray2"
   bBg = False
   printPage(sTray, bBg, iPageNr, sPrinter)
End Sub


' ------------------------------
' This macro prints a given page without the background(-image) to the
' papertray holding the pre-printed (other-page-)stationary:
' you can set an image as a background, that you don't want to print,
' but that you want to show up when converted to PDF.
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Print_stat_rest(iPageNr AS Integer, sPrinter AS String)
   DIM sTray AS String
   DIM bBg AS Boolean
   sTray = "Tray1"
   bBg = False
   printPage(sTray, bBg, iPageNr, sPrinter)
End Sub


' ------------------------------
' This macro prints a given page without the background(-image) to the
' papertray holding plain paper, for example to keep in your own file
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Print_plain(iPageNr AS Integer, sPrinter AS String)
   DIM sTray AS String
   DIM bBg AS Boolean
   sTray = "Tray1"
   bBg = False
   printPage(sTray, bBg, iPageNr, sPrinter)
End Sub


' ------------------------------
' This macro prints a given page with the background(-image) to the
' papertray holding plain paper, for example to keep in your official books
'
' Written by Vincent Van Houtte (2012)
' ------------------------------
Sub Print_plain_with_background(iPageNr AS Integer, sPrinter AS String)
   DIM sTray AS String
   DIM bBg AS Boolean
   sTray = "Tray1"
   bBg = True
   printPage(sTray, bBg, iPageNr, sPrinter)
End Sub


' ------------------------------
' This macro prints a specified page given the chosen parameters
'
' Written by Vincent Van Houtte (2010)
' ------------------------------
Sub printPage(sTray AS String, bBg AS Boolean, sPageNr AS String, sPrinter AS String)
   DIM oDoc AS Object
   oDoc = ThisComponent

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   REM Set backgroundImage-option in DocumentSettings to False
   DIM oSettings AS Object
   oSettings = oDoc.createInstance("com.sun.star.text.DocumentSettings")
   oSettings.PrintPageBackground = bBg

   REM Set the chosen printer
   DIM mPrinterOpts(2) AS NEW com.sun.star.beans.PropertyValue
   mPrinterOpts(0).Name = "Name"
   mPrinterOpts(0).Value = sPrinter
   mPrinterOpts(1).Name = "PaperFormat"
   mPrinterOpts(1).Value = com.sun.star.view.PaperFormat.A4
   mPrinterOpts(2).Name = "PaperOrientation"
   mPrinterOpts(2).Value = com.sun.star.view.PaperOrientation.PORTRAIT
   oDoc.Printer = mPrinterOpts()

   REM cast sPageNr as a integer
   DIM iPageNr AS Integer
   iPageNr = sPageNr

   REM set Papertray in Styles
   DIM oStyle AS Object, oViewCursor AS Object, sPageStyleName AS String
   oViewCursor = oDoc.CurrentController.getViewCursor()
   oViewCursor.JumpToPage(iPageNr)
   sPageStyleName = oViewCursor.PageStyleName
   oStyle = oDoc.StyleFamilies.getByName("PageStyles").getByName(sPageStyleName)
   'If the printer has but one tray, comment the next line out:
   oStyle.PrinterPaperTray = sTray

   REM Set printOptions
   DIM mPrintOpts(3) AS NEW com.sun.star.beans.PropertyValue
   mPrintOpts(0).Name = "CopyCount"
   mPrintOpts(0).Value = 1
   mPrintOpts(1).Name = "Collate"
   mPrintOpts(1).Value = True
   mPrintOpts(2).Name = "Pages"
   mPrintOpts(2).Value = sPageNr
   mPrintOpts(3).Name = "Wait"
   mPrintOpts(3).Value = True

   REM Print or Debug
'   MsgBox sPageNr + " / " + sPageStyleName
'   Xray oViewCursor
   oDoc.Print(mPrintOpts())

   REM RESET OPTIONS
   REM Set backgroundImage-option in DocumentSettings to True
   oSettings = oDoc.createInstance("com.sun.star.text.DocumentSettings")
   oSettings.PrintPageBackground = True
'ErrorHandler
Exit Sub
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Sub


REM ** PRINTING MACRO'S ASSIGNED TO BUTTONS**

' ------------------------------
' This macro prints the document once to stationary and exits
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Fax_close()
   DIM oDoc AS Object, oCursor AS Object, oText AS Object
   DIM iPageCount AS Integer, n AS Integer
   DIM sPage AS String
   DIM sPrinter AS String
   DIM sActionText AS String

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   sPrinter= ShowListPrinters()
   oDoc   = ThisComponent

   REM Count the amount of pages
   iPageCount = oDoc.getCurrentController().getPropertyValue("PageCount")

'Print stat
   REM Print the first page
   Print_stat_first(1, sPrinter)

   REM Loop over every next page and print it
   For n = 2 to iPageCount
      Print_stat_rest(n, sPrinter)
   next

'Exit
   REM Save and close the document
   closeDocument(oDoc)

'ErrorHandler
Exit Sub
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Sub


' ------------------------------
' This macro prints a copy of the document, sends the
' document to the default email app as a PDF and exits
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Mail_close()
   DIM oDoc AS Object, oCursor AS Object, oText AS Object
   DIM iPageCount AS Integer, n AS Integer
   DIM sPage AS String
   DIM sPrinter AS String
   DIM sActionText AS String

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   sPrinter= ShowListPrinters()
   oDoc   = ThisComponent

   REM Count the amount of pages
   iPageCount = oDoc.getCurrentController().getPropertyValue("PageCount")

'Print copy
   REM Insert timestamp of sending
   sActionText = "VERZONDEN"
   InsertDTstampFirstPage(sActionText)

   REM Loop over every next page and print it
   For n = 1 to iPageCount
      Print_plain(n, sPrinter)
   next

   REM Remove the copystamp-frame
   RemoveDTstamp()

'Create PDF
   REM Replace .odt with .pdf
   DIM sDocURL AS String, sPDFURL AS String
   sDocURL = oDoc.getURL()
   sPDFURL = Left$(sDocURL,Len(sDocURL)-4) + ".pdf"

   REM Save as PDF
   DIM args(0) AS NEW com.sun.star.beans.PropertyValue
   args(0).Name = "FilterName"
   args(0).Value = "writer_pdf_Export"
   oDoc.storeToURL(sPDFURL,args())

'Send to mailapp
   REM Get the values of the textfields inside the document to form the subject line
   DIM enuTF AS Object, aTextField AS Object
   DIM sDosName AS String, sDosNum AS String, sDosUref AS String, sTo AS String, sSubject AS String
   enuTF = oDoc.TextFields.createEnumeration
      Do While enuTF.hasMoreElements
      aTextField = enuTF.nextElement
         if aTextField.supportsService("com.sun.star.text.TextField.Input") then
            Select Case aTextField.getPropertyValue("Hint")
               Case "briefBetreft":
                  sDosName = aTextField.getPropertyValue("Content")
               Case "briefOnzeReferte":
                  sDosNum = aTextField.getPropertyValue("Content")
               Case "briefUwReferte":
                  sDosUref = aTextField.getPropertyValue("Content")
               Case "verzendingsadres":
                  sTo = aTextField.getPropertyValue("Content")
            End Select
         end if
      Loop
   sSubject = sDosName + " - " + sDosUref + " - " + sDosNum

   REM Send the PDF as an attachment
   DIM MailClient AS Object, MailAgent AS Object, MailMessage AS Object
   'On linux systems, use SimpleCommandMail
   MailAgent = CreateUnoService("com.sun.star.system.SimpleCommandMail")
   'On windows systems, use SimpleSystemMail
   'MailAgent = CreateUnoService("com.sun.star.system.SimpleSystemMail")
   MailClient = MailAgent.querySimpleMailClient()
      MailMessage=MailClient.createSimpleMailMessage()
      MailMessage.setRecipient(sTo)
      MailMessage.setSubject(sSubject)
      MailMessage.setAttachement(array(sPDFURL))
   MailClient.sendSimpleMailMessage(MailMessage, 0)

'Exit
   REM Save and close the document
   closeDocument(oDoc)

'ErrorHandler
Exit Sub
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Sub

' ------------------------------
' This macro prints the document once to stationary, once as a copy and exits
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Letter_close()
   DIM oDoc AS Object, oCursor AS Object, oText AS Object
   DIM iPageCount AS Integer, n AS Integer
   DIM sPage AS String
   DIM sPrinter AS String
   DIM sActionText AS String

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   sPrinter= ShowListPrinters()
   oDoc   = ThisComponent

   REM Count the amount of pages
   iPageCount = oDoc.getCurrentController().getPropertyValue("PageCount")

'Print stat
   REM Print the first page
   Print_stat_first(1, sPrinter)

   REM Loop over every next page and print it
   For n = 2 to iPageCount
      Print_stat_rest(n, sPrinter)
   next

'Print copy
   REM Insert timestamp of sending
   sActionText = "KOPIE"
   InsertDTstampFirstPage(sActionText)

   REM Loop over every next page and print it
   For n = 1 to iPageCount
      Print_plain(n, sPrinter)
   next

   REM Remove the copystamp-frame
   RemoveDTstamp()

'Exit
   REM Save and close the document
   closeDocument(oDoc)

'ErrorHandler
Exit Sub
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Sub

' ------------------------------
' This macro prints the document twice to stationary, once as a copy and exits
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Letter_recommended_close()
   DIM oDoc AS Object, oCursor AS Object, oText AS Object
   DIM iPageCount AS Integer, n AS Integer
   DIM sPage AS String
   DIM sPrinter AS String
   DIM sActionText AS String

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   sPrinter= ShowListPrinters()
   oDoc   = ThisComponent

   REM Count the amount of pages
   iPageCount = oDoc.getCurrentController().getPropertyValue("PageCount")

'Print stat
   REM Print the first page
   Print_stat_first(1, sPrinter)

   REM Loop over every next page and print it
   For n = 2 to iPageCount
      Print_stat_rest(n, sPrinter)
   next

'Print stat second
   REM Print the first page
   Print_stat_first(1, sPrinter)

   REM Loop over every next page and print it
   For n = 2 to iPageCount
      Print_stat_rest(n, sPrinter)
   next

'Print copy
   REM Insert timestamp of sending
   sActionText = "KOPIE"
   InsertDTstampFirstPage(sActionText)

   REM Loop over every next page and print it
   For n = 1 to iPageCount
      Print_plain(n, sPrinter)
   next

   REM Remove the copystamp-frame
   RemoveDTstamp()

'Exit
   REM Save and close the document
   closeDocument(oDoc)

'ErrorHandler
Exit Sub
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Sub


' ------------------------------
' This macro prints a copy of the document, and makes a
' PDF-doc with copy-stamp
'
' Written by Vincent Van Houtte (2011)
' ------------------------------
Sub Print_copy()
   DIM oDoc AS Object, oCursor AS Object, oText AS Object
   DIM iPageCount AS Integer, n AS Integer
   DIM sPage AS String
   DIM sPrinter AS String
   DIM sActionText AS String

   REM Initiate Errorhandler
   On error GoTo ErrorHandler

   sPrinter= ShowListPrinters()
   oDoc   = ThisComponent

   REM Count the amount of pages
   iPageCount = oDoc.getCurrentController().getPropertyValue("PageCount")

'Print copy
   REM Insert timestamp of sending
   sActionText = "KOPIE"
   InsertDTstampFirstPage(sActionText)

   REM Loop over every next page and print it
   For n = 1 to iPageCount
      Print_plain(n, sPrinter)
   next

   REM Remove the copystamp-frame
   RemoveDTstamp()

'Create PDF
   REM Replace .odt with _cp.pdf
   DIM sDocURL AS String, sPDFURL AS String
   sDocURL = oDoc.getURL()
   sPDFURL = Left$(sDocURL,Len(sDocURL)-4) + "_cp.pdf"

   REM Save as PDF
   DIM args(0) AS NEW com.sun.star.beans.PropertyValue
   args(0).Name = "FilterName"
   args(0).Value = "writer_pdf_Export"
   oDoc.storeToURL(sPDFURL,args())

   REM Remove the copystamp-frame
   RemoveDTstamp()

'ErrorHandler
Exit Sub
   ErrorHandler:
   Reset
   MsgBox "Error " & Err & ": " & Error$ + chr(13) + "At line : " + Erl + chr(13) + Now , 16 ,"an error occurred"
End Sub
Back to top
View user's profile Send private message
lknoll
General User
General User


Joined: 19 Oct 2011
Posts: 32
Location: Harrisburg, Pa

PostPosted: Fri May 03, 2013 6:48 am    Post subject: Reply with quote

Rather than looping through every page and printing each individually, you could specify a page range like "2-Total Number of pages"
Back to top
View user's profile Send private message
zenlord
Power User
Power User


Joined: 24 Nov 2006
Posts: 53

PostPosted: Fri May 03, 2013 7:00 am    Post subject: Reply with quote

You're right - rereading the code in light of your reply, I suppose you're right.

The only reason I can think of to not go that road is that it would make my code less flexible, since I would have to shift logic from the higher level functions to the lower level functions.

Or do you see a way to keep the flexibility and group the printing commands into 1?

Thx!
Back to top
View user's profile Send private message
lknoll
General User
General User


Joined: 19 Oct 2011
Posts: 32
Location: Harrisburg, Pa

PostPosted: Fri May 03, 2013 7:35 am    Post subject: Reply with quote

It was just an observation I made while I was working on a similar task. Thanks for posting your code. It was beneficial in helping me complete this task!

I needed to provide 3 macros to print 1 copy, print 2 copies, and print the first page only.

Code:
Sub PrintOneCopy
   SendToPrinter(ThisComponent, 1)
End Sub
Sub PrintTwoCopy
   SendToPrinter(ThisComponent, 2)
End Sub

Sub PrintFirstPage
   SendToPrinter(ThisComponent, 1, "1")
End Sub

Sub SendToPrinter(oDoc, Optional CopyNo, Optional Pages, Optional PrinterName)
   
   if isMissing(CopyNo) then
      CopyNo = 1
   end if
   if isMissing(Pages) then
      Pages = "1-" & oDoc.CurrentController.PageCount
   end if
   if isMissing(PrinterName) then
      count = 0
   else
      count = 1
   end if
   
   REM Set the chosen printer
   DIM mPrinterOpts(count) AS NEW com.sun.star.beans.PropertyValue
   mPrinterOpts(0).Name = "PaperOrientation"
   mPrinterOpts(0).Value = com.sun.star.view.PaperOrientation.PORTRAIT
   
   if count = 1 then
      mPrinterOpts(1).Name = "Name"
      mPrinterOpts(1).Value = PrinterName
   end if
   oDoc.Printer = mPrinterOpts()
      
   REM Set printOptions
   DIM mPrintOpts(3) AS NEW com.sun.star.beans.PropertyValue
   mPrintOpts(0).Name = "CopyCount"
   mPrintOpts(0).Value = CopyNo
   mPrintOpts(1).Name = "Collate"
   mPrintOpts(1).Value = True
   mPrintOpts(2).Name = "Pages"
   mPrintOpts(2).Value = Pages
   mPrintOpts(3).Name = "Wait"
   mPrintOpts(3).Value = True   
   REM Print
   oDoc.Print(mPrintOpts())

End Sub
Back to top
View user's profile Send private message
zenlord
Power User
Power User


Joined: 24 Nov 2006
Posts: 53

PostPosted: Fri May 03, 2013 10:23 am    Post subject: Reply with quote

Nice - I like the way you pass the object as an argument. I guess I never really grasped the fundamentals of OO programming...

I do wonder why you're setting the var 'count' instead of using the isMissing(PrinterName) directly? (or am I not seeing the whole code?)
Back to top
View user's profile Send private message
lknoll
General User
General User


Joined: 19 Oct 2011
Posts: 32
Location: Harrisburg, Pa

PostPosted: Fri May 03, 2013 11:01 am    Post subject: Reply with quote

I set count to use it here:
Code:
DIM mPrinterOpts(count) AS NEW com.sun.star.beans.PropertyValue
Back to top
View user's profile Send private message
zenlord
Power User
Power User


Joined: 24 Nov 2006
Posts: 53

PostPosted: Fri May 03, 2013 11:10 am    Post subject: Reply with quote

Aha, but you don't need that. As long as you define the number high enough, you can add variables. It's not like you need to determine upfront how many variables you will set.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group