首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C++Builder 獲取印表機參數完全指南:解析度、紙張尺寸、可列印區域

     編輯:VC 教學

核心 API:GetDeviceCaps

所有印表機物理參數均透過 GetDeviceCaps(Printer->Handle, nIndex) 取得,Printer 為 VCL TPrinter 實例。

1. 印表機解析度(DPI)

int dpiX = GetDeviceCaps(Printer->Handle, LOGPIXELSX); // 水平 DPI
int dpiY = GetDeviceCaps(Printer->Handle, LOGPIXELSY); // 垂直 DPI

典型值:600, 1200, 2400 DPI。注意:部分印表機水平/垂直 DPI 不同。

2. 紙張像素尺寸

屬性VCL 屬性API 常數說明
可列印寬度Printer->PageWidthHORZRES扣除邊界後可用像素
可列印高度Printer->PageHeightVERTRES扣除邊界後可用像素
物理寬度—PHYSICALWIDTH含不可列印邊界的完整像素
物理高度—PHYSICALHEIGHT含不可列印邊界的完整像素
物理左邊距—PHYSICALOFFSETX從物理左緣到可列印區左緣的像素
物理上邊距—PHYSICALOFFSETY從物理上緣到可列印區上緣的像素

3. 實際紙張尺寸(英吋/公釐)

double paperWidthInch  = (double)GetDeviceCaps(Printer->Handle, PHYSICALWIDTH)  / dpiX;
double paperHeightInch = (double)GetDeviceCaps(Printer->Handle, PHYSICALHEIGHT) / dpiY;

double paperWidthCm  = paperWidthInch  * 2.54;
double paperHeightCm = paperHeightInch * 2.54;

4. 邊界與可列印區關係圖解

物理寬度 (PHYSICALWIDTH)
│◄──────────────────────►│
├────────┬──────────────┬┤
│ 左邊距 │  可列印區    │右邊距
│OFFSETX │ PageWidth    │
└────────┴──────────────┘

5. 實戰應用:精準列印佈局

void __fastcall TForm1::PrintLayout()
{
    Printer()->BeginDoc();
    try {
        int dpiX = GetDeviceCaps(Printer()->Handle, LOGPIXELSX);
        int dpiY = GetDeviceCaps(Printer()->Handle, LOGPIXELSY);
        int physW = GetDeviceCaps(Printer()->Handle, PHYSICALWIDTH);
        int physH = GetDeviceCaps(Printer()->Handle, PHYSICALHEIGHT);
        int offsetX = GetDeviceCaps(Printer()->Handle, PHYSICALOFFSETX);
        int offsetY = GetDeviceCaps(Printer()->Handle, PHYSICALOFFSETY);

        // 1. 計算可列印區域(像素)
        TRect printRect;
        printRect.left   = offsetX;
        printRect.top    = offsetY;
        printRect.right  = physW - (GetDeviceCaps(Printer()->Handle, PHYSICALWIDTH) - Printer()->PageWidth - offsetX);
        printRect.bottom = physH - (GetDeviceCaps(Printer()->Handle, PHYSICALHEIGHT) - Printer()->PageHeight - offsetY);

        // 2. 轉換為 mm 方便佈局
        double mmPerPxX = 25.4 / dpiX;
        double mmPerPxY = 25.4 / dpiY;

        // 3. 繪製邊框測試
        Printer()->Canvas->Rectangle(printRect);

        // 4. 文字輸出(以 mm 定位)
        Printer()->Canvas->TextOut(
            (int)(20 / mmPerPxX),  // 20mm from left
            (int)(10 / mmPerPxY),  // 10mm from top
            "精準列印測試");

    }
    __finally { Printer()->EndDoc(); }
}

常見陷阱與對策

  • PageWidth/PageHeight 為 0: 確保 Printer()->BeginDoc() 後再讀取。
  • DPI 不對稱: 一律分別讀取 X/Y,勿假設相等。
  • 多重紙匣: Printer()->PrinterIndex 切換印表機時,參數會隨之變更,需重新查詢。
  • 虛擬印表機 (PDF): 參數同理適用,但 PHYSICALOFFSET 可能為 0。

印表機物理與邏輯尺寸關係圖

精通 GetDeviceCaps 各項指標,是實現「所見即所得」高品質列印的關鍵基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved