打印機設置一等分、二等分、三等分打印尺寸使用教程
一、設置方法概述:
通過在系統的打印機中,創建3種尺寸紙張大小的打印模版,然後在打印的時候,選擇對應尺寸的打印模版進行打印即可。
二、不同紙張尺寸大小說明:
A4:21.0cm*29.7cm
針式打印紙1等分:24.1cm*28.0cm;
針式打印紙2等分:24.1cm*14.0cm;
針式打印紙3等分:24.1cm*9.3cm。
三、操作步驟:
(一)設置打印尺寸模版
如果你使用的電腦是Windows 7系統:
1.點擊開始-設備和打印機,進入對應頁面;
2.隨便選中一個打印機,上方會顯示“打印服務器屬性”,點擊“打印服務器屬性”;
3.進入打印服務器屬性頁面,勾選創建新紙張規格,填寫紙張規格名稱和紙張大小,例如填寫名稱“3等分“,寬度24.1cm,高度9.3cm。最後點擊確定按鈕。
如果你使用的電腦是Windows 10系統:
1.點擊開始-設置-設備-打印機和掃描儀,下拉到底部,點擊打印服務器屬性;
2.同Windows 7系統中的步驟3
(二)打印時選擇正確尺寸模版
1.在使用瀏覽器的打印功能時,都可以選擇事先創建的紙張尺寸。例如下圖展示了有贊中採購訂單打印頁面,點擊打印後,可以在紙張尺寸中選擇“3等分”這個尺寸。
2.如果打印頁面沒有紙張尺寸的選項,可以點擊下方的更多設置按鈕。
3.每個不同的瀏覽器都會默認記住上一次選擇的紙張尺寸,只需要選擇1次即可。如果更換瀏覽器,請重新選擇紙張尺寸。
CSS page-break-after 屬性
實例
在 <footer> 元素後始終插入分頁符:
屬性定義及使用說明
page-break-after 屬性用於設置在指定元素後面插入分頁符。
注意: 您不能對絕對定位的元素使用此屬性。
注意: 請儘可能少地使用分頁屬性,並且避免在表格、浮動元素、帶有邊框的塊元素中使用分頁屬性。
默認值: | auto |
---|---|
繼承: | no |
版本: | CSS2 |
JavaScript 語法: | object.style.pageBreakAfter="always" |
屬性值
值 | 描述 |
---|---|
auto | 默認。如果必要則在元素後插入分頁符。 |
always | 在元素後插入分頁符。 |
avoid | 避免在元素後插入分頁符。 |
left | 在元素之後足夠的分頁符,一直到一張空白的左頁爲止。 |
right | 在元素之後足夠的分頁符,一直到一張空白的右頁爲止。 |
inherit |
規定應該從父元素繼承 page-break-after 屬性的設置。 |
前端實現打印預覽功能以及page-break-inside屬性解決打印換行問題(打印預覽表格或文字被分割開)
崽崽的穀雨
於 2021-05-18 09:48:59 發佈
2827
收藏 3
分類專欄: 前端 js 文章標籤: javascript
版權
前端
同時被 2 個專欄收錄
12 篇文章0 訂閱
訂閱專欄
js
45 篇文章0 訂閱
訂閱專欄
前言:
做項目的時候可能會遇到打印,不管是調用系統的(Ctrl+shift+p)或者瀏覽器裏window.print();
打印實現方案:
1.調用系統的(Ctrl+shift+p);
2.調用瀏覽器裏window.print(); window.print() api
window.print():默認打印當前頁面body裏的所有內容。當然也可以打印局部。思路就是把要打印的臨時賦值給body然後再重新賦值會原來的。
function doPrint2(){
//根據div標籤ID拿到div中的局部內容
bdhtml=window.document.body.innerHTML;
var jubuData = document.getElementById("printcontent").innerHTML;
//把獲取的 局部div內容賦給body標籤, 相當於重置了 body裏的內容
window.document.body.innerHTML= jubuData;
//調用打印功能
window.print();
window.document.body.innerHTML=bdhtml;//重新給頁面內容賦值;
return false;
}
參考:window.print實現局部打印
window.onbeforeprint()--打印之前做的事 onbeforeprint api
window.onafterprint()--打印之後做的事 nafterprint api
3.實際上轉換成圖片再打印也行或者截圖打印(當然效果不太好,對於海報之類的可能會好些可以用)這個也是一個思路建議用上面的。
例如:html2Canvas html2Cavas遇到的問題及解決方案 html2Cavas官網 api
定義和用法
onbeforeprint 事件在頁面即將打印時觸發 (在打印窗口出現前)。
提示: onbeforeprint 事件的相反事件爲 onafterprint 。
遇到的問題:
打印預覽的時候表格被分割了,就是一共兩頁而其中一行顯示在不同的兩個頁面(而不想讓tr被隔開,很難看)。如下圖:
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
tr {
width: 500px;
height: 500px;
}
table {
/* width: 200px; */
border-top: 1px solid #999;
border-left: 1px solid #999;
border-spacing: 0;
/*去掉單元格間隙*/
}
</style>
</head>
<body>
<button onclick=func()>printthis page</button>
<table border="1px">
<tr>
<th>nmae</th>
<th>age</th>
</tr>
<tr>
<td>33</td>
<td>33</td>
</tr>
<tr>
<td>33</td>
<td>33</td>
</tr>
<tr class="vv">
<td>33</td>
<td>33</td>
</tr>
</table>
</body>
<script>
function func() {
window.print();
}
</script>
</html>
解決方案:
給tr加上age-break-inside: avoid;
tr {
width: 500px;
height: 500px;
page-break-inside: avoid;
/* page-break-before: avoid;
page-break-after: avoid; */
}
加上之後效果圖
瀏覽器支持
表格中的數字註明了完全支持該屬性的首個瀏覽器版本。
屬性 Chrome IE Firefox Safari Opera
page-break-inside 1.0 8.0 19.0 1.3 7.0
一、定義和用法 (page-break-inside)
page-break-inside 屬性設置元素內部的 page-breaking 行爲。
儘管可以用 always 強制放上分頁符,但是無法保證避免分頁符的插入,創作人員最多隻能要求用戶代理儘可能避免插入分頁。
應用於:position 值爲 relative 或 static 的非浮動塊級元素。
註釋:請儘可能少地使用分頁屬性,並且避免在表格、浮動元素、帶有邊框的塊元素中使用分頁屬性。
默認值: auto
繼承性: no
版本: CSS2
JavaScript 語法: object.style.pageBreakInside="avoid"
可能的值
值 描述
auto 默認。如果必要則在元素內部插入分頁符。
avoid 避免在元素內部插入分頁符。
inherit 規定應該從父元素繼承 page-break-inside 屬性的設置。
參考: w3c page-break-inside api
二、定義和用法(page-break-before)
page-break-before 屬性設置元素前的 page-breaking 行爲。
儘管可以用 always 強制放上分頁符,但是無法保證避免分頁符的插入,創作人員最多隻能要求用戶代理儘可能避免插入分頁。
應用於:position 值爲 relative 或 static 的非浮動塊級元素。
註釋:請儘可能少地使用分頁屬性,並且避免在表格、浮動元素、帶有邊框的塊元素中使用分頁屬性。
可能的值
值 描述
auto 默認值。如果必要則在元素前插入分頁符。
always 在元素前插入分頁符。
avoid 避免在元素前插入分頁符。
left 在元素之前足夠的分頁符,一直到一張空白的左頁爲止。
right 在元素之前足夠的分頁符,一直到一張空白的右頁爲止。
inherit 規定應該從父元素繼承 page-break-before 屬性的設置。
參考: w3c page-break-before api
三、定義和用法(page-break-after)
page-break-after 屬性設置元素後的 page-breaking 行爲。
儘管可以用 always 強制放上分頁符,但是無法保證避免分頁符的插入,創作人員最多隻能要求用戶代理儘可能避免插入分頁。
應用於:position 值爲 relative 或 static 的非浮動塊級元素。
可能的值
值 描述
auto 默認。如果必要則在元素後插入分頁符。
always 在元素後插入分頁符。
avoid 避免在元素後插入分頁符。
left 在元素之後足夠的分頁符,一直到一張空白的左頁爲止。
right 在元素之後足夠的分頁符,一直到一張空白的右頁爲止。
inherit 規定應該從父元素繼承 page-break-after 屬性的設置。
註釋:請儘可能少地使用分頁屬性,並且避免在表格、浮動元素、帶有邊框的塊元素中使用分頁屬性。
參考:w3c page-break-after api
其他用法:
這個只是其中一種用法,可以搭配另外兩個屬性組合成各種效果(根據自己的效果搭配)。
一、page-break-before
想要實現讓h1獨佔一頁
代碼如下:
任何屬性都沒加
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<title>Document</title>
<style>
h1{
text-align: center;
}
</style>
</head>
<body>
<button onclick=func()>printthis page</button>
<h1>ttttt</h1>
<p>
5555555555555555555
</p>
</body>
<script>
function func() {
window.print();
}
</script>
</html>
解決方案:
(1)給h1加page-break-after: right;
<style>
h1{
text-align: center;
page-break-after: right;
}
</style>
(2)給p加 page-break-before: right;
<style>
h1{
text-align: center;
/* page-break-after: right; */
}
p{
page-break-before: right;
}
</style>
本文部分參api考於:css-page-break 屬性
vue和react中的插件
vue: vue-printjs
vue-printjs
https://codechina.csdn.net/mirrors/xyl66/vueplugs_printjs?utm_source=csdn_github_accelerator vue-print.js api地址當然github上也有隻是,訪問很慢 github print.js api
react:react-to-print
https://codechina.csdn.net/mirrors/gregnb/react-to-print?utm_source=csdn_github_accelerator react-to-print 地址 當然github上也有隻是,訪問很慢github react-to-print api
當然vue,react或者其他框架裏也可以事用上面的瀏覽器自帶的方案也行 ,請根據自己的需求擇優選擇。這些插件都事基於window.print封裝的,有些api還是很方便的。
動態調整打印機紙張大小
江蘇省崑山市地方稅務局
信息管理系統中經常要提供各種打印功能,例如報表打印、憑證打印以及發票打印。在這些打印過程中所需要紙張的大小往往是不一致的,例如,打印報表有可能使用A4 紙或A3 紙,打印憑證或發票可能需要將打印紙張設置成自定義大小。如果在同一臺打印機上打印這些內容,那麼就應該針對不同的打印內容設置不同的紙張尺寸。顯然如果用手動的方法來設置打印機的紙張尺寸是件很麻煩的事,最好的方法是讓程序動態地修改打印機的紙張尺寸。
解決問題的思路
通過查閱API 函數技術文檔可知,每個打印機都擁有唯一的一個叫做DevMode 的結構,與打印機相關的各項參數被存放在這個結構中。通過對DevMode 結構的分析,發現與設置打印機紙張大小有關的結構成員有四項:dmFields、dmPaperSize、dmPaperLength 以及dmPaperWidth。dmFields 是DevMode 的標誌位初始化部分,如果要修改結構中的某些成員,那麼dmFields 中相應位應被置位。dmPaperSize 表示打印機當前默認的打印紙張的大小,若要設置自定義紙張該項應爲0(注,上述解釋是根據微軟提供的技術文檔,但是在Delphi 中應將該成員設置成$100 即256)。dmPaperLength 和dmPaperWidth 只是在設置自定義大小紙張時使用,分別表示紙張的長度和寬度。如何對打印機的DevMode 結構進行修改呢?無非採用兩種方法,一種是利用Delphi 提供的TPrinter 類中的某些方法,還有一種是調用與打印有關的API 函數。下面就以Delphi 爲開發工具,以Epson 1600K 爲默認打印機,用兩種不同的方法來實現這一功能。
方法一:利用Delphi 的TPrinter 類
TPrinter 類是Delphi 對Windows 打印處理系統的封裝,它能夠幫助程序員在開發打印程序時儘可能地減少工作量。在程序中使用TPrinter,只要在單元的Use 子句後面添加Printers 即可。當前打印機的DevMode 結構的句柄可以通過調用Tprinter 類中的GetPrinter 方法來獲取。當程序獲得DevMode 結構的句柄後,就調用GlobalLock 函數來得到指向該結構的指針,隨後可對結構中的某些成員進行修改。下面就舉一個例子來說明這一問題:假設當前打印機的默認紙張尺寸是A3 紙,現在要打印長度爲114mm、寬度爲190mm 的紙張。爲了簡單起見,我們只在Form1 上放置一個Button1 按鈕,增加一個OnClick 事件,在Use 子句後添加Printers。程序的代碼如下:
Procedure TForm1.Button1Click(Sender: TObject);
var
Device : array[0..cchDeviceName -1] of Char;
Driver : array[0..(MAX_PATH -1)] of Char;
Port : array[0..32]of Char;
hDMode : THandle;
pDMode : PDevMode;
begin
Printer.GetPrinter(Device,Driver,Port,hDMode);
// 獲取打印機DevMode 結構的句柄值,
存放在hDMode 中
if hDMode < > 0 then begin
pDMode := GlobalLock(hDMode);
// 獲取指向打印機DevMode 結構的// 指針
if pDMode < > nil then begin
pDMode^.dmPaperSize := 256;
// 如果要將當前打印機紙張變爲自定義
dmPaperSize 必須設置成256
pDMode^.dmPaperLength := 1140;
pDMode^.dmPaperWidth := 1900;
pDMode^.dmFields := pDMode^.dmFields or
DM_PAPERSIZE;
pDMode^.dmFields :=
pDMode^.dmFields or DM_PAPERLENGTH;
pDMode^.dmFields :=
pDMode^.dmFields or DM_PAPERWIDTH;
{ 以上三條語句是對相應
的dmFields 成員進行置位。}
ResetDC(Printer.Handle,pDMode^);
// 設置打印機設備環境句柄的值
GlobalUnlock(hDMode);
end;
end;
{ 下面的代碼是爲了測試打印機是否
按190 *114 紙張大小來打印}
with Printer do begin
BeginDoc;
Canvas.TextOut(10,10,'Hello, My Friend!');
EndDoc;
end;
end;
方法二:利用有關打印的Windows API 函數
解決問題的思路和第一種方法類似,首先要獲取當前打印機的DevMode 結構的指針,然後再對該結構進行修改,從而修改打印機紙張大小。要完成上述功能,就得調用DocumentProperties 函數。利用該函數程序就可以獲取並修改與當前打印機相關的DevMode 結構中的成員。DocumentProperties 函數申明如下:
LONG DocumentProperties
(
HWND hWnd,
HANDLE hPrinter,
LPTSTR pDeviceName,
PDEVMODE pDevModeOutput,
PDEVMODE pDevModeInput,
DWORD fMode
);
六個參數中只有pDevModeOutput 是輸出變量,其餘五個參數必須由程序給出具體值。其中,hWnd 表徵當前窗口的句柄值;hPrinter 表示當前打印機的句柄;pDeviceName 是對打印機設備的描述;pDevModeOutput 是指向句柄值爲hPrinter 的打印機DevMode 結構的指針;pDevModeInput 是指向一個修改後的DevMode 結構的指針,該結構有待於被句柄值爲hPrinter 的打印機接受;fMode 定義了該函數的具體功能,如果取值DM_IN_BUFFER 那麼表示打印機接受由參數pDevModeInput 表示的由程序修改了的DevMode 值,如果取值DM_OUT_BUFFER 那麼程序可以通過參數pDevModeOutput 來獲取打印機的DevMode 值,如果fMode 爲零,則函數返回的值表示結構DevMode 所需的字節數。承接上述例子,現在將190 *114 大小的紙張設成A4 紙。再往Form1 上放置按鈕Button2,增加OnClick 事件,在Use 子句後面添加WinSpool。代碼如下:
Procedure TForm1.Button2Click(Sender: TObject);
var
PrnHd : THandle;
PrnInfo : PPrinterInfo1;
pcbNeeded : DWORD;
PDevModeBytes : DWORD;
DevMode: PDeviceMode;
PrnHdc : HDC;
DocInfo : PDocInfo;
begin
OpenPrinter('Epson LQ -1600K',PrnHd,nil);
// 獲得打印機句柄PrnHd
GetMem(PrnInfo,1024);
GetPrinter(PrnHd,1,PrnInfo,1024,@pcbNeeded);
PDevModeBytes:= DocumentProperties
( Handle,PrnHd,prninfo^.
pDescription,DevMode^,DevMode^,0 );
{ 獲取DevMode 結構所需的字節數}
GetMem(DevMode,PDevModeBytes);
// 給結構DevMode 分配空間
DocumentProperties( Handle,PrnHd,PrnInfo^.p
Description,DevMode^,DevMode^,DM_OUT_BUFFER );
// 獲取打印機的DevMode 結構
With DevMode^ do begin
dmPaperSize := DMPAPER_A4 ;
// 將紙張設置成A4 紙
dmFields := dmFields or DM_PAPERSIZE;
end;
DocumentProperties( Handle,PrnHd,PrnInfo^.p
Description,DevMode^,DevMode^,
DM_OUT_BUFFER or DM_IN_BUFFER);
// 修改DevMode 結構。
{ 下面的代碼是爲了測試打印機
是否按A4 紙大小來打印 }
PrnHdc := CreateDC
( nil, 'Epson LQ -1600K',nil,DevMode );
GetMem( DocInfo, 100 );
With DocInfo^ do begin
cbSize := sizeof(DocInfo);
lpszDocName := nil;
lpszOutput := nil;
lpszDatatype := nil;
fwType := DI_APPBANDING;
end;
StartDoc( PrnHdc, DocInfo^);
StartPage(PrnHdc);
TextOut( PrnHdc, 10, 10, 'Hello My Friend!',17);
EndPage(PrnHdc);
EndDoc(PrnHdc);
DeleteDC(PrnHdc);
FreeMem(DocInfo);
FreeMem(PrnInfo);
FreeMem(DevMode);
end;
至此,程序實現了本文開頭所提出的要求。需要指出的是,上述代碼是在程序運行時,動態地改變打印機紙張大小,而不改變打印機默認紙張大小。也就是說當打印程序運行結束後,打印機還是會按照默認打印紙張大小來打印、走紙。動態調整打印機紙張尺寸也是因打印機而異,某些打印機基本不支持自定義紙張,例如惠普的HP DeskJet 1120C 噴墨打印機以及衆多激光打印機。因此在這些打印機上,不能實現按任意紙張大小打印。對於一些針式打印機則沒有上述問題。
上述程序是在Windows 95 環境下,用Delphi 4.0 爲開發工具調試通過。
打印自定義紙張大小 長江支流說的辦法保留太多了,結果不行,很多類都是他在程序集裏自定義的,源碼又沒公開 不過還是要感謝他的提示 今天和小陳搞了一天,他在國外的論壇上看到了一篇文章得到了啓示,最後我們在凌晨3點終於把自定義紙張的代碼給寫出來了,看來必須用API,微軟的.NET對打印的支持太菜了 現公開我們工作室實現此功能的部分代碼 using System; using System.Text; using System.Runtime.InteropServices; using System.Security; using System.ComponentModel; using System.Drawing.Printing; namespace MCCustomPrintForm { /// <summary> /// 成都微創工作室(電子科技大學微創工作室) /// Tell 028-82853098 /// Email [email protected] , [email protected] /// 打印機紙張的真正自定義部分代碼 /// 2006-1-2 /// </summary> public class MCCustomPrintForm { // Make a static class private MCCustomPrintForm() { } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] internal struct structPrinterDefaults { [MarshalAs(UnmanagedType.LPTStr)] public String pDatatype; public IntPtr pDevMode; [MarshalAs(UnmanagedType.I4)] public int DesiredAccess; }; [DllImport("winspool.Drv", EntryPoint="OpenPrinter", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false,CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)] string printerName, out IntPtr phPrinter, ref structPrinterDefaults pd); [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false, CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool ClosePrinter(IntPtr phPrinter); [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] internal struct structSize { public Int32 width; public Int32 height; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] internal struct structRect { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; } [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] internal struct FormInfo1 { [FieldOffset(0), MarshalAs(UnmanagedType.I4)] public uint Flags; [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)] public String pName; [FieldOffset(8)] public structSize Size; [FieldOffset(16)] public structRect ImageableArea; }; [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi/* changed from CharSet=CharSet.Auto */)] internal struct structDevMode { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public String dmDeviceName; [MarshalAs(UnmanagedType.U2)] public short dmSpecVersion; [MarshalAs(UnmanagedType.U2)] public short dmDriverVersion; [MarshalAs(UnmanagedType.U2)] public short dmSize; [MarshalAs(UnmanagedType.U2)] public short dmDriverExtra; [MarshalAs(UnmanagedType.U4)] public int dmFields; [MarshalAs(UnmanagedType.I2)] public short dmOrientation; [MarshalAs(UnmanagedType.I2)] public short dmPaperSize; [MarshalAs(UnmanagedType.I2)] public short dmPaperLength; [MarshalAs(UnmanagedType.I2)] public short dmPaperWidth; [MarshalAs(UnmanagedType.I2)] public short dmScale; [MarshalAs(UnmanagedType.I2)] public short dmCopies; [MarshalAs(UnmanagedType.I2)] public short dmDefaultSource; [MarshalAs(UnmanagedType.I2)] public short dmPrintQuality; [MarshalAs(UnmanagedType.I2)] public short dmColor; [MarshalAs(UnmanagedType.I2)] public short dmDuplex; [MarshalAs(UnmanagedType.I2)] public short dmYResolution; [MarshalAs(UnmanagedType.I2)] public short dmTTOption; [MarshalAs(UnmanagedType.I2)] public short dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public String dmFormName; [MarshalAs(UnmanagedType.U2)] public short dmLogPixels; [MarshalAs(UnmanagedType.U4)] public int dmBitsPerPel; [MarshalAs(UnmanagedType.U4)] public int dmPelsWidth; [MarshalAs(UnmanagedType.U4)] public int dmPelsHeight; [MarshalAs(UnmanagedType.U4)] public int dmNup; [MarshalAs(UnmanagedType.U4)] public int dmDisplayFrequency; [MarshalAs(UnmanagedType.U4)] public int dmICMMethod; [MarshalAs(UnmanagedType.U4)] public int dmICMIntent; [MarshalAs(UnmanagedType.U4)] public int dmMediaType; [MarshalAs(UnmanagedType.U4)] public int dmDitherType; [MarshalAs(UnmanagedType.U4)] public int dmReserved1; [MarshalAs(UnmanagedType.U4)] public int dmReserved2; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] internal struct PRINTER_INFO_9 { public IntPtr pDevMode; } [DllImport("winspool.Drv", EntryPoint="AddFormW", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool AddForm( IntPtr phPrinter, [MarshalAs(UnmanagedType.I4)] int level, ref FormInfo1 form); /* This method is not used [DllImport("winspool.Drv", EntryPoint="SetForm", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool SetForm(IntPtr phPrinter, string paperName, [MarshalAs(UnmanagedType.I4)] int level, ref FormInfo1 form); */ [DllImport("winspool.Drv", EntryPoint="DeleteForm", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false,CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool DeleteForm( IntPtr phPrinter, [MarshalAs(UnmanagedType.LPTStr)] string pName); [DllImport("kernel32.dll", EntryPoint="GetLastError", SetLastError=false, ExactSpelling=true, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern Int32 GetLastError(); [DllImport("GDI32.dll", EntryPoint="CreateDC", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern IntPtr CreateDC([MarshalAs(UnmanagedType.LPTStr)] string pDrive, [MarshalAs(UnmanagedType.LPTStr)] string pName, [MarshalAs(UnmanagedType.LPTStr)] string pOutput, ref structDevMode pDevMode); [DllImport("GDI32.dll", EntryPoint="ResetDC", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern IntPtr ResetDC( IntPtr hDC, ref structDevMode pDevMode); [DllImport("GDI32.dll", EntryPoint="DeleteDC", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=false, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool DeleteDC(IntPtr hDC); [DllImport("winspool.Drv", EntryPoint="SetPrinterA", SetLastError=true, CharSet=CharSet.Auto, ExactSpelling=true, CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()] internal static extern bool SetPrinter( IntPtr hPrinter, [MarshalAs(UnmanagedType.I4)] int level, IntPtr pPrinter, [MarshalAs(UnmanagedType.I4)] int command); /* LONG DocumentProperties( HWND hWnd, // handle to parent window HANDLE hPrinter, // handle to printer object LPTSTR pDeviceName, // device name PDEVMODE pDevModeOutput, // modified device mode PDEVMODE pDevModeInput, // original device mode DWORD fMode // mode options ); */ [DllImport("winspool.Drv", EntryPoint="DocumentPropertiesA", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] public static extern int DocumentProperties( IntPtr hwnd, IntPtr hPrinter, [MarshalAs(UnmanagedType.LPStr)] string pDeviceName /* changed from String to string */, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode ); [DllImport("winspool.Drv", EntryPoint="GetPrinterA", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] public static extern bool GetPrinter( IntPtr hPrinter, int dwLevel /* changed type from Int32 */, IntPtr pPrinter, int dwBuf /* chagned from Int32*/, out int dwNeeded /* changed from Int32*/ ); // SendMessageTimeout tools [Flags] public enum SendMessageTimeoutFlags : uint { SMTO_NORMAL = 0x0000, SMTO_BLOCK = 0x0001, SMTO_ABORTIFHUNG = 0x0002, SMTO_NOTIMEOUTIFNOTHUNG = 0x0008 } const int WM_SETTINGCHANGE = 0x001A; const int HWND_BROADCAST = 0xffff; [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout( IntPtr windowHandle, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags flags, uint timeout, out IntPtr result ); //打印紙張長寬設置 public static void AddMC80MmPaperSizeToDefaultPrinter() { AddCustomPaperSizeToDefaultPrinter("MC 80mm * Receipt Length", 80.1f, 4003.9f); } public static void AddMC104MmPaperSizeToDefaultPrinter() { AddCustomPaperSizeToDefaultPrinter("MC 104mm * Receipt Length", 104.1f, 4003.9f); } /// <summary> /// Adds the printer form to the default printer /// </summary> /// <param name="paperName">Name of the printer form</param> /// <param name="widthMm">Width given in millimeters</param> /// <param name="heightMm">Height given in millimeters</param> public static void AddCustomPaperSizeToDefaultPrinter(string paperName, float widthMm, float heightMm) { PrintDocument pd = new PrintDocument(); string sPrinterName = pd.PrinterSettings.PrinterName; AddCustomPaperSize(sPrinterName, paperName, widthMm, heightMm); } /// <summary> /// Add the printer form to a printer /// </summary> /// <param name="printerName">The printer name</param> /// <param name="paperName">Name of the printer form</param> /// <param name="widthMm">Width given in millimeters</param> /// <param name="heightMm">Height given in millimeters</param> public static void AddCustomPaperSize(string printerName, string paperName, float widthMm, float heightMm) { if (PlatformID.Win32NT == Environment.OSVersion.Platform) { // The code to add a custom paper size is different for Windows NT then it is // for previous versions of windows const int PRINTER_ACCESS_USE = 0x00000008; const int PRINTER_ACCESS_ADMINISTER = 0x00000004; const int FORM_PRINTER = 0x00000002; structPrinterDefaults defaults = new structPrinterDefaults(); defaults.pDatatype = null; defaults.pDevMode = IntPtr.Zero; defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE; IntPtr hPrinter = IntPtr.Zero; // Open the printer. if (OpenPrinter(printerName, out hPrinter, ref defaults)) { try { // delete the form incase it already exists DeleteForm(hPrinter, paperName); // create and initialize the FORM_INFO_1 structure FormInfo1 formInfo = new FormInfo1(); formInfo.Flags = 0; formInfo.pName = paperName; // all sizes in 1000ths of millimeters formInfo.Size.width = (int)(widthMm * 1000.0); formInfo.Size.height = (int)(heightMm * 1000.0); formInfo.ImageableArea.left = 0; formInfo.ImageableArea.right = formInfo.Size.width; formInfo.ImageableArea.top = 0; formInfo.ImageableArea.bottom = formInfo.Size.height; if (!AddForm(hPrinter, 1, ref formInfo)) { StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendFormat("Failed to add the custom paper size {0} to the printer {1}, System error number: {2}", paperName, printerName, GetLastError()); throw new ApplicationException(strBuilder.ToString()); } // INIT const int DM_OUT_BUFFER = 2; const int DM_IN_BUFFER = 8; structDevMode devMode = new structDevMode(); IntPtr hPrinterInfo, hDummy; PRINTER_INFO_9 printerInfo; printerInfo.pDevMode = IntPtr.Zero; int iPrinterInfoSize, iDummyInt; // GET THE SIZE OF THE DEV_MODE BUFFER int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, printerName, IntPtr.Zero, IntPtr.Zero, 0); if(iDevModeSize < 0) throw new ApplicationException("Cannot get the size of the DEVMODE structure."); // ALLOCATE THE BUFFER IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100); // GET A POINTER TO THE DEV_MODE BUFFER int iRet = DocumentProperties(IntPtr.Zero, hPrinter, printerName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER); if(iRet < 0) throw new ApplicationException("Cannot get the DEVMODE structure."); // FILL THE DEV_MODE STRUCTURE devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType()); // SET THE FORM NAME FIELDS TO INDICATE THAT THIS FIELD WILL BE MODIFIED devMode.dmFields = 0x10000; // DM_FORMNAME // SET THE FORM NAME devMode.dmFormName = paperName; // PUT THE DEV_MODE STRUCTURE BACK INTO THE POINTER Marshal.StructureToPtr(devMode, hDevMode, true); // MERGE THE NEW CHAGES WITH THE OLD iRet = DocumentProperties(IntPtr.Zero, hPrinter, printerName, printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER); if(iRet < 0) throw new ApplicationException("Unable to set the orientation setting for this printer."); // GET THE PRINTER INFO SIZE GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize); if(iPrinterInfoSize == 0) throw new ApplicationException("GetPrinter failed. Couldn't get the # bytes needed for shared PRINTER_INFO_9 structure"); // ALLOCATE THE BUFFER hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100); // GET A POINTER TO THE PRINTER INFO BUFFER bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt); if(!bSuccess) throw new ApplicationException("GetPrinter failed. Couldn't get the shared PRINTER_INFO_9 structure"); // FILL THE PRINTER INFO STRUCTURE printerInfo = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType()); printerInfo.pDevMode = hDevMode; // GET A POINTER TO THE PRINTER INFO STRUCTURE Marshal.StructureToPtr(printerInfo, hPrinterInfo, true); // SET THE PRINTER SETTINGS bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0); if(!bSuccess) throw new Win32Exception(Marshal.GetLastWin32Error(), "SetPrinter() failed. Couldn't set the printer settings"); // Tell all open programs that this change occurred. SendMessageTimeout( new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero, MCCustomPrintForm.SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out hDummy); } finally { ClosePrinter(hPrinter); } } else { StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendFormat("Failed to open the {0} printer, System error number: {1}", printerName, GetLastError()); throw new ApplicationException(strBuilder.ToString()); } } else { structDevMode pDevMode = new structDevMode(); IntPtr hDC = CreateDC(null, printerName, null, ref pDevMode); if (hDC != IntPtr.Zero) { const long DM_PAPERSIZE = 0x00000002L; const long DM_PAPERLENGTH = 0x00000004L; const long DM_PAPERWIDTH = 0x00000008L; pDevMode.dmFields = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH); pDevMode.dmPaperSize = 256; pDevMode.dmPaperWidth = (short)(widthMm * 1000.0); pDevMode.dmPaperLength = (short)(heightMm * 1000.0); ResetDC(hDC, ref pDevMode); DeleteDC(hDC); } } } } }
C# PrintDocument打印 多頁 打印預覽
PrintDocument實例所有的訂閱事件如下:
1.創建一個PrintDocument的實例.如下:
System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument();
2.設置打印機開始打印的事件處理函數.函數原形如下:
void docToPrint_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
3.將事件處理函數添加到PrintDocument的PrintPage事件中。
docToPrint.PrintPage+=new PrintPageEventHandler(docToPrint_PrintPage);
4.設置PrintDocument的相關屬性,如:
PrintDialog1.AllowSomePages = true;PrintDialog1.ShowHelp = true;
5.把PrintDialog的Document屬性設爲上面配置好的PrintDocument的實例:
PrintDialog1.Document = docToPrint;
6.調用PrintDialog的ShowDialog函數顯示打印對話框:
DialogResult result = PrintDialog1.ShowDialog();
7.根據用戶的選擇,開始打印:
if (result==DialogResult.OK)
{
docToPrint.Print();
}
8.打印預覽控件PrintPreviewDialog
例子如下:
使用時先創建PrintService類的實例,然後調用void StartPrint(Stream streamToPrint,string streamType)函數開始打印。其中streamToPrint是要打印的內容(字節流),streamType是流的類型(txt表示普通文本,image表示圖像);
public
partial
class
PrintTxt
{
private
PrintPreviewDialog PrintPreview =
new
PrintPreviewDialog();
private
string
StreamType;
private
Image image =
null
;
private
Stream StreamToPrint =
null
;
Font mainFont =
new
Font(
"宋體"
, 12);
//打印的字體
public
string
Filename =
null
;
//1、實例化打印文檔
PrintDocument pdDocument =
new
PrintDocument();
private
string
[] lines;
private
int
linesPrinted;
public
PrintTxt(
string
filepath,
string
filetype)
{
Filename = Path.GetFileNameWithoutExtension(filepath);
//訂閱BeginPrint事件
pdDocument.BeginPrint +=
new
PrintEventHandler(pdDocument_BeginPrint);
//訂閱EndPrint事件,釋放資源
pdDocument.PrintPage +=
new
PrintPageEventHandler(OnPrintPage);
//訂閱Print打印事件,該方法必須放在訂閱打印事件的最後
FileStream fs =
new
FileStream(filepath, FileMode.Open, FileAccess.Read);
StartPrint(fs, filetype);
//打印結束
pdDocument.EndPrint +=
new
PrintEventHandler(pdDocument_EndPrint);
}
//2、啓動Print打印方法
public
void
StartPrint(Stream streamToPrint,
string
streamType)
{
//返回值的PageSettings A4\A5
PageSettings ps =
new
PageSettings();
//顯示設置打印頁對話框
PageSetupDialog Psdl =
new
PageSetupDialog();
//打印多份設置,注意,該方法需放在printpage方法後面。
PrintDialog pt =
new
PrintDialog();
pt.AllowCurrentPage =
true
;
pt.AllowSomePages =
true
;
pt.AllowPrintToFile =
true
;
StreamToPrint = streamToPrint;
//打印的字節流
StreamType = streamType;
//打印的類型
pdDocument.DocumentName = Filename;
//打印的文件名
Psdl.Document = pdDocument;
PrintPreview.Document = pdDocument;
pt.Document = pdDocument;
Psdl.PageSettings = pdDocument.DefaultPageSettings;
try
{
//顯示對話框
if
(Psdl.ShowDialog() == DialogResult.OK)
{
ps = Psdl.PageSettings;
pdDocument.DefaultPageSettings = Psdl.PageSettings;
}
if
(pt.ShowDialog() == DialogResult.OK)
{
pdDocument.PrinterSettings.Copies = pt.PrinterSettings.Copies;
pdDocument.Print();
}
if
(PrintPreview.ShowDialog()==DialogResult.OK )
//調用打印
pdDocument.Print();
* PrintDocument對象的Print()方法在PrintController類中執行PrintPage事件。
*/
}
catch
(InvalidPrinterException ex)
{
MessageBox.Show(ex.Message,
"Simple Editor"
, MessageBoxButtons.OK, MessageBoxIcon.Error);
throw
;
}
}
/// <summary>
/// 3、得到打印內容
/// 每個打印任務只調用OnBeginPrint()一次。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void
pdDocument_BeginPrint(
object
sender, PrintEventArgs e)
{
char
[] param = {
'\n'
};
char
[] trimParam = {
'\r'
};
//回車
switch
(StreamType)
{
case
"txt"
:
StringBuilder text =
new
StringBuilder();
System.IO.StreamReader streamReader =
new
StreamReader(StreamToPrint, Encoding.Default);
while
(streamReader.Peek() >= 0)
{
lines = streamReader.ReadToEnd().Split(param);
for
(
int
i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].TrimEnd(trimParam);
}
}
break
;
case
"image"
:
image = System.Drawing.Image.FromStream(StreamToPrint);
break
;
default
:
break
;
}
}
/// <summary>
/// 4、繪製多個打印界面
/// printDocument的PrintPage事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private
void
OnPrintPage(
object
sender, PrintPageEventArgs e)
{
int
leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);
//左邊距
int
topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3);
//頂邊距
switch
(StreamType)
{
case
"txt"
:
while
(linesPrinted < lines.Length)
{
//向畫布中填寫內容
e.Graphics.DrawString(lines[linesPrinted++],
new
Font(
"Arial"
, 10), Brushes.Black, leftMargin, topMargin,
new
StringFormat());
topMargin += 55;
//行高爲55,可調整
//走紙換頁
if
(topMargin >= e.PageBounds.Height - 60)
//頁面累加的高度大於頁面高度。根據自己需要,可以適當調整
{
//如果大於設定的高
e.HasMorePages =
true
;
/*
* PrintPageEventArgs類的HaeMorePages屬性爲True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
* PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
*/
return
;
}
}
break
;
case
"image"
:
//一下涉及剪切圖片,
int
width = image.Width;
int
height = image.Height;
if
((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect =
new
System.Drawing.Rectangle(topMargin, leftMargin, width, height);
//向畫布寫入圖片
for
(
int
i = 0; i < Convert.ToInt32(Math.Floor((
double
)image.Height/ 820)) + 1; i++)
{
e.Graphics.DrawImage(image, destRect, i*820,i*1170 , image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
//走紙換頁
if
(i * 1170 >= e.PageBounds.Height - 60)
//頁面累加的高度大於頁面高度。根據自己需要,可以適當調整
{
//如果大於設定的高
e.HasMorePages =
true
;
/*
* PrintPageEventArgs類的HaeMorePages屬性爲True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
* PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
*/
return
;
}
}
break
;
}
//打印完畢後,畫線條,且註明打印日期
e.Graphics.DrawLine(
new
Pen(Color.Black), leftMargin, topMargin, e.MarginBounds.Right, topMargin);
string
strdatetime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
e.Graphics.DrawString(
string
.Format(
"打印時間:{0}"
, strdatetime), mainFont, Brushes.Black, e.MarginBounds.Right-240, topMargin+40,
new
StringFormat());
linesPrinted = 0;
//繪製完成後,關閉多頁打印功能
e.HasMorePages =
false
;
}
/// <summary>
///5、EndPrint事件,釋放資源
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void
pdDocument_EndPrint(
object
sender, PrintEventArgs e)
{
//變量Lines佔用和引用的字符串數組,現在釋放
lines =
null
;
}
}
//PrintTxt simple = new PrintTxt("D:\\Mainsoft\\12.txt", "txt");
C#學習筆記之PrintDocument打印
秋憶夏傷
於 2016-05-30 15:26:56 發佈
8703
收藏 18
分類專欄: C#學習筆記
版權
C#學習筆記
專欄收錄該內容
54 篇文章0 訂閱
訂閱專欄
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PrintDocument控件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// PrintDocument:用於打印最重要的類,幾乎所有的打印類都與這個類有關係。
/// </summary>
// 1、打印頁面設置
private void btnSetting_Click(object sender, EventArgs e)
{
// 打印頁面設置對話框
PageSetupDialog page = new PageSetupDialog();
page.Document = printDocument1;
page.AllowMargins = true;
page.AllowOrientation = true;
page.AllowPaper = true;
page.AllowPrinter = true;
page.ShowHelp = true;
if (page.ShowDialog() == DialogResult.OK)
{
// 將設置好的打印頁 用作 PrintDocument進行打印。
printDocument1.DefaultPageSettings = page.PageSettings;
}
}
// 2、打印機設置
private void btnPrint_Click(object sender, EventArgs e)
{
// 打印機設置對話框
PrintDialog print = new PrintDialog();
print.Document = printDocument1;
print.AllowCurrentPage = true;
print.AllowPrintToFile = true;
print.AllowSelection = true;
print.AllowSomePages = true;
print.ShowHelp = true;
if (print.ShowDialog() == DialogResult.OK)
{
// 將設置好的打印機 用作 PrinDocument進行打印。
printDocument1.PrinterSettings = print.PrinterSettings;
}
}
// 3、打印預覽
private void btnPreview_Click(object sender, EventArgs e)
{
if (MessageBox.Show("是否要預覽打印文件?", "打印預覽", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
// 設置要預覽的文檔
printPreviewDialog1.Document = printDocument1;
// 開啓操作系統的抗鋸齒功能
printPreviewDialog1.UseAntiAlias = true;
// 打開預覽窗口
if (printPreviewDialog1.ShowDialog() == DialogResult.OK)
{
// 如果選擇的是系統默認打印機,點擊“打印”按鈕之後,會跳出“文件另存爲”窗口;
// 如果選擇別的打印機,點擊“打印”之後,會直接打印,不會返回“OK”。
MessageBox.Show("開始打印");
}
else
{
MessageBox.Show("關閉預覽");
}
}
}
// 4、開始打印
private void btnStart_Click(object sender, EventArgs e)
{
// PrintController:控制一個PrintDocument是如何打印的。
PrintController printController = new StandardPrintController();
printDocument1.PrintController = printController;
printDocument1.DocumentName = "社保樣卡";
printDocument1.PrinterSettings.PrinterName = "XID8600 U1";
printDocument1.Print(); // 觸發Print_Page事件。
}
// PrintDocument 三個事件中的第二個參數 e 有如下屬性:
// e.Cancel:設置爲true,將取消這次打印作業。
// e.Griphics:所使用打印機的設備環境。
// e.HasMorePages:PrintPage事件打印一頁後,如果仍有數據未打印,退出事件前設置
// HasMorePages=true;退出事件之後將再次出發PrintPage事件,打印下一頁。
// e.MarginBounds:打印區域的大小,是Rectangle結構,元素包括左上角座標(Left和Top),
// 寬和高(Width和Height),單位爲1/100英寸。
// e.PageSettings:PageSettings類對象,包含用對話框PageSetupDialog設置的頁面打印方式的
// 全部信息,
// 在調用 Print 方法後,在打印文檔的第一頁之前發生。
private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
}
// 需要打印新的一頁時發生,負責打印一頁所需要的數據
// 打印預覽會調用該事件,預覽的內容就是此處設置好的內容。
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Image iamge = Image.FromFile(@"D:\photo\test.jpg");
e.Graphics.DrawString("社保卡樣卡", new Font("黑體", 35), Brushes.Black, new Point(400, 120));
e.Graphics.DrawString("姓名 張三", new Font("黑體", 25), Brushes.Black, new Point(480, 270));
e.Graphics.DrawString("社會保障號碼 32032032302030230", new Font("黑體", 25), Brushes.Black, new Point(480, 360));
e.Graphics.DrawString("社會保障卡號 JS2018098", new Font("黑體", 25), Brushes.Black, new Point(480, 450));
e.Graphics.DrawString("制卡日期 2016年5月", new Font("黑體", 25), Brushes.Black, new Point(480, 540));
e.Graphics.DrawImage(iamge, new Point(100, 240));
}
// 在打印完最後一頁文檔時發生。
private void printDocument1_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
}
/// <summary>
/// 打印機狀態值
/// </summary>
public enum PrinterStatus
{
其他狀態 = 1,
未知,
空閒,
正在打印,
預熱,
停止打印,
打印中,
離線
}
// 獲取指定打印機的狀態
private void btnState_Click(object sender, EventArgs e)
{
string strPrinter = "win32_printer.DeviceId='XID8300 U1'";
// 用指定的打印機實例化一個打印機對象。
ManagementObject printer = new ManagementObject(strPrinter);
// 獲取打印機信息。
printer.Get();
// 獲取打印機狀態屬性
string str = printer.Properties["PrinterStatus"].Value.ToString();
textBox1.Text = str;
}
// 獲取本地所有打印機信息
private void button1_Click(object sender, EventArgs e)
{
string strPrinter = "win32_printer";
// 獲取本地所有打印機
ManagementClass mc = new ManagementClass(strPrinter);
// 獲取所有打印機實例的集合
ManagementObjectCollection moc = mc.GetInstances();
// 遍歷本地所有打印機
foreach (ManagementObject printer in moc)
{
// 打印機名字
string strName = printer.Properties["DeviceId"].Value.ToString();
// 打印機狀態
string strState = printer.Properties["PrinterStatus"].Value.ToString();
comboBox1.Items.Add(strName);
}
}
}
}
秋憶夏傷
關注
————————————————
版權聲明:本文爲CSDN博主「秋憶夏傷」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_29331365/article/details/51538369