医疗终端札记
  KUhs7mNfc72R 2023年11月02日 18 0


医疗终端札记_API



文章目录

  • 一、打印
  • 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 COMDocument 接口 NET COM

Word VBA 參考 microsoftWord 解决方案 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,GetDefaultPrinterQt 使用 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;
}

   


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
KUhs7mNfc72R