医疗终端札记

news/2024/7/8 4:06:47 标签: print

在这里插入图片描述


文章目录

  • 一、打印
    • 1、Windows 下打印 PDF
    • 2、通过 com 打印 Word、Excel
      • Python
      • Java
      • Go
      • Qt
    • 3、打印普通文件
    • 4、Windows 打印 API
    • 5、打印信息
  • 二、Windows API


一、打印

1、Windows 下打印 PDF

从 Windows 命令行打印 PDF

AcroRd32.exe /t "C:\Path\To\Your\File.pdf" "PrinterName"
# 其中,“C:\Path\To\Your\File.pdf”是您要打印的PDF文件的完整路径,“PrinterName”是您要使用的打印机的名称。
# 这将启动Acrobat Reader并自动将指定的PDF文件发送到打印机进行打印。请注意,“/t”选项将Acrobat Reader设置为“传统打印模式”,这意味着直接将文件发送到打印机而不会打开Acrobat Reader界面。

用Python实现PDF自动打印至打印机
PDFtoPrinter: Command-line PDF printing

# To print a PDF file to the default Windows printer, use this command:
PDFtoPrinter filename.pdf

# To print to a specific printer, add the name of the printer in quotation marks:
PDFtoPrinter filename.pdf "Name of Printer"

# If you want to print to a network printer, use the name that appears in Windows print 
# dialogs, like this (and be careful to note the two backslashes at the start of the name and
# the single backslash after the servername):
PDFtoPrinter filename.pdf "\\SERVER\PrinterName"

2、通过 com 打印 Word、Excel

Python

Python:通过Win32模块操作Office对象之打印
Python pywin32实现word和Excel的处理
Python的Pywin32库:简化Windows编程的强大工具

pip install pywin32
def print_word():
    from win32com.client.gencache import EnsureDispatch
    from win32com.client import constants

    Word = EnsureDispatch("Word.Application")  # 连接/创建Word对象(打开Word程序)
    f = r"z:\123.docx"

    doc = Word.Documents.Open(f)  # 打开Word文档
    doc.PrintOut()  # 打印(到默认打印机);如果默认打印机为虚拟打印机,则会弹出保存文件对话框(需要选择保存文件的格式和路径)
    doc.Close(constants.wdDoNotSaveChanges)  # (不保存)关闭Word文档

    Word.Quit()  # 退出Word程序


def print_execl():
    from win32com.client.gencache import EnsureDispatch
    from win32com.client import constants

    Excel = EnsureDispatch("Excel.Application")  # 打开Excel程序
    f = r"z:\34.xlsx"

    wb = Excel.Workbooks.Open(f)  # 打开Excel工作簿
    sht = wb.Sheets("Sheet1")  # 指定工作表
    sht.PrintOut()  # 打印工作表
    wb.Close(constants.xlDoNotSaveChanges)  # (不保存)关闭工作簿

    Excel.Quit()  # 退出Excel程序

def word_to_pdf():
    from win32com import client as wc

    pythoncom.CoInitialize()
    file_path = 'Z:/123.docx'
    try:
        word = wc.gencache.EnsureDispatch('word.application')
    except:
        try:
            word = wc.gencache.EnsureDispatch('kwps.application')  # 如果使用wps
        except:
            word = wc.gencache.EnsureDispatch('wps.application')  # 如果使用wps
    newpdf = word.Documents.Open(file_path)
    word.Visible = 0
    newpdf.SaveAs(f'Z:/123.pdf', FileFormat=17)
    newpdf.Close()
    pythoncom.CoUninitialize()

