### Get Printer Status with cURL Source: https://context7.com/shenluwei/py-webprinter/llms.txt Retrieves information about all available printers on the system, including their name, description, location, and capabilities. This endpoint is useful for understanding the printing environment and available devices. ```bash curl -X POST http://127.0.0.1:5100/printer_status \ -H "Content-Type: application/json" ``` -------------------------------- ### Get Print Task Status with cURL Source: https://context7.com/shenluwei/py-webprinter/llms.txt Retrieves the status of all print tasks, including active, completed, and pending jobs. This API is crucial for monitoring the progress and outcome of print requests sent to the DplusPrinter service. ```bash curl -X POST http://127.0.0.1:5100/print_tasks \ -H "Content-Type: application/json" ``` -------------------------------- ### Manage Auto Startup for Applications Source: https://context7.com/shenluwei/py-webprinter/llms.txt Enables or disables automatic application startup on system boot for Windows and macOS. This function configures system startup settings, requiring appropriate administrative privileges on Windows and potentially user confirmation on macOS. ```python import platform import sys import os def set_startup(enable): if platform.system() == "Windows": import winreg key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, winreg.KEY_SET_VALUE ) if enable: winreg.SetValueEx(key, "DplusPrinter", 0, winreg.REG_SZ, sys.executable) else: try: winreg.DeleteValue(key, "DplusPrinter") except FileNotFoundError: pass winreg.CloseKey(key) elif platform.system() == "Darwin": import plistlib import subprocess agent_path = os.path.expanduser('~/Library/LaunchAgents/cn.dianplus.DpulsPrinter.plist') if enable: agent_dict = { 'Label': 'cn.dianplus.DpulsPrinter', 'ProgramArguments': ['/Applications/DpulsPrinter.app/Contents/MacOS/DpulsPrinter'], 'RunAtLoad': True } with open(agent_path, 'wb') as f: plistlib.dump(agent_dict, f) subprocess.run(['launchctl', 'load', agent_path]) else: subprocess.run(['launchctl', 'unload', agent_path]) if os.path.exists(agent_path): os.remove(agent_path) ``` -------------------------------- ### Render HTML and Print Document (Python) Source: https://context7.com/shenluwei/py-webprinter/llms.txt Renders provided HTML content using QWebEngineView and prints it to a QPrinter object. It involves creating a QWebEngineView, setting its HTML content, and then initiating the print job. Dependencies include PyQt6 libraries. It takes a QPrinter object and HTML string as input. ```python from PyQt6.QtWebEngineWidgets import QWebEngineView from PyQt6.QtPrintSupport import QPrinter from PyQt6.QtCore import QEventLoop def printDocument(self, printer, html): webView = QWebEngineView() webView.setFixedWidth(1) webView.setFixedHeight(1) webView.setHtml(html) self.mainLayout.addWidget(webView) loop = QEventLoop() def onWebViewLoadFinished(success): if success: webView.printFinished.connect(loop.quit) webView.print(printer) else: loop.quit() webView.loadFinished.connect(lambda success: onWebViewLoadFinished(success)) loop.exec() self.mainLayout.removeWidget(webView) webView.deleteLater() ``` -------------------------------- ### Configure QPrinter Object (Python) Source: https://context7.com/shenluwei/py-webprinter/llms.txt Prepares and configures a QPrinter object with specified printing options such as page size, margins, orientation, copy count, resolution, and duplex mode. It allows for customization of various printer settings. Dependencies include PyQt6 libraries. It takes a task key and a dictionary of options as input and returns a configured QPrinter object. ```python from PyQt6.QtPrintSupport import QPrinter from PyQt6.QtGui import QPageLayout, QPageSize from PyQt6.QtCore import QSizeF, QMarginsF def prepareQPrinter(self, taskKey, options): printer = QPrinter(QPrinter.PrinterMode.HighResolution) # Set printer name if options.get('printerName'): printer.setPrinterName(options['printerName']) # Set page size (A4 default) pageRect = options.get('pageRect', {}) width = pageRect.get('width', 210) height = pageRect.get('height', 297) pageSize = QPageSize(QSizeF(width, height), QPageSize.Unit.Millimeter) printer.setPageSize(pageSize) # Set margins margins = options.get('margins', {}) pageMargin = QMarginsF( margins.get('left', 0), margins.get('top', 0), margins.get('right', 0), margins.get('bottom', 0) ) printer.setPageMargins(pageMargin, QPageLayout.Unit.Millimeter) # Set orientation orientation = options.get('orientation', 'portrait') if orientation == 'landscape': printer.setPageOrientation(QPageLayout.Orientation.Landscape) else: printer.setPageOrientation(QPageLayout.Orientation.Portrait) # Set copy count printer.setCopyCount(options.get('printCount', 1)) # Set resolution (default 300 DPI) printer.setResolution(options.get('resolution', 300)) # Set duplex mode duplex = options.get('duplex') if duplex == 'long': printer.setDuplex(QPrinter.DuplexMode.DuplexLongSide) elif duplex == 'short': printer.setDuplex(QPrinter.DuplexMode.DuplexShortSide) elif duplex == 'auto': printer.setDuplex(QPrinter.DuplexMode.DuplexAuto) # Set color mode colorMode = options.get('colorMode', 'grayScale') if colorMode == 'color': printer.setColorMode(QPrinter.ColorMode.Color) else: printer.setColorMode(QPrinter.ColorMode.GrayScale) return printer ``` -------------------------------- ### POST /preview Source: https://context7.com/shenluwei/py-webprinter/llms.txt Generates a print preview for the given HTML content. This endpoint allows users to visualize how the content will be printed, with options to adjust settings before committing to a print job. ```APIDOC ## POST /preview ### Description Opens a print preview dialog displaying how the HTML content will appear when printed, with options to adjust settings. ### Method POST ### Endpoint /preview ### Parameters #### Query Parameters None #### Request Body - **taskKey** (string) - Required - A unique identifier for the preview task. - **content** (string) - Required - The HTML content to preview, URL-encoded. - **options** (object) - Optional - Preview configuration options. - **pageRect** (object) - Optional - Defines the page dimensions. - **width** (number) - Page width in millimeters. - **height** (number) - Page height in millimeters. - **margins** (object) - Optional - Page margins in millimeters. - **left** (number) - Left margin. - **top** (number) - Top margin. - **right** (number) - Right margin. - **bottom** (number) - Bottom margin. - **orientation** (string) - Optional - Page orientation ("portrait" or "landscape"). ### Request Example ```javascript $.ajax({ url: 'http://127.0.0.1:5100/preview', type: 'POST', contentType: 'application/json', data: JSON.stringify({ taskKey: new Date().getTime(), content: encodeURIComponent(`

