Jump to content
JanZoudlik

Print table from script using internet browser

Recommended Posts

JanZoudlik

Hello everyone,

here is my little contribution to AutoIt community.

I was looking for a way to print tables from my scripts. None of the solutions was exactly working for me as there were always some limitations.

If you need to be able to print table, while making sure that header is printed on each page (if large table), rows won't split up(across several pages) and you want to be able to adjust table size on page or each column size, you in the right place. Also you can choose between landscape and portrait mode :)

It uses a browser to print table out. Simply, it generates a html file which is then open within browser and it initialize print. This version is tested with Chrome browser...

Please be aware that there is a bug. When you try to disable row numbers, it will also remove table borders(lines). If anybody can figure out why, it would be appreciated by me and I am sure by others as well.

Enjoy

Jan

UPDATE: found today that geniuses from Google stopped following standards and it no longer prints correctly with Chrome. It also ignores the portrait/landscape settings.

However, I tested it with latest IE on Win 7 and it works fine!!! so I suggest you use IE to print...

In case you don't have IE as main browser and you do have issues with your current browser then replace shellexecute and winwaitactive at the end of function with:

local $hIE=run('"C:\Program Files\Internet Explorer\iexplore.exe" "' & $sFile & '"')
ProcessWait($hIE)
; AutoIt Version: 3.3.10
; Language:       English
; Platform:       Win
; Author:         Jan Zoudlik
; NOTE:           big thanks to DoctorDestructo from http://stackoverflow.com/ for main script with css styling etc 
;                 and guinness, tproli, Lupo73 from https://www.autoitscript.com/forum/ for inspiration with their listview to html function
; Script Function:
;  table print - example + _table_print function

#include <File.au3>

Local $aTestArray[4][4] = [[20, 50, 20, 7], ["head", "heading<br/>accross two lines", "heading", "X"],["data row 1",5,"data",6],["data row 2",5&"<br/>"&6,"data",6]]
_table_print("test title",100,$aTestArray,True)