def execl_to_pdf():
    from win32com import client as wc

    try:
        excel = wc.DispatchEx('Excel.Application')
    except:
        try:
            excel = wc.DispatchEx('ket.Application')
        except:
            excel = wc.DispatchEx('et.Application')
    newpdf = excel.Workbooks.Open(r'Z:\34.xlsx')
    excel.DisplayAlerts = 0
    # 获取第一个sheet
    all_sheets = [sheet.Name for sheet in newpdf.Sheets]
    ws_source = newpdf.Worksheets(all_sheets[0])
    # 设置页面设置
    ws_source.PageSetup.LeftHeader = ""
    ws_source.PageSetup.CenterHeader = ""
    ws_source.PageSetup.RightHeader = ""
    ws_source.PageSetup.LeftFooter = ""
    ws_source.PageSetup.CenterFooter = ""
    ws_source.PageSetup.RightFooter = ""
    # ws_source.PageSetup.FitToPagesTall = 0
    ws_source.PageSetup.FirstPageNumber = True
    ws_source.PageSetup.LeftMargin = 0
    ws_source.PageSetup.RightMargin = 0
    ws_source.PageSetup.TopMargin = 0
    ws_source.PageSetup.BottomMargin = 0
    ws_source.PageSetup.HeaderMargin = 0
    ws_source.PageSetup.FooterMargin = 0
    # ws_source.PageSetup.PaperSize = 1
    ws_source.PageSetup.Orientation = 2  # 横向转换pdf
    ws_source.PageSetup.FitToPagesWide = 1  # 所有列压缩在一页纸
    ws_source.PageSetup.FitToPagesTall = False
    ws_source.PageSetup.Zoom = False  # 所有列压缩在一页纸
    ws_source.PageSetup.CenterVertically = True
    ws_source.PageSetup.CenterHorizontally = True
    ws_source.PageSetup.Draft = False
    ws_source.Select()
    # 行列自动调整
    # ws_source.Columns.AutoFit()
    # ws_source.Rows.AutoFit()
    # 设置Excel的边框
    rows = ws_source.UsedRange.Rows.Count
    cols = ws_source.UsedRange.Columns.Count
    ws_source.Range(ws_source.Cells(1, 1), ws_source.Cells(rows, cols)).Borders.LineStyle = 1
    ws_source.Range(ws_source.Cells(1, 1), ws_source.Cells(rows, cols)).Borders.TintAndShade = 0
    ws_source.Range(ws_source.Cells(1, 1), ws_source.Cells(rows, cols)).Borders.Weight = 1
    # 转换为PDF文件
    newpdf.ExportAsFixedFormat(0, r'Z:\34.pdf')
    newpdf.Close()
    excel.Quit()

Java

Java生成固定格式word并打印word文档解决方案【windows环境】
printword.exe

Go

Golang 实现word和Excel处理

package main

import (
	ole "github.com/go-ole/go-ole"
	"github.com/go-ole/go-ole/oleutil"
)

func printWord(fileName string) {
	ole.CoInitialize(0)
	unknown, _ := oleutil.CreateObject("Word.Application")
	word, _ := unknown.QueryInterface(ole.IID_IDispatch)
	oleutil.PutProperty(word, "Visible", false)
	documents := oleutil.MustGetProperty(word, "Documents").ToIDispatch()
	document := oleutil.MustCallMethod(documents, "Open", fileName).ToIDispatch()
	// oleutil.MustCallMethod(document, "PrintPreview").ToIDispatch()
	// oleutil.MustCallMethod(document, "PresentIt").ToIDispatch()
	oleutil.MustCallMethod(document, "PrintOut").ToIDispatch()
	document.Release()
	documents.Release()
	word.Release()
	ole.CoUninitialize()
}

func printExcel(fileName string) {
	ole.CoInitialize(0)
	unknown, _ := oleutil.CreateObject("Excel.Application")
	excel, _ := unknown.QueryInterface(ole.IID_IDispatch)
	oleutil.PutProperty(excel, "Visible", false)
	workbooks := oleutil.MustGetProperty(excel, "Workbooks").ToIDispatch()
	workbook, _ := oleutil.CallMethod(workbooks, "Open", fileName)
	//defer workbook.ToIDispatch().Release()
	worksheet := oleutil.MustGetProperty(workbook.ToIDispatch(), "Worksheets", 1).ToIDispatch()
	//defer worksheet.Release()

	oleutil.MustCallMethod(worksheet, "PrintOut").ToIDispatch()

	worksheet.Release()
	workbooks.Release()
	excel.Release()
	ole.CoUninitialize()
}