Sales Report

ProductQuantityPrice
Widget A10$50.00
Widget B5$75.00
`), options: { pageRect: { width: 200, height: 80 }, margins: { left: 10, top: 10, right: 10, bottom: 10 }, orientation: "landscape" } }), success: function(data) { console.log('Preview opened successfully'); } }); ``` ### Response #### Success Response (200) Typically returns a success message or status indicating the preview dialog has been opened. The exact response structure may vary. #### Response Example ```json { "success": true, "message": "Print preview opened successfully." } ``` ``` -------------------------------- ### POST /print Source: https://context7.com/shenluwei/py-webprinter/llms.txt Initiates a print job for the provided HTML content. This endpoint opens a print dialog, allowing the user to select a printer and configure print settings before the job is sent. ```APIDOC ## POST /print ### Description Opens a print dialog allowing users to select printer and configure settings before printing HTML content. ### Method POST ### Endpoint /print ### Parameters #### Query Parameters None #### Request Body - **taskKey** (string) - Required - A unique identifier for the print task. - **content** (string) - Required - The HTML content to be printed, URL-encoded. - **options** (object) - Optional - Print job configuration options. - **printerName** (string) - Optional - The name of the printer to use. - **pageRect** (object) - Optional - Defines the page dimensions. - **width** (number) - Page width in millimeters. - **height** (number) - Page height in millimeters. - **margins** (object) - Optional - Page margins in millimeters. - **left** (number) - Left margin. - **top** (number) - Top margin. - **right** (number) - Right margin. - **bottom** (number) - Bottom margin. - **printCount** (number) - Optional - The number of copies to print. - **orientation** (string) - Optional - Page orientation ("portrait" or "landscape"). - **duplex** (string) - Optional - Duplex printing mode ("long" or "short"). - **colorMode** (string) - Optional - Color mode ("color" or "grayScale"). - **pageScopes** (object) - Optional - Specifies the range of pages to print. - **from** (number) - Starting page number. - **to** (number) - Ending page number. ### Request Example ```javascript $.ajax({ url: 'http://127.0.0.1:5100/print', type: 'POST', contentType: 'application/json', data: JSON.stringify({ taskKey: new Date().getTime(), content: encodeURIComponent('