Func _table_print($Title,$Table_Size,ByRef $2D_array, $Landscape=True, $Row_Numbers=True)
   ;table that will print as table should (tested with chrome and ie browsers)> header on each page, table cell won't be printed across two pages > so even multi line row will always stay on one page or will be as whole pushed to next page
   ;to break the line within the cell or heading use "<br/>" not @LF or @CRLF as it is html... if word within cell is wider then column width it will adjust columnm width so word will fit, it will auto(line)break sentance if wider than column
   ;the allingment withing table is : vertical middle - horizontal left(header is vertical down - horizontal middle) and row numbers are vertical middle - horizontal right... sufficient for me...
   ;file name automatically generated and saved in temp folder
   ;Title - self explaining - displayed on the top of the table on first page only
   ;Table_Size - in percent - how big table(width) should be compare to the paper size so 100 - table will spread accross whole paper printable area, 50 - table size will be approx half of the paper size
   ;2D_array - row 0, number in percent per each column (width of column) - all together it should add up 100%(97% if row_numbers are used as 3% is used as size for row count column)
   ;2D_array - row 1, column header - will repeat on each page
   ;2D_array - row 2-n, data
   ;$Row_Numbers - first column will contain row number(so there will be one extra column in table)
   ;$Landscape - to print in landscape or portrait mode...
   ;paper size is as per printer settings
   ;font size is set to 10; if adjustment needed for blind people, then search for font-size: 10px; and don't forget to also adjust line-height: 13px accordingly(so it is bigger than font)
   ;_table_print function CREATED BY Jan Zoudlik
   ;big thanks to DoctorDestructo from http://stackoverflow.com/ for main script with css styling etc and guinness, tproli, Lupo73 from https://www.autoitscript.com/forum/ for inspiration with their listview to html function

   $sHTMLTable='<!DOCTYPE html>' & @CRLF & _
   '<html>' & @CRLF & _
   '  <body>' & @CRLF & _
   '    <table '
   if $Row_Numbers then $sHTMLTable=$sHTMLTable & 'class="print t1" '
   $sHTMLTable=$sHTMLTable & 'width="' & $Table_Size & '%"> <!-- Delete "t1" class to remove row numbers. -->' & @CRLF & _
   '      <caption>' & $Title & '</caption>' & @CRLF
   if $Row_Numbers then $sHTMLTable=$sHTMLTable & '     <col width="3%">' & @CRLF
   for $column=0 to ubound($2D_array,2)-1
      $sHTMLTable=$sHTMLTable & '       <col width="' & $2D_array[0][$column] & '%">' & @CRLF
   Next
   $sHTMLTable=$sHTMLTable & '      <thead>' & @CRLF & _
   '        <tr>' & @CRLF
   if $Row_Numbers then $sHTMLTable=$sHTMLTable & '          <th>#</th>' & @CRLF
   for $column=0 to ubound($2D_array,2)-1
      $sHTMLTable=$sHTMLTable & '          <th>' & $2D_array[1][$column] & '</th>' & @CRLF
   Next
   $sHTMLTable=$sHTMLTable & '        </tr>' & @CRLF & _
   '      </thead>' & @CRLF & _
   '      <tbody>' & @CRLF
   for $row=2 to ubound($2D_array)-1
      $sHTMLTable=$sHTMLTable & '        <tr>' & @CRLF
      if $Row_Numbers then $sHTMLTable=$sHTMLTable & '          <td></td>' & @CRLF
      for $column=0 to ubound($2D_array,2)-1
         $sHTMLTable=$sHTMLTable & '          <td>' & $2D_array[$row][$column] & '</td>' & @CRLF
      Next
      $sHTMLTable=$sHTMLTable & '        </tr>' & @CRLF
   Next
   $sHTMLTable=$sHTMLTable & '      </tbody>' & @CRLF & _
   '    </table>' & @CRLF & _
   '  </body>' & @CRLF & _
   '</html>' & @CRLF
   $sCSSstyle='<style>' & @CRLF & _
   '  /* THE FOLLOWING CSS IS REQUIRED AND SHOULD NOT BE MODIFIED. */' & @CRLF & _
   '    div.fauxRow {' & @CRLF & _
   '      display: inline-block;' & @CRLF & _
   '      vertical-align: top;' & @CRLF & _
   '      width: 100%;' & @CRLF & _
   '      page-break-inside: avoid;' & @CRLF & _
   '    }' & @CRLF & _
   '    table.fauxRow {border-spacing: 0;}' & @CRLF & _
   '    table.fauxRow > tbody > tr > td {' & @CRLF & _
   '      padding: 0;' & @CRLF & _
   '      overflow: hidden;' & @CRLF & _
   '    }' & @CRLF & _
   '    table.fauxRow > tbody > tr > td > table.print {' & @CRLF & _
   '      display: inline-table;' & @CRLF & _
   '      vertical-align: top;' & @CRLF & _
   '    }' & @CRLF & _
   '    table.fauxRow > tbody > tr > td > table.print > caption {caption-side: top;}' & @CRLF & _
   '    .noBreak {' & @CRLF & _
   '      float: right;' & @CRLF & _
   '      width: 100%;' & @CRLF & _
   '      visibility: hidden;' & @CRLF & _
   '    }' & @CRLF & _
   '    .noBreak:before, .noBreak:after {' & @CRLF & _
   '      display: block;' & @CRLF & _
   '      content: "";' & @CRLF & _
   '    }' & @CRLF & _
   '    .noBreak:after {margin-top: -594mm;}' & @CRLF & _
   '    .noBreak > div {' & @CRLF & _
   '      display: inline-block;' & @CRLF & _
   '      vertical-align: top;' & @CRLF & _
   '      width:100%;' & @CRLF & _
   '      page-break-inside: avoid;' & @CRLF & _
   '    }' & @CRLF & _
   '    /*table.print > thead {white-space: nowrap;}*/ /* Uncomment if line-wrapping causes problems. */' & @CRLF & _
   '    table.print > tbody > tr {page-break-inside: avoid;}' & @CRLF & _
   '    table.print > tbody > .metricsRow > td {border-top: none !important;}' & @CRLF & _
   '' & @CRLF & _
   '  /* THE FOLLOWING CSS IS REQUIRED, but the values may be adjusted. */' & @CRLF & _
   '    /* NOTE: All size values that can affect an elements height should use the px unit! */' & @CRLF & _
   '    table.fauxRow, table.print {' & @CRLF & _
   '      font-size: 10px;' & @CRLF & _
   '      line-height: 13px;' & @CRLF & _
   '    }' & @CRLF & _
   '' & @CRLF & _
   '  /* THE FOLLvOWING CSS IS OPTIONAL. */' & @CRLF
   if $Landscape then $sCSSstyle=$sCSSstyle & ' @page {size: landscape;} /* Delete to print in portrait mode*/' & @CRLF
   if $Row_Numbers then  $sCSSstyle=$sCSSstyle & '    body {counter-reset: t1;} /* Delete to remove row numbers. */' & @CRLF & _
   '    .noBreak .t1 > tbody > tr > :first-child:before {counter-increment: none;} /* Delete to remove row numbers. */' & @CRLF & _
   '    .t1 > tbody > tr > :first-child:before { /* Delete to remove row numbers. */' & @CRLF & _
   '      display: block;' & @CRLF & _
   '      text-align: right;' & @CRLF & _
   '      counter-increment: t1 1;' & @CRLF & _
   '      content: counter(t1);' & @CRLF & _
   '    }' & @CRLF
   $sCSSstyle=$sCSSstyle & '    table.fauxRow, table.print {' & @CRLF & _
   '      font-family: Tahoma, Verdana, Georgia; /* Try to use fonts that dont get bigger when printed. */' & @CRLF & _
   '      margin: 0 auto 0 auto; /* Delete if you dont want table to be centered. */' & @CRLF & _
   '    }' & @CRLF & _
   '    table.print {border-spacing: 0;}' & @CRLF & _
   '    table.print > * > tr > * {' & @CRLF & _
   '      border-right: 1px solid black;' & @CRLF & _
   '      border-bottom: 1px solid black;' & @CRLF & _
   '      padding: 0 3px 0 3px;' & @CRLF & _
   '    }' & @CRLF & _
   '    table.print > * > :first-child > * {border-top: 1px solid black;}' & @CRLF & _
   '    table.print > thead ~ * > :first-child > *, table.print > tbody ~ * > :first-child > * {border-top: none;} ' & @CRLF & _
   '    table.print > * > tr > :first-child {border-left: 1px solid black;}' & @CRLF & _
   '    table.print > thead {vertical-align: bottom;}' & @CRLF & _
   '    table.print > thead > .borderRow > th {border-bottom: none;}' & @CRLF & _
   '    table.print > tbody {vertical-align:middle;}' & @CRLF & _
   '    table.print > caption {font-weight: bold;}' & @CRLF & _
   '</style>' & @CRLF & _
   '' & @CRLF & _
   '<script>' & @CRLF & _
   '' & @CRLF & _
   '  (function() { // THIS FUNCTION IS REQUIRED.' & @CRLF & _
   '    if(/Firefox|MSIE |Trident/i.test(navigator.userAgent))' & @CRLF & _
   '        var formatForPrint = function(table) {' & @CRLF & _
   '        var noBreak = document.createElement("div")' & @CRLF & _
   '          , noBreakTable = noBreak.appendChild(document.createElement("div")).appendChild(table.cloneNode())' & @CRLF & _
   '          , tableParent = table.parentNode' & @CRLF & _
   '          , tableParts = table.children' & @CRLF & _
   '          , partCount = tableParts.length' & @CRLF & _
   '          , partNum = 0' & @CRLF & _
   '          , cell = table.querySelector("tbody > tr > td");' & @CRLF & _
   '        noBreak.className = "noBreak";' & @CRLF & _
   '        for(; partNum < partCount; partNum++) {' & @CRLF & _
   '          if(!/tbody/i.test(tableParts[partNum].tagName))' & @CRLF & _
   '            noBreakTable.appendChild(tableParts[partNum].cloneNode(true));' & @CRLF & _
   '        }' & @CRLF & _
   '        if(cell) {' & @CRLF & _
   '          noBreakTable.appendChild(cell.parentNode.parentNode.cloneNode()).appendChild(cell.parentNode.cloneNode(true));' & @CRLF & _
   '          if(!table.tHead) {' & @CRLF & _
   '            var borderRow = document.createElement("tr");' & @CRLF & _
   '            borderRow.appendChild(document.createElement("th")).colSpan="1000";' & @CRLF & _
   '            borderRow.className = "borderRow";' & @CRLF & _
   '            table.insertBefore(document.createElement("thead"), table.tBodies[0]).appendChild(borderRow);' & @CRLF & _
   '          }' & @CRLF & _
   '          }' & @CRLF & _
   '        tableParent.insertBefore(document.createElement("div"), table).style.paddingTop = ".009px";' & @CRLF & _
   '        tableParent.insertBefore(noBreak, table);' & @CRLF & _
   '      };' & @CRLF & _
   '      else' & @CRLF & _
   '      var formatForPrint = function(table) {' & @CRLF & _
   '      var tableParent = table.parentNode' & @CRLF & _
   '         , cell = table.querySelector("tbody > tr > td");' & @CRLF & _
   '        if(cell) {' & @CRLF & _
   '          var topFauxRow = document.createElement("table")' & @CRLF & _
   '            , fauxRowTable = topFauxRow.insertRow(0).insertCell(0).appendChild(table.cloneNode())' & @CRLF & _
   '            , colgroup = fauxRowTable.appendChild(document.createElement("colgroup"))' & @CRLF & _
   '            , headerHider = document.createElement("div")' & @CRLF & _
   '            , metricsRow = document.createElement("tr")' & @CRLF & _
   '            , cells = cell.parentNode.cells' & @CRLF & _
   '            , cellNum = cells.length' & @CRLF & _
   '            , colCount = 0' & @CRLF & _
   '            , tbods = table.tBodies' & @CRLF & _
   '            , tbodCount = tbods.length' & @CRLF & _
   '            , tbodNum = 0' & @CRLF & _
   '            , tbod = tbods[0];' & @CRLF & _
   '          for(; cellNum--; colCount += cells[cellNum].colSpan);' & @CRLF & _
   '          for(cellNum = colCount; cellNum--; metricsRow.appendChild(document.createElement("td")).style.padding = 0);' & @CRLF & _
   '          cells = metricsRow.cells;' & @CRLF & _
   '          tbod.insertBefore(metricsRow, tbod.firstChild);' & @CRLF & _
   '          for(; ++cellNum < colCount; colgroup.appendChild(document.createElement("col")).style.width = cells[cellNum].offsetWidth + "px");' & @CRLF & _
   '          var borderWidth = metricsRow.offsetHeight;' & @CRLF & _
   '          metricsRow.className = "metricsRow";' & @CRLF & _
   '          borderWidth -= metricsRow.offsetHeight;' & @CRLF & _
   '          tbod.removeChild(metricsRow);' & @CRLF & _
   '          tableParent.insertBefore(topFauxRow, table).className = "fauxRow";' & @CRLF & _
   '          if(table.tHead)' & @CRLF & _
   '            fauxRowTable.appendChild(table.tHead);' & @CRLF & _
   '          var fauxRow = topFauxRow.cloneNode(true)' & @CRLF & _
   '            , fauxRowCell = fauxRow.rows[0].cells[0];' & @CRLF & _
   '          fauxRowCell.insertBefore(headerHider, fauxRowCell.firstChild).style.marginBottom = -fauxRowTable.offsetHeight - borderWidth + "px";' & @CRLF & _
   '          if(table.caption)' & @CRLF & _
   '            fauxRowTable.insertBefore(table.caption, fauxRowTable.firstChild);' & @CRLF & _
   '          if(tbod.rows[0])' & @CRLF & _
   '            fauxRowTable.appendChild(tbod.cloneNode()).appendChild(tbod.rows[0]);' & @CRLF & _
   '          for(; tbodNum < tbodCount; tbodNum++) {' & @CRLF & _
   '            tbod = tbods[tbodNum];' & @CRLF & _
   '            rows = tbod.rows;' & @CRLF & _
   '            for(; rows[0]; tableParent.insertBefore(fauxRow.cloneNode(true), table).rows[0].cells[0].children[1].appendChild(tbod.cloneNode()).appendChild(rows[0]));' & @CRLF & _
   '          }' & @CRLF & _
   '        tableParent.removeChild(table);' & @CRLF & _
   '        }' & @CRLF & _
   '        else' & @CRLF & _
   '         tableParent.insertBefore(document.createElement("div"), table).appendChild(table).parentNode.className="fauxRow";' & @CRLF & _
   '      };' & @CRLF & _
   '    var tables = document.body.querySelectorAll("table.print")' & @CRLF & _
   '    , tableNum = tables.length;' & @CRLF & _
   '    for(; tableNum--; formatForPrint(tables[tableNum]));' & @CRLF & _
   '  })();' & @CRLF & _
   '</script>'

   $sFile=_TempFile ( @TempDir , "~", ".html" )