func wordToPdf(fileName string) {
	ole.CoInitialize(0)
	unknown, _ := oleutil.CreateObject("Word.Application")
	word, _ := unknown.QueryInterface(ole.IID_IDispatch)
	oleutil.PutProperty(word, "Visible", false)
	documents := oleutil.MustGetProperty(word, "Documents").ToIDispatch()
	document := oleutil.MustCallMethod(documents, "Open", fileName).ToIDispatch()
	oleutil.MustCallMethod(document, "SaveAs2", "z:/123_2.pdf", 17).ToIDispatch()
	document.Release()
	documents.Release()
	word.Release()
	ole.CoUninitialize()
}

func excelToPdf(fileName string) {
	ole.CoInitialize(0)
	unknown, _ := oleutil.CreateObject("Excel.Application")
	excel, _ := unknown.QueryInterface(ole.IID_IDispatch)
	oleutil.PutProperty(excel, "Visible", false)
	workbooks := oleutil.MustGetProperty(excel, "Workbooks").ToIDispatch()
	workbook, _ := oleutil.CallMethod(workbooks, "Open", fileName)
	//defer workbook.ToIDispatch().Release()
	worksheet := oleutil.MustGetProperty(workbook.ToIDispatch(), "Worksheets", 1).ToIDispatch()
	//defer worksheet.Release()
	ps := oleutil.MustGetProperty(worksheet, "PageSetup").ToIDispatch()
	oleutil.PutProperty(ps, "LeftHeader", "")
	oleutil.PutProperty(ps, "CenterHeader", "")
	oleutil.PutProperty(ps, "RightHeader", "")
	oleutil.PutProperty(ps, "LeftFooter", "")
	oleutil.PutProperty(ps, "CenterFooter", "")
	oleutil.PutProperty(ps, "RightFooter", "")
	oleutil.PutProperty(ps, "LeftMargin", 0)
	oleutil.PutProperty(ps, "RightMargin", 0)
	oleutil.PutProperty(ps, "TopMargin", 0)
	oleutil.PutProperty(ps, "BottomMargin", 0)
	oleutil.PutProperty(ps, "HeaderMargin", 0)
	oleutil.PutProperty(ps, "FooterMargin", 0)
	oleutil.PutProperty(ps, "Orientation", 2)
	oleutil.PutProperty(ps, "Zoom", false)
	oleutil.PutProperty(ps, "FitToPagesWide", 1)
	oleutil.PutProperty(ps, "FitToPagesTall", false)
	oleutil.PutProperty(ps, "CenterVertically", true)
	oleutil.PutProperty(ps, "CenterHorizontally", true)
	oleutil.PutProperty(ps, "Draft", false)
	oleutil.PutProperty(ps, "FirstPageNumber", true)
	oleutil.MustCallMethod(worksheet, "ExportAsFixedFormat", 0, "z:/34_2.pdf").ToIDispatch()
	ps.Release()
	worksheet.Release()
	workbooks.Release()
	excel.Release()
	ole.CoUninitialize()
}

func main() {
	// wordToPdf("z:/123.docx")
	printWord("z:/123.docx")
	// printWord("z:/123.pdf")
	// excelToPdf("z:/34.xlsx")
	printExcel("z:/34.xlsx")
}

win32com操作word 第二集:Application&Documents接口
win32com操作word 第三集:Range精讲(一)

Application 接口 NET COM
Document 接口 NET COM

Word VBA 參考 microsoft
Word 解决方案 microsoft