Invoice #12345

Total: $150.00

'), options: { printerName: "HP_LaserJet_400_M401dne", pageRect: { width: 210, // A4 width in mm height: 297 // A4 height in mm }, margins: { left: 10, top: 10, right: 10, bottom: 10 }, printCount: 2, orientation: "portrait", duplex: "long", colorMode: "grayScale", pageScopes: { from: 1, to: 1 } } }), success: function(data) { console.log('Print request sent successfully'); }, error: function(xhr, status, error) { console.error('Print failed:', error); } }); ``` ### Response #### Success Response (200) Typically returns a success message or status indicating the print job was submitted. The exact response structure may vary. #### Response Example ```json { "success": true, "message": "Print job submitted successfully to dialog." } ``` ``` -------------------------------- ### Python Core Functions Source: https://context7.com/shenluwei/py-webprinter/llms.txt Details on the core Python functions used for rendering and preparing print jobs. ```APIDOC ## Python Core Functions ### printDocument Function #### Description Renders HTML content using QWebEngineView and sends it to the configured printer. #### Parameters - **printer** (QPrinter) - The configured QPrinter object. - **html** (string) - The HTML content to render and print. ### prepareQPrinter Function #### Description Configures a QPrinter object with custom page size, margins, orientation, and other printing options. #### Parameters - **taskKey** (string) - A unique identifier for the print task (used internally, not directly in QPrinter configuration). - **options** (object) - A dictionary containing printing options: - **printerName** (string) - Optional - The name of the printer to use. - **pageRect** (object) - Optional - The dimensions of the page in millimeters. - **width** (number) - Optional - Page width (default 210). - **height** (number) - Optional - Page height (default 297). - **margins** (object) - Optional - Page margins in millimeters. - **left** (number) - Optional - Left margin (default 0). - **top** (number) - Optional - Top margin (default 0). - **right** (number) - Optional - Right margin (default 0). - **bottom** (number) - Optional - Bottom margin (default 0). - **orientation** (string) - Optional - Page orientation ('portrait' or 'landscape', default 'portrait'). - **printCount** (integer) - Optional - Number of copies to print (default 1). - **resolution** (integer) - Optional - Printer resolution in DPI (default 300). - **duplex** (string) - Optional - Duplex printing mode ('long', 'short', 'auto'). - **colorMode** (string) - Optional - Color mode ('color' or 'grayScale', default 'grayScale'). #### Returns - **QPrinter** - A configured QPrinter object. ``` -------------------------------- ### Manage SSL Certificates for HTTPS Source: https://context7.com/shenluwei/py-webprinter/llms.txt Automatically downloads and monitors SSL certificates for HTTPS support, updating them when changes are detected. This function relies on external services and local file storage, and may require disabling SSL verification for certain requests. ```python import tempfile import requests def downloadFileToTempfile(url): with tempfile.NamedTemporaryFile(delete=False, mode='wb') as temp_file: response = requests.get(url, stream=True, verify=False) if response.status_code == 200: for chunk in response.iter_content(chunk_size=8192): temp_file.write(chunk) return temp_file.name else: raise Exception(f"Failed to download file. Status code: {response.status_code}") def isCertFileChanged(): try: httpKeyPath = 'https://file.dianplus.cn/ssl/localhost.dianjia.io.key' httpCertPath = 'https://file.dianplus.cn/ssl/localhost.dianjia.io.pem' keyContent = requests.get(httpKeyPath, verify=False).text certContent = requests.get(httpCertPath, verify=False).text # Compare with cached versions if certFileCaches.get(httpKeyPath) != keyContent or \ certFileCaches.get(httpCertPath) != certContent: # Update local certificate files with open(key_temp_path, 'w') as f: f.write(keyContent) with open(cert_temp_path, 'w') as f: f.write(certContent) return True return False except Exception as e: print(f"Certificate check failed: {e}") return False ``` -------------------------------- ### POST /direct_print Source: https://context7.com/shenluwei/py-webprinter/llms.txt Sends HTML content directly to the printer without showing any dialog, using specified configuration. ```APIDOC ## POST /direct_print ### Description Sends HTML content directly to the printer without showing any dialog, using specified configuration. ### Method POST ### Endpoint /direct_print ### Parameters #### Request Body - **taskKey** (string) - Required - A unique identifier for the print task. - **content** (string) - Required - The HTML content to be printed, URI-encoded. - **options** (object) - Optional - Configuration options for the printer. - **printerName** (string) - Optional - The name of the printer to use. - **pageRect** (object) - Optional - The dimensions of the page. - **width** (number) - Optional - The width of the page in millimeters (default 210). - **height** (number) - Optional - The height of the page in millimeters (default 297). - **margins** (object) - Optional - The margins for the page. - **left** (number) - Optional - Left margin in millimeters (default 0). - **top** (number) - Optional - Top margin in millimeters (default 0). - **right** (number) - Optional - Right margin in millimeters (default 0). - **bottom** (number) - Optional - Bottom margin in millimeters (default 0). - **orientation** (string) - Optional - Page orientation ('portrait' or 'landscape', default 'portrait'). - **printCount** (integer) - Optional - Number of copies to print (default 1). - **resolution** (integer) - Optional - Printer resolution in DPI (default 300). - **duplex** (string) - Optional - Duplex printing mode ('long', 'short', 'auto'). - **colorMode** (string) - Optional - Color mode ('color' or 'grayScale', default 'grayScale'). ### Request Example ```json { "taskKey": "receipt-1678886400000", "content": "IyI8ZGl2IHN0eWxlPVwid2lkdGg6ODBtbTsgZm9udC1zaXplOjFweFwiPjxoMj4gU3RvcmUgUmVjZWlwdDwvaDI+PHAgRGF0ZT48L3A+PHAgSXRlbT4gQ29mZmVlIC0gJDMuNTA8L3A+PHAgSXRlbT4gU2FuZHdpY2ggLS ...", "options": { "printerName": "Thermal_Receipt_Printer", "pageRect": { "width": 80, "height": 200 }, "margins": { "left": 5, "top": 5, "right": 5, "bottom": 5 }, "orientation": "portrait" } } ``` ### Response #### Success Response (200) Indicates that the print job was successfully submitted. The response body may be empty or contain a success message. #### Response Example ```json { "message": "Print job submitted successfully" } ``` ### Error Handling - **400 Bad Request**: Invalid request payload or missing required fields. - **500 Internal Server Error**: Printer is not available or an internal error occurred. ``` -------------------------------- ### Request Print Preview with JavaScript (jQuery) Source: https://context7.com/shenluwei/py-webprinter/llms.txt Requests a print preview of HTML content from the DplusPrinter service, allowing users to visualize the output before actual printing. It supports specifying page dimensions, margins, and orientation. Requires jQuery for AJAX requests. ```javascript $.ajax({ url: 'http://127.0.0.1:5100/preview', type: 'POST', contentType: 'application/json', data: JSON.stringify({ taskKey: new Date().getTime(), content: encodeURIComponent(`

