что использовать для скрипта, печатающего документы на принтере с разными настройками?
Собственно, мне по работе прилетают много документов docx, которые я должен печатать с разными настройками принтера в зависимости от количества страниц. Если 2, то двухсторонняя печать. Если больше 4, то размещать по две страницы на лист и печать с двух сторон. Это как правило, но не всегда.
Я решил, что надо автоматизировать этот процесс, но не знаю куда копать. Что стоит использовать? Python? C#? Java? Bat скрипт? какие библиотеки подключить? Или может есть какая-нибудь программа для подобных условий? Интерфейс не важен, можно через консоль.
Дайте совет, пожалуйста. Буду очень признателен.
Ответы (1 шт):
Путем некоторого гуглинга я выяснил, что проще всего мою задачу решить с помощью Visual Basic Applications.
Оставлю некоторые зацепки для тех, кто ищет что-то подобное.
С помощью данного фрагмента мы можем подсчитать количество страниц текущего открытого ворд документа:
Dim NumPages As Long
NumPages = ActiveDocument.ActiveWindow.Panes(1).Pages.Count
Печатать документ несложно, для этого поможет строчка:
ActiveDocument.PrintOut Background:=True, Copies:=5, Collate:=True, PrintZoomColumn:=2, PrintZoomRow:=1 '5 копий будет напечатано
С печатью с двух сторон оказалось труднее, так как VBA в настройки принтера доступа не имеет, но нам может помочь такой код:
' Due to 64-bit version some pointers were changed into LogtPtr type of data
Option Explicit
Public Type PRINTER_DEFAULTS
pDatatype As LongPtr
pDevmode As LongPtr
DesiredAccess As LongPtr
End Type
Public Type PRINTER_INFO_2
pServerName As LongPtr
pPrinterName As LongPtr
pShareName As LongPtr
pPortName As LongPtr
pDriverName As LongPtr
pComment As LongPtr
pLocation As LongPtr
pDevmode As LongPtr ' Pointer to DEVMODE
pSepFile As LongPtr
pPrintProcessor As LongPtr
pDatatype As LongPtr
pParameters As LongPtr
pSecurityDescriptor As LongPtr ' Pointer to SECURITY_DESCRIPTOR
Attributes As LongPtr
Priority As Long
DefaultPriority As Long
StartTime As Long
UntilTime As Long
Status As Long
cJobs As Long
AveragePPM As Long
End Type
Public Type DEVMODE
dmDeviceName As String * 32
dmSpecVersion As Integer
dmDriverVersion As Integer
dmSize As Integer
dmDriverExtra As Integer
dmFields As Long
dmOrientation As Integer
dmPaperSize As Integer
dmPaperLength As Integer
dmPaperWidth As Integer
dmScale As Integer
dmCopies As Integer
dmDefaultSource As Integer
dmPrintQuality As Integer
dmColor As Integer
dmDuplex As Integer
dmYResolution As Integer
dmTTOption As Integer
dmCollate As Integer
dmFormName As String * 32
dmUnusedPadding As Integer
dmBitsPerPel As Integer
dmPelsWidth As Long
dmPelsHeight As Long
dmDisplayFlags As Long
dmDisplayFrequency As Long
dmICMMethod As Long
dmICMIntent As Long
dmMediaType As Long
dmDitherType As Long
dmReserved1 As Long
dmReserved2 As Long
End Type
Public Const DM_DUPLEX = &H1000&
Public Const DM_IN_BUFFER = 8
Public Const DM_OUT_BUFFER = 2
Public Const PRINTER_ACCESS_ADMINISTER = &H4
Public Const PRINTER_ACCESS_USE = &H8
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Public Const PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or _
PRINTER_ACCESS_ADMINISTER Or PRINTER_ACCESS_USE)
Public Declare PtrSafe Function ClosePrinter Lib "winspool.drv" _
(ByVal hPrinter As LongPtr) As Long
Public Declare PtrSafe Function DocumentProperties Lib "winspool.drv" _
Alias "DocumentPropertiesA" (ByVal hwnd As Long, _
ByVal hPrinter As LongPtr, ByVal pDeviceName As String, _
ByVal pDevModeOutput As LongPtr, ByVal pDevModeInput As LongPtr, _
ByVal fMode As LongPtr) As Long
Public Declare PtrSafe Function GetPrinter Lib "winspool.drv" Alias _
"GetPrinterA" (ByVal hPrinter As LongPtr, ByVal Level As Long, _
pPrinter As Byte, ByVal cbBuf As Long, pcbNeeded As Long) As Long
Public Declare PtrSafe Function OpenPrinter Lib "winspool.drv" Alias _
"OpenPrinterA" (ByVal pPrinterName As String, phPrinter As LongPtr, _
pDefault As PRINTER_DEFAULTS) As Long
Public Declare PtrSafe Function SetPrinter Lib "winspool.drv" Alias _
"SetPrinterA" (ByVal hPrinter As LongPtr, ByVal Level As Long, _
pPrinter As Byte, ByVal Command As Long) As Long
Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(pDest As Any, pSource As Any, ByVal cbLength As LongPtr)
Public Function SetPrinterDuplex(ByVal sPrinterName As String, _
ByVal nDuplexSetting As Long) As Boolean
Dim hPrinter As LongPtr
Dim pd As PRINTER_DEFAULTS
Dim pinfo As PRINTER_INFO_2
Dim dm As DEVMODE
Dim yDevModeData() As Byte
Dim yPInfoMemory() As Byte
Dim nBytesNeeded As Long
Dim nRet As Long, nJunk As Long
On Error GoTo cleanup
If (nDuplexSetting < 1) Or (nDuplexSetting > 3) Then
MsgBox "Error: dwDuplexSetting is incorrect."
Exit Function
End If
pd.DesiredAccess = PRINTER_ALL_ACCESS
nRet = OpenPrinter(sPrinterName, hPrinter, pd)
If (nRet = 0) Or (hPrinter = 0) Then
If Err.LastDllError = 5 Then
MsgBox "Access denied -- See the article for more info."
Else
MsgBox "Cannot open the printer specified " & _
"(make sure the printer name is correct)."
End If
Exit Function
End If
nRet = DocumentProperties(0, hPrinter, sPrinterName, 0, 0, 0)
If (nRet < 0) Then
MsgBox "Cannot get the size of the DEVMODE structure."
GoTo cleanup
End If
ReDim yDevModeData(nRet + 100) As Byte
nRet = DocumentProperties(0, hPrinter, sPrinterName, _
VarPtr(yDevModeData(0)), 0, DM_OUT_BUFFER)
If (nRet < 0) Then
MsgBox "Cannot get the DEVMODE structure."
GoTo cleanup
End If
Call CopyMemory(dm, yDevModeData(0), Len(dm))
If Not CBool(dm.dmFields And DM_DUPLEX) Then
MsgBox "You cannot modify the duplex flag for this printer " & _
"because it does not support duplex or the driver " & _
"does not support setting it from the Windows API."
GoTo cleanup
End If
dm.dmDuplex = nDuplexSetting
Call CopyMemory(yDevModeData(0), dm, Len(dm))
nRet = DocumentProperties(0, hPrinter, sPrinterName, _
VarPtr(yDevModeData(0)), VarPtr(yDevModeData(0)), _
DM_IN_BUFFER Or DM_OUT_BUFFER)
If (nRet < 0) Then
MsgBox "Unable to set duplex setting to this printer."
GoTo cleanup
End If
Call GetPrinter(hPrinter, 2, 0, 0, nBytesNeeded)
If (nBytesNeeded = 0) Then GoTo cleanup
ReDim yPInfoMemory(nBytesNeeded + 100) As Byte
nRet = GetPrinter(hPrinter, 2, yPInfoMemory(0), nBytesNeeded, nJunk)
If (nRet = 0) Then
MsgBox "Unable to get shared printer settings."
GoTo cleanup
End If
Call CopyMemory(pinfo, yPInfoMemory(0), Len(pinfo))
pinfo.pDevmode = VarPtr(yDevModeData(0))
pinfo.pSecurityDescriptor = 0
Call CopyMemory(yPInfoMemory(0), pinfo, Len(pinfo))
nRet = SetPrinter(hPrinter, 2, yPInfoMemory(0), 0)
If (nRet = 0) Then
MsgBox "Unable to set shared printer settings."
End If
SetPrinterDuplex = CBool(nRet)
cleanup:
If (hPrinter <> 0) Then Call ClosePrinter(hPrinter)
End Function
Теперь мы можем использовать принтер при печати следующим фрагментом:
ActivePrinter = "ПИШЕМ СЮДА НАЗВАНИЕ ПРИНТЕРА"
Call SetPrinterDuplex(ActivePrinter, 2) '2 - печать с отражением по длинной стороне, 3 - печать по короткой стороне
ActiveDocument.PrintOut Background:=True, Copies:=NumbersArray(i), Collate:=True, PrintZoomColumn:=1, PrintZoomRow:=1
С помощью параметра PrintZoomColumn мы можем задать количество столбцов, с помощью PrintZoomRow можем задать количество рядов. Параметр Collate призывает печатать текущую копию до конца, это когда мы множественные копии используем.
Осталось только добавить логику скрипта и автоматизация готова.
Вот как-то так.