如何使用Golang生成和转换PDF文档

golang打印机控制,go 打印机

Qt

C++/Qt 和 Word,Excel,PDF 交互总结

3、打印普通文件

使用 Win32api 打印到打印机
python使用win32api调用打印机

# print cmd
import win32api
import win32print
win32api.ShellExecute(0,"print","C:\Test.csv",None,".",0)
win32api.ShellExecute(0, "print", "test.txt", '/d:"%s"' % win32print.GetDefaultPrinter(), ".", 0)

打印机小例子(windowsAPI)

4、Windows 打印 API

打印后台处理程序 API microsoft

Windows API函数(打印函数)
c++调用win32API控制打印机打印

Windows打印机API封装

5、打印信息

获取打印机和打印作业的状态
Qt/Windows 获取 MITSUBISHI P95DW 打印机状态信息

// pro
// QT += printsupport

	#include <QPrinterInfo>
	
    QPrinterInfo printerInfo;
    auto pNames = printerInfo.availablePrinterNames();

遍历电脑打印机、设置默认打印机、EnumPrinters ,SetDefaultPrinter,GetDefaultPrinter
Qt 使用 MSVC编译器构建工程时, 指定多字节字符集

CheckMenuItem()函数,EnumPrinters()枚举打印机AppendMenu(),添加菜单 printerPropertites()GetMenuString()CreateIC()

二、Windows API

Windows API 索引
OpenPrinter 函数

Windows API函数大全

qt中使用Windows API函数CreateProcess启动msu文件
【Unity】用Windows Api控制窗口置顶、窗口风格等操作
windows通过进程名查找hwnd,并发送消息

QT中使用虚拟键盘

cmake_minimum_required(VERSION 3.9)
project(FaceSdk C CXX)

set(CMAKE_CXX_STANDARD 14)

# add_definitions(-DUNICODE -D_UNICODE)

add_executable(test main.cpp)
#include <string.h>
#include <tchar.h>
#include <windows.h>

#include <Psapi.h>

#include <iostream>

using namespace std;

HWND hFoundWindow = NULL;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
  DWORD dwID;
  GetWindowThreadProcessId(hwnd, &dwID);
  if (dwID == (DWORD)lParam) {
    // 找到了窗口句柄,将其保存在全局变量中
    hFoundWindow = hwnd;
    std::cout << "hwnd:" << hwnd << ", dwID:" << dwID << std::endl;
    return FALSE;
  }
  return TRUE;
}

BOOL CALLBACK EnumWindowsProc2(HWND hwnd, LPARAM lParam) {
  DWORD dwID;
  GetWindowThreadProcessId(hwnd, &dwID);

  HANDLE hProcess =
      OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwID);
  if (hProcess == NULL) {
    _tprintf(_T("Could not open process\n"));
    return 1;
  }

  TCHAR filename[MAX_PATH];
  GetModuleFileNameEx(hProcess, NULL, filename, MAX_PATH);

  // _tprintf(_T("Process name: %s\n"), filename);

  CloseHandle(hProcess);

  // wstring currentFileName(filename);
  string currentFileName(filename);

  if (currentFileName.find((LPCTSTR)lParam) != std::string::npos) {
    // 找到了窗口句柄,将其保存在全局变量中
    hFoundWindow = hwnd;
    cout << "filename:" << filename << ", " << (LPCTSTR)lParam
         << ", hwnd:" << hFoundWindow << endl;

    return FALSE;
  }

  return TRUE;
}

HWND FindWindowByProcessId(DWORD dwProcessId) {
  hFoundWindow = NULL;
  EnumWindows(EnumWindowsProc, (LPARAM)dwProcessId);
  return hFoundWindow;
}

HWND FindWindowByProcessName(LPCTSTR processName) {
  hFoundWindow = NULL;
  EnumWindows(EnumWindowsProc2, (LPARAM)processName);
  return hFoundWindow;
}