Sales Report

ProductQuantityPrice
Widget A10$50.00
Widget B5$75.00
`), options: { pageRect: { width: 200, height: 80 }, margins: { left: 10, top: 10, right: 10, bottom: 10 }, orientation: "landscape" } }), success: function(data) { console.log('Preview opened successfully'); } }); ``` -------------------------------- ### Initiate Print Job with JavaScript (jQuery) Source: https://context7.com/shenluwei/py-webprinter/llms.txt Sends an HTML content to the DplusPrinter service for printing, optionally opening a print dialog for user configuration. It allows specifying printer name, page dimensions, margins, print count, orientation, duplex mode, color settings, and page scopes. Requires jQuery for AJAX requests. ```javascript $.ajax({ url: 'http://127.0.0.1:5100/print', type: 'POST', contentType: 'application/json', data: JSON.stringify({ taskKey: new Date().getTime(), content: encodeURIComponent('

Invoice #12345

Total: $150.00

'), options: { printerName: "HP_LaserJet_400_M401dne", pageRect: { width: 210, // A4 width in mm height: 297 // A4 height in mm }, margins: { left: 10, top: 10, right: 10, bottom: 10 }, printCount: 2, orientation: "portrait", duplex: "long", colorMode: "grayScale", pageScopes: { from: 1, to: 1 } } }), success: function(data) { console.log('Print request sent successfully'); }, error: function(xhr, status, error) { console.error('Print failed:', error); } }); ``` -------------------------------- ### POST /printer_status Source: https://context7.com/shenluwei/py-webprinter/llms.txt Retrieves information about all available printers on the system, including their names, descriptions, locations, and capabilities. This endpoint helps in understanding the printing environment. ```APIDOC ## POST /printer_status ### Description Retrieves information about all available printers on the system including name, description, location, and capabilities. ### Method POST ### Endpoint /printer_status ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://127.0.0.1:5100/printer_status \ -H "Content-Type: application/json" ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **printerInfos** (array) - A list of printer information objects. - **name** (string) - The name of the printer. - **description** (string) - A description of the printer. - **location** (string) - The physical location of the printer. - **is_default** (boolean) - Whether this is the default printer. - **is_remote** (boolean) - Whether the printer is remote. - **supported_resolutions** (array) - A list of supported printer resolutions. #### Response Example ```json { "success": true, "printerInfos": [ { "name": "HP_LaserJet_400_M401dne", "description": "HP LaserJet 400", "location": "Office", "is_default": true, "is_remote": false, "supported_resolutions": [[300, 600, 1200]] } ] } ``` ``` -------------------------------- ### Direct HTML Print to Printer (JavaScript) Source: https://context7.com/shenluwei/py-webprinter/llms.txt Sends HTML content directly to a specified printer without displaying a print dialog. It utilizes an AJAX POST request to a local server endpoint ('/direct_print') with the HTML content and print options. Dependencies include jQuery for AJAX requests. It takes HTML content and printer configuration options as input. ```javascript $.ajax({ url: 'http://127.0.0.1:5100/direct_print', type: 'POST', contentType: 'application/json', data: JSON.stringify({ taskKey: 'receipt-' + new Date().getTime(), content: encodeURIComponent( `