;~    $sFile= @ScriptDir  & "\Export.html"
   $hFile= FileOpen($sFile, 2 + 8)
   FileWrite($hFile,$sHTMLTable & $sCSSstyle)
   FileClose($hFile)
   If @error Then
      msgbox(0,"Print Error","Failed to close the file!")
   EndIf
   ShellExecute($sFile)
   WinWaitActive(StringTrimLeft($sFile,StringInStr($sFile,"\","",-1)))
   send("^p")
EndFunc ;==>_table_print
Edited by JanZoudlik
update
  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • stafe
      By stafe
      Hello
      I am trying to get chrome to save it's current webpage to a pdf using autoit.  I wold like to save the file into a folder on the desktop called "ChromeFiles" .  However when I use the send command chrome only occasionally responds.
      Thank you
      Simon
       
    • AndyS19
      By AndyS19
      I am trying to print using a small font, but no mater how I try it, the printed font remains unchanged.
      I have created a sample script that sets the font to 8.
      Here are the functions I use to create, then set the font:
      Func _Printer_SetFont($hDC) Local $hFont If ($a__Printer_Font == 0) Then _Printer_MakeFont() EndIf $hFont = $a__Printer_Font _LogMsg("+++: $hDC & " & $hDC & ", $hFont = " & $hFont) _WinAPI_SetFont($hDC, $hFont) ; <===================== EndFunc ;==>_Printer_SetFont Func _Printer_MakeFont() Local $hFontDC, $err, $errm, $str, $flag, $iHeight $flag = $FW_BOLD $iHeight = 8 $hFontDC = _WinAPI_CreateFont( _ $iHeight, _ 0, _ ; average character width 0, _ ; angle of escape 0, _ ; base-line orientation $flag, _ ; font weight - $FW_NORMAL, $FW_BOLD, etc. False, _ ; italic False, _ ; underline False, _ ; strikeout $DEFAULT_CHARSET, _ ; the character set $OUT_DEFAULT_PRECIS, _ ; the output precision $CLIP_DEFAULT_PRECIS, _ ; the clipping precision $DEFAULT_QUALITY, _ ; the output quality 0, _ ; the pitch and family of the font "courier new") ; typeface name _LogMsg("+++: $hFontDC = 0x" & Hex($hFontDC)) If ($hFontDC <= 0) Then $str = "_WinAPI_CreateFont() failed." & @CRLF $err = _WinAPI_GetLastError() $errm = _WinAPI_GetLastErrorMessage() _LogMsg("+++: " & $err & ", 0) - '" & $errm & "'" & @CRLF & $str) Exit (9) EndIf $a__Printer_Font = $hFontDC EndFunc ;==>_Printer_MakeFont Here is the complete script:
      #AutoIt3Wrapper_UseUpx=n #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 Opt('MustDeclareVars', 1) #include <APIDlgConstants.au3> #include <FontConstants.au3> #include <WinAPI.au3> ; #VARIABLES# ================================================================ Global $i__LastLineNum = -1, $i__NextLineNum = -1, $i__ThisLineNum = -1 Global $i__LeftMargin_X, $i__TopMargin_Y, $i__PageWidth, $i__PageHeight Global $i__CurrentPos_X, $i__CurrentPos_Y Global $i__Printer_Char_H = -1, $i__Printer_Char_W = -1 Global $a__Printer_Font = 0 Global $i__x_start, $i__x_end, $i__y_start, $i__y_end ; ============================================================================ ; #CONSTANTS# ================================================================ Global $PHYSICALWIDTH = 110, $PHYSICALHEIGHT = 111 Global $PHYSICALOFFSETX = 112, $PHYSICALOFFSETY = 113 Const $VLINESPACE = 20 ; Number of pixels between lines Global Const $tagPD = "align 1;DWORD lStructSize;" & "HWND hwndOwner;" & "handle hDevMode;" & "handle hDevNames;" & _ "handle hDC;" & "DWORD Flags;" & _ "WORD nFromPage;" & "WORD nToPage;" & "WORD nMinPage;" & "WORD nMaxPage;" & "WORD nCopies;" & _ "handle hInstance;" & "LPARAM lCustData;" & "ptr lpfnPrintHook;" & "ptr lpfnSetupHook;" & _ "ptr lpPrintTemplateName;" & "ptr lpSetupTemplateName;" & "handle hPrintTemplate;" & "handle hSetupTemplate" Global Const $tagDOCINFO = "int Size;" & "ptr DocName;" & "ptr Output;" & "ptr Datatype;" & "dword Type" ; ============================================================================ _Main() Func _Main() Local $hDC, $str, $str2 = "", $linenum $hDC = _Printer_Open(0, Default, "DOCNAME: ++++") _LogMsg("+++: $hPrintDc = 0x" & Hex($hDC)) If (Not $hDC) Then Exit (1) _Printer_SetFont($hDC) For $y = 1 To 10 $str2 &= "123456789." Next $linenum = 30 ; Start in the middle of the page For $x = 1 To 15 $str = "[" & $x & " " & $str2 _LogMsg("+++: $str ==>" & $str & "<==") _Printer_PrintTextLine($hDC, $str, $linenum) $linenum += 1 Next _Printer_Close($hDC) EndFunc ;==>_Main Func _Printer_SetFont($hDC) Local $hFont If ($a__Printer_Font == 0) Then _Printer_MakeFont() EndIf $hFont = $a__Printer_Font _LogMsg("+++: $hDC & " & $hDC & ", $hFont = " & $hFont) _WinAPI_SetFont($hDC, $hFont) ; <===================== EndFunc ;==>_Printer_SetFont Func _Printer_MakeFont() Local $hFontDC, $err, $errm, $str, $flag, $iHeight $flag = $FW_BOLD $iHeight = 8 $hFontDC = _WinAPI_CreateFont( _ $iHeight, _ 0, _ ; average character width 0, _ ; angle of escape 0, _ ; base-line orientation $flag, _ ; font weight - $FW_NORMAL, $FW_BOLD, etc. False, _ ; italic False, _ ; underline False, _ ; strikeout $DEFAULT_CHARSET, _ ; the character set $OUT_DEFAULT_PRECIS, _ ; the output precision $CLIP_DEFAULT_PRECIS, _ ; the clipping precision $DEFAULT_QUALITY, _ ; the output quality 0, _ ; the pitch and family of the font "courier new") ; typeface name _LogMsg("+++: $hFontDC = 0x" & Hex($hFontDC)) If ($hFontDC <= 0) Then $str = "_WinAPI_CreateFont() failed." & @CRLF $err = _WinAPI_GetLastError() $errm = _WinAPI_GetLastErrorMessage() _LogMsg("+++: " & $err & ", 0) - '" & $errm & "'" & @CRLF & $str) Exit (9) EndIf $a__Printer_Font = $hFontDC EndFunc ;==>_Printer_MakeFont Func _Printer_Open($hGUI = 0, $iFlags = Default, $sDocName = "") Local $hDC, $tPD, $err If $iFlags = Default Then $iFlags = 0 $iFlags = BitOR($iFlags, $PD_RETURNDC) $iFlags = BitOR($iFlags, $PD_USEDEVMODECOPIESANDCOLLATE) EndIf $tPD = DllStructCreate($tagPD) DllStructSetData($tPD, "lStructSize", DllStructGetSize($tPD)) DllStructSetData($tPD, "hwndOwner", $hGUI) ; If $hGUI <> 0 Then DllStructGetData($tPD, "hInstance", _WinAPI_GetModuleHandle("")) EndIf DllStructSetData($tPD, "Flags", $iFlags) DllStructSetData($tPD, "nCopies", 2) Local $bRet = DllCall("Comdlg32.dll", "int", "PrintDlgW", "ptr", DllStructGetPtr($tPD)) $err = @error If $err Then $err = _WinAPI_GetLastError() Local $errm = _WinAPI_GetLastErrorMessage() _LogMsg("+++: _Printer_Open() returns: (1, " & $err & ", 0) - '" & $errm & "'") $tPD = 0 Return SetError(1, $err, 0) EndIf If $bRet[0] = True Then $hDC = DllStructGetData($tPD, "hDC") Else Return SetError(2, $err, 0) EndIf $tPD = 0 __Printer_SetupCharWH($hDC) _Printer_GetMetrics($hDC) _Printer_Startup($hDC, $sDocName) Return (SetError(0, 0, $hDC)) EndFunc ;==>_Printer_Open Func _Printer_Startup($hDC, $sDocName) Local $oDocNameStruct, $DOCINFO, $printJobID, $errstr __Printer_SetupCharWH($hDC) ; Get the height and width of a printer character $oDocNameStruct = DllStructCreate("char DocName[" & StringLen($sDocName & Chr(0)) & "]") DllStructSetData($oDocNameStruct, "DocName", $sDocName & Chr(0)) ; Size of DOCINFO structure $DOCINFO = DllStructCreate($tagDOCINFO) ; Structure for Print Document info DllStructSetData($DOCINFO, "Size", 20) ; Size of DOCINFO structure DllStructSetData($DOCINFO, "DocName", DllStructGetPtr($oDocNameStruct)) ; Set name of print job (Optional) _Printer_GetMetrics($hDC) $printJobID = _Printer_StartDoc($hDC, $DOCINFO) ; start new print doc If ($printJobID <= 0) Then $errstr = "_Printer_StartDoc() failed" _LogMsg("+++: _Printer_Startup() returns: @error = 1 - " & $errstr) Return (SetError(1, 0, $errstr)) EndIf Return (SetError(0, 0, $printJobID)) ; print job ID EndFunc ;==>_Printer_Startup Func _Printer_Close($hDC) _Printer_EndPage($hDC) ; End the currend page _Printer_EndDoc($hDC) ; End the print job _WinAPI_DeleteDC($hDC) ; Delete the printer device context EndFunc ;==>_Printer_Close Func _Printer_EndPage($hDC) Local $aResult If ($i__ThisLineNum > 1) Then $aResult = DllCall("GDI32.dll", "long", "EndPage", "hwnd", $hDC) EndIf _Printer_SetInitial_XY() $i__ThisLineNum = -1 Return ($aResult[0]) EndFunc ;==>_Printer_EndPage Func _Printer_EndDoc($hDC) Local $aResult $aResult = DllCall("GDI32.dll", "long", "EndDoc", "hwnd", $hDC) Return ($aResult[0]) EndFunc ;==>_Printer_EndDoc Func _Printer_TextOut($hDC, $iXStart, $iYStart, $sString) Local $aResult $aResult = DllCall("GDI32.dll", _ "long", "TextOut", _ "hwnd", $hDC, _ "long", $iXStart, _ "long", $iYStart, _ "str", $sString, _ "long", StringLen($sString)) Return $aResult[0] ; 0 = fail, 1 = OK EndFunc ;==>_Printer_TextOut Func _Printer_PrintTextLine($hDC, $sText, $iLineNumber = -1) Local $ret, $lines, $ndx If ($iLineNumber <= 0) Then $iLineNumber = $i__ThisLineNum EndIf $sText = StringStripWS($sText, 2) ; Clear trailing whitespace ; Break text into an array of lines, based on any of the ; usual line endings (@CR, @LF, etc.) found in the string. $sText = StringRegExpReplace($sText, "[\\][n]", @CR) $sText = StringReplace($sText, @CRLF, @LF) $sText = StringReplace($sText, @CR, @LF) While (StringRight($sText, 1) == @LF) StringTrimRight($sText, 1) ; remove trailing LF's WEnd $lines = StringSplit($sText, @LF, 2) ; Now print each line in the array of lines, advancing the ; printer line position each time For $ndx = 0 To UBound($lines) - 1 $i__CurrentPos_X = $i__x_start ; $i__LeftMargin_X $i__CurrentPos_Y = (($i__Printer_Char_H + $VLINESPACE) * $iLineNumber) + $i__y_start $ret = _Printer_TextOut($hDC, $i__CurrentPos_X, $i__CurrentPos_Y, $lines[$ndx]) $iLineNumber += 1 $i__ThisLineNum += 1 If ($ret == 0) Then ExitLoop If ($iLineNumber > $i__LastLineNum) Then _Printer_EndPage($hDC) $iLineNumber = 1 $i__ThisLineNum = 1 EndIf Next ; Calculate next x/y position $i__CurrentPos_Y = (($i__Printer_Char_H + $VLINESPACE) * $iLineNumber) Return (SetError(0, 0, $iLineNumber)) EndFunc ;==>_Printer_PrintTextLine Func _Printer_StartDoc($hDC, $tDocInfo) Local $aResult $aResult = DllCall("GDI32.dll", "long", "StartDoc", "hwnd", $hDC, "ptr", DllStructGetPtr($tDocInfo)) _Printer_SetInitial_XY() Return ($aResult[0]) ; >0 = OK, <=0 = Fail EndFunc ;==>_Printer_StartDoc Func _Printer_GetMetrics($hDC) $i__LeftMargin_X = _WinAPI_GetDeviceCaps($hDC, $PHYSICALOFFSETX) $i__TopMargin_Y = _WinAPI_GetDeviceCaps($hDC, $PHYSICALOFFSETY) $i__PageWidth = _WinAPI_GetDeviceCaps($hDC, $PHYSICALWIDTH) $i__PageHeight = _WinAPI_GetDeviceCaps($hDC, $PHYSICALHEIGHT) #Tidy_Off _LogMsg("+++:" & @CRLF _ & "$PHYSICALOFFSETX [" & $PHYSICALOFFSETX & "] $i__LeftMargin_X = " & $i__LeftMargin_X & @CRLF _ & "$PHYSICALOFFSETY [" & $PHYSICALOFFSETY & "] $i__TopMargin_Y = " & $i__TopMargin_Y & @CRLF _ & "$PHYSICALWIDTH [" & $PHYSICALWIDTH & "] $i__PageWidth = " & $i__PageWidth & @CRLF _ & "$PHYSICALHEIGHT [" & $PHYSICALHEIGHT & "] $i__PageHeight = " & $i__PageHeight & @CRLF _ ) #Tidy_On $i__x_start = $i__LeftMargin_X - 75 $i__y_start = $i__TopMargin_Y - 75 $i__x_end = $i__PageWidth - 250 $i__y_end = $i__PageHeight - 200 _Printer_SetInitial_XY() $i__LastLineNum = _Printer_GetLastLineNum() EndFunc ;==>_Printer_GetMetrics Func _Printer_SetInitial_XY() $i__CurrentPos_X = $i__LeftMargin_X $i__CurrentPos_Y = $i__TopMargin_Y * 22 EndFunc ;==>_Printer_SetInitial_XY Func _Printer_GetLastLineNum() Local $x1, $y, $linenumber $linenumber = -1 If ($i__Printer_Char_H > 0) Then For $x1 = 1 To 999 $y = (($i__Printer_Char_H + $VLINESPACE) * ($x1 + 1)) If ($y >= $i__y_end) Then $linenumber = $x1 ExitLoop EndIf Next EndIf If ($linenumber == -1) Then MsgBox(0, "Internal Error", "ERROR: Could not calculate the last line number") Exit (1) EndIf $linenumber -= 1 Return ($linenumber) EndFunc ;==>_Printer_GetLastLineNum Func __Printer_SetupCharWH($hDC) Local $vExtents $vExtents = _WinAPI_GetTextExtentPoint32($hDC, "x") $i__Printer_Char_W = DllStructGetData($vExtents, "X") ; Get the width of a character $i__Printer_Char_H = DllStructGetData($vExtents, "Y") ; Get the height of a character EndFunc ;==>__Printer_SetupCharWH Func _LogMsg($msg, $lnum = @ScriptLineNumber) If (StringLeft($msg, 4) = "+++:") Then $msg = StringTrimLeft($msg, 5) $msg = StringStripWS($msg, 3) ConsoleWrite("+++:" & $lnum & "] " & $msg & @CRLF) EndFunc ;==>_LogMsg Func _Printer_SetFont($hDC) Local $hFont If ($a__Printer_Font == 0) Then _Printer_MakeFont() EndIf $hFont = $a__Printer_Font _LogMsg("+++: $hDC & " & $hDC & ", $hFont = " & $hFont) _WinAPI_SetFont($hDC, $hFont) ; <===================== EndFunc ;==>_Printer_SetFont Func _Printer_MakeFont() Local $hFontDC, $err, $errm, $str, $flag, $iHeight $flag = $FW_BOLD $iHeight = 8 $hFontDC = _WinAPI_CreateFont( _ $iHeight, _ 0, _ ; average character width 0, _ ; angle of escape 0, _ ; base-line orientation $flag, _ ; font weight - $FW_NORMAL, $FW_BOLD, etc. False, _ ; italic False, _ ; underline False, _ ; strikeout $DEFAULT_CHARSET, _ ; the character set $OUT_DEFAULT_PRECIS, _ ; the output precision $CLIP_DEFAULT_PRECIS, _ ; the clipping precision $DEFAULT_QUALITY, _ ; the output quality 0, _ ; the pitch and family of the font "courier new") ; typeface name _LogMsg("+++: $hFontDC = 0x" & Hex($hFontDC)) If ($hFontDC <= 0) Then $str = "_WinAPI_CreateFont() failed." & @CRLF $err = _WinAPI_GetLastError() $errm = _WinAPI_GetLastErrorMessage() _LogMsg("+++: " & $err & ", 0) - '" & $errm & "'" & @CRLF & $str) Exit (9) EndIf $a__Printer_Font = $hFontDC EndFunc ;==>_Printer_MakeFont Here is the full script.  Run it to see the problem:
    • iamtech
      By iamtech
      When I click on print button (Javascript Button) in webpage using _IEAction($btnprint,"click") then display print dialog, like this one:
      i want to Automate this print dialog box and print file using default printer. (not using controlclick).
      its possible to print without showing print dialog box?

    • natedog102
      By natedog102
      Hi everyone. I want to format the output of _INetGetSource to look nice and pretty. 
      Example google.com source output: 
      <!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script>(function(){window.google={kEI:'DJtTWvCOI6WGjwSE9JrICg',kEXPI:'18167,1354277,1354916,1355218,1355675,1355793,1356171,1356806,1357219,1357326,3700304,3700519,3700521,4003510,4029815,4031109,4043492,4045841,4048347,4081038,4081164,4095909,4096834,4097153,4097195,4097922,4097929,4098733,4098740,4098752,4102237,4102827,4103475,4103845,4106084,4107914,4109316,4109490,4112770,4113217,4115697,4116349,4116724,4116731,4116926,4116927,4116935,4117980,4118798,4119032,4119034,4119036,4120285,4120286,4120660,4121175,4121518,4122511,4123830,4123850,4124091,4124850,4125837,4126202,4126754,4126869,4127262,4127418,4127473,4127744,4127863,4128586,4128622,4129001,4129520,4129556,4129633,4130362,4130783,4131247,4131834,4132956,4133114,4133509,4135025,4135088,4135249,4135934,4136073,4136092,4136137,4137597,4137646,4140792,4140849,4141281,4141707,4141915,4142071,4142328,4142420,4142443,4142503,4142678,4142729,4142829,4142834,4142847,4143278,4143527,4143902,4144442,4144550,4144704,4145074,4145075,4145082,4145088,4145461,4145485,4145622,4145688,4145713,4145836,4146146,4146183,4146874,4147032,4147043,4147096,4147443,4147800,4147951,4148257,4148304,4148436,4148498,4148573,6512220,10200083,10202524,10202562,15807763,19000288,19000423,19000427,19001999,19002287,19002288,19002366,19002548,19002880,19003321,19003323,19003325,19003326,19003328,19003329,19003330,19003407,19003408,19003409,19004309,19004516,19004517,19004518,19004519,19004520,19004521,19004531,19004656,19004668,19004670,19004692,41317155',authuser:0,kscs:'c9c918f0_DJtTWvCOI6WGjwSE9JrICg',u:'c9c918f0',kGL:'US'};google.kHL='en';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){return"https:"==window.location.protocol};google.ml=function(){return null};google.wl=function(a,b){try{google.ml(Error(a),!1,b)}catch(d){}};google.time=function(){return(new Date).getTime()};google.log=function(a,b,d,c,g){if(a=google.logUrl(a,b,d,c,g)){b=new Image;var e=google.lc,f=google.li;e[f]=b;b.onerror=b.onload=b.onabort=function(){delete e[f]};google.vel&&google.vel.lu&&google.vel.lu(a);b.src=a;google.li=f+1}};google.logUrl=function(a,b,d,c,g){var e="",f=google.ls||"";d||-1!=b.search("&ei=")||(e="&ei="+google.getEI(c),-1==b.search("&lei=")&&(c=google.getLEI(c))&&(e+="&lei="+c));c="";!d&&google.cshid&&-1==b.search("&cshid=")&&(c="&cshid="+google.cshid);a=d||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+e+f+"&zx="+google.time()+c;/^http:/i.test(a)&&google.https()&&(google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a};}).call(this);(function(){google.y={};google.x=function(a,b){if(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.lm=[];google.plm=function(a){google.lm.push.apply(google.lm,a)};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};}).call(this);google.f={};var a=window.location,b=a.href.indexOf("#");if(0<=b){var c=a.href.substring(b+1);/(^|&)q=/.test(c)&&-1==c.indexOf("#")&&a.replace("/search?"+c.replace(/(^|&)fp=[^&]*/g,"")+"&cad=h")};</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important} But I want it outputted like this:
      <!doctype html> <html itemscope="" itemtype="http://schema.org/WebPage" lang="en"> <head> <meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"> <meta content="noodp" name="robots"> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"> <title>Google</title> <script> (function() { window.google = { kEI: 'DJtsdfgWGjwSE9JrICg', kEXPI: '18167,1354277,1354916,1355218,1355675,1355793,1356171,1356806,1357219,1357326,37sdfg0304,3700519,3700521,4003510,4029815,4031109,4043492,4045841,4048347,4081038,4081164,4095909,4096834,4097153,4097195,4097922,4097929,4098733,4098740,4098752,4102237,4102827,4103475,4103845,4106084,4107914,4109316,4109490,4112770,4113217,4115697,4116349,4116724,4116731,4116926,4116927,4116935,4117980,4118798,4119032,4119034,4119036,4120285,4120286,4120660,4121175,4121518,4122511,4123830,4123850,4124091,4124850,4125837,4126202,4126754,4126869,4127262,4127418,4127473,4127744,4127863,4128586,4128622,4129001,4129520,4129556,4129633,4130362,4130783,4131247,4131834,413sdfg56,4133114,4133509,4135025,4135088,4135249,4135934,4136073,4136092,4136137,4137597,4137646,4140792,4140849,4141281,4141707,4141915,4142071,4142328,4142420,4142443,4142503,4142678,4142729,4142829,4142834,4142847,4143278,4143527,4143902,4144442,4144550,4144704,4145074,4145075,4145082,4145088,4145461,4145485,4145622,4145688,4145713,4145836,4146146,4146183,4146874,4147032,4147043,4147096,4147443,4147800,4147951,4148257,4148304,4148436,4148498,4148573,6512220,10200083,10202524,10202562,15807763,19000288,190sdfg23,19000427,19001999,19002287,19002288,19002366,19002548,19002880,19003321,19003323,19003325,19003326,19003328,19003329,19003330,19003407,19003408,19003409,19004309,19004516,19004517,19004518,19004519,19004520,19004521,19004531,19004656,19004668,19004670,19004692,41317155', authuser: 0, kscs: 'c9c918f0_DJtTWvCOI6WGjwSE9JrICg', u: 'c9c918f0', kGL: 'US' }; google.kHL = 'en'; })(); ....... I checked the forums and did not see any UDFs that allow for this. I see the Chilkat UDF but that only supports JSON. Any help would be greatly appreciated.
    • argumentum
      By argumentum
      by  eltorro Posted April 26, 2010
      Most print preview solutions use the MFC Doc/View architecture which limits it usefulness outside of c++. I found an article where a Delphi programmer used Enhanced Meta Files wrapped in a custom header and packaged together to create a print preview control. After a little more searching, It looks like using EMFs is a solution that would work.
      Some people suggest to create the document in Word or HTML and use Word or a browser to view it. Indeed, I have rendered documents to HTML and used the IE UDF to display the contents and/or print them. Not quite as ideal as one would like.
      Using GRS's printwin.au3 as a start, I came up with a print preview solution which others may be able to expand upon
×