void PressKey(HWND hWnd, WORD key, DWORD time = 50) {
  PostMessage(hWnd, WM_KEYDOWN, key, 1);
  Sleep(time);
  PostMessage(hWnd, WM_KEYUP, key, 1);
}

int main(int argc, char *argv[]) {
  cout << "i am father process" << endl;

  STARTUPINFO si = {
      sizeof(STARTUPINFO)}; // 在产生子进程时,子进程的窗口相关信息
  PROCESS_INFORMATION pi; // 子进程的ID/线程相关信息
  DWORD returnCode;       // 用于保存子程进的返回值;

  // char commandLine[] =
  // "C:\\Users\\jx\\Desktop\\test01\\lib\\Debug\\childprocess.exe -l";
  // //测试命令行参数一
  // char commandLine[] = "childprocess.exe -l a b c";  // 测试命令行参数一
  // char commandLine[] = "calc.exe";  // 测试命令行参数一
  // char commandLine[] = "code";  // 测试命令行参数一
  // char commandLine[] = R"("C:\Program Files\Common Files\microsoft
  // shared\ink\TabTip.exe")";  // 测试命令行参数一
  // char
  //     commandLine[] =
  //         "\"C:\\\\Program Files\\\\Common Files\\\\microsoft "
  //         "shared\\\\ink\\\\TabTip.exe\"";  // 测试命令行参数一
  // string commandLine = "calc.exe";
  // string commandLine = "cmd.exe";
  // string commandLine = "Code.exe";
  string commandLine = "D:/getcolor.exe";
  // string commandLine = R"("C:\Program Files\Common
  // Files\microsoftshared\ink\TabTip.exe")";

  BOOL bRet = CreateProcess( // 调用失败,返回0;调用成功返回非0;
      NULL, // 一般都是空;(另一种批处理情况:此参数指定"cmd.exe",下一个命令行参数
            // "/c otherBatFile")
      (LPSTR)commandLine.c_str(), // 命令行参数
      NULL,  //_In_opt_    LPSECURITY_ATTRIBUTES lpProcessAttributes,
      NULL,  //_In_opt_    LPSECURITY_ATTRIBUTES lpThreadAttributes,
      FALSE, //_In_        BOOL                  bInheritHandles,
      // CREATE_NO_WINDOW,
      CREATE_NEW_CONSOLE, // 新的进程使用新的窗口。
      NULL,               //_In_opt_    LPVOID                lpEnvironment,
      NULL, //_In_opt_    LPCTSTR               lpCurrentDirectory,
      &si,  //_In_        LPSTARTUPINFO         lpStartupInfo,
      &pi); //_Out_       LPPROCESS_INFORMATION lpProcessInformation

  if (0 != bRet) {
    std::cout << "Create Child Process sucess!" << std::endl;
    // 等待子进程结束
    // WaitForSingleObject(pi.hProcess, -1);
    // std::cout << "Child Process is finished" << std::endl;
    // 获取子进程的返回值
    GetExitCodeProcess(pi.hProcess, &returnCode);
    std::cout << "Child Process return code:" << returnCode << std::endl;
  } else {
    std::cout << "Create child Process error!" << std::endl;
    return 0;
  }

  Sleep(500);
  // 获取进程的句柄
  // LPCTSTR titleName = "calc.exe";
  // LPCTSTR titleName = "cmd.exe";
  // LPCTSTR titleName = "Code.exe";
  LPCTSTR titleName = "getcolor.exe";
  HWND hWnd;
  // hWnd = FindWindow(NULL, titleName);

  std::cout << "dwProcessId:" << pi.dwProcessId << std::endl;
  hWnd = FindWindowByProcessId(pi.dwProcessId);
  if (hWnd == NULL) {
    std::cout << "FindWindowByProcessId failed" << std::endl;
    // return -1;
  }

  hWnd = FindWindowByProcessName(titleName);
  if (hWnd == NULL) {
    std::cout << "FindWindowByProcessName failed" << std::endl;
    return -1;
  }

  // RECT lpRect;
  // GetWindowRect(hWnd, &lpRect);

  for (size_t i = 0; i < 20; i++) {
    Sleep(500);
    // SetWindowPos(hWnd, HWND_TOP, i * 30, i * 20, 120, 120, SWP_NOSIZE);
    SetWindowPos(hWnd, HWND_TOPMOST, i * 30, i * 20, 120, 120, SWP_SHOWWINDOW);
  }

  // system("pause");
  Sleep(500);
  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);
  return 0;
}

   