Store Receipt

Date: ${new Date().toLocaleDateString()}

Item: Coffee - $3.50

Item: Sandwich - $6.00


Total: $9.50

Thank you!

` ), options: { printerName: "Thermal_Receipt_Printer", pageRect: { width: 80, height: 200 }, margins: { left: 5, top: 5, right: 5, bottom: 5 }, orientation: "portrait" } }), success: function(data) { console.log('Direct print submitted'); }, error: function(xhr, status, error) { console.error('Print error:', error); } }); ``` -------------------------------- ### POST /print_tasks Source: https://context7.com/shenluwei/py-webprinter/llms.txt Retrieves the status of all print tasks, including active, completed, and pending jobs. This endpoint is useful for monitoring the print queue and job progress. ```APIDOC ## POST /print_tasks ### Description Retrieves the status of all print tasks including active, completed, and pending jobs. ### Method POST ### Endpoint /print_tasks ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://127.0.0.1:5100/print_tasks \ -H "Content-Type: application/json" ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **printTasks** (array) - A list of print task objects. - **taskKey** (string) - A unique identifier for the print task. - **status** (string) - The current status of the print task (e.g., "success", "pending", "failed"). - **active** (boolean) - Whether the print task is currently active. - **printer** (string) - The name of the printer assigned to this task. #### Response Example ```json { "success": true, "printTasks": [ { "taskKey": "1234567890", "status": "success", "active": true, "printer": "HP_LaserJet_400_M401dne" } ] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.