http://www.niftyadmin.cn/n/5110475.html

相关文章

FGSM快速梯度符号法非定向攻击代码(PyTorch)

数据集&#xff1a;手写字体识别MNIST 模型&#xff1a;LeNet import torch.nn as nn import torch.nn.functional as F import torch from torchvision import datasets, transforms import matplotlib.pyplot as plt use_cuda True device torch.device("cuda"…

Canvas系列绘制图片学习:绘制图片和渐变效果

我们现在已经可以绘制好多东西了&#xff0c;不过在实际开发中&#xff0c;绘制最多的当然是图片了&#xff0c;这章我们就讲讲图片的绘制。 绘制图片 绘制图片的API是drawImage&#xff0c;它的参数有三种情况&#xff1a; // 将图片绘制在canvas的(dX, dY)坐标处 context.…

配置Linux

首先安装VMware&#xff1a; 安装说明&#xff1a;&#xff08;含许可证的key&#xff09; https://mp.weixin.qq.com/s/XE-BmeKHlhfiRA1bkNHTtg 给大家提供了VMware Workstation Pro16&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1q8VE3TkPzDnM3u9bkTdA_g 提取码&…

高校教务系统登录页面JS分析——巢湖学院

高校教务系统密码加密逻辑及JS逆向 本文将介绍高校教务系统的密码加密逻辑以及使用JavaScript进行逆向分析的过程。通过本文&#xff0c;你将了解到密码加密的基本概念、常用加密算法以及如何通过逆向分析来破解密码。 本文仅供交流学习&#xff0c;勿用于非法用途。 一、密码加…

16、监测数据采集物联网应用开发步骤(12.1)

阶段性源码将于本章节末尾给出下载 监测数据采集物联网应用开发步骤(11) 本章节进行前端web UI开发web数据接口服务开发 web数据接口服务利用SOCKET TCP服务方式解析http协议内容模式 在com.zxy.common.Com_Para.py中添加如下内容 #修改web数据接口服务端口 port 9000 #是…

3D双目跟踪瞳孔识别

人眼数据集通常用于眼部相关的计算机视觉、眼动追踪、瞳孔检测、情感识别以及生物特征识别等领域的研究和开发。以下是一些常见的人眼数据集&#xff1a; BioID Face Database: 这个数据库包含1,521张近距离的人脸图像&#xff0c;其中包括瞳孔位置的标记。它通常用于瞳孔检测和…

EPLAN_010#STEP格式_箱柜模型的定义、拼柜

一、导入 首先创建一个宏项目——在布局空间中导航器新建一个布局空间 菜单栏——布局空间——导入(3D图形&#xff09;——导入下载下来的STEP 如果导入进来的箱柜是这种模样的&#xff0c;表示可以使用。如果左侧只显示一个逻辑组件&#xff0c;则无法使用。&#xff08;如果…

最近又火了!吴恩达《生成式 AI》重磅发布!

吴恩达教授可能是许多人接触 AI 的启蒙课导师吧&#xff0c;在过去的十多年中&#xff0c;他的《Machine Learning》课程已经对数百万的学习者产生了积极影响。 而随着 ChatGPT 的推出&#xff0c;大模型和各类生成式人工智能&#xff08;GenAI&#xff09;技术在行业内外备受…