【问题标题】:Preview a PDF file and choose printer before actually printing the document在实际打印文档之前预览 PDF 文件并选择打印机
【发布时间】:2017-03-14 09:18:34
【问题描述】:

我目前正在 Python3/tkinter 中开发一个应用程序,它将主要在 Mac 上运行,并且需要打印 PDF 文件。

过去,我设法通过使用 bash 脚本中的一些命令将 PDF 文件自动发送到打印机,所以我认为我最终可以使用这种方法作为最后的手段。

但是,我从来没有找到一种方法来指定一台打印机,它总是将它直接发送到当前选择的打印机(通常是最后使用的打印机)。问题是所有这些计算机都连接到一台以上的打印机,并且有些打印机不适合 A4 文档(例如,标签打印机)。

有谁知道是否有任何方法可以从命令行启动预览应用程序,或者任何允许我们在实际打印之前预览和选择打印机的外部模块?

【问题讨论】:

  • 在我的 Bash 脚本中,我使用 pdfsplit $FILENAME 3 |lpr 来打印来自上一个操作的 PDF 文件的第 3 页。我还可以指定更多页面,在每个页面之间添加一个空格。
  • 嗯,让用户自己打印 pdf 也可以吗?您可以使用webbrowser 打开它,让您的用户自己查看和打印...
  • @Nearoo 是否有预览应用程序的 URL 方案?还是我必须启动浏览器并从那里打印?
  • 后者就是这样。但我看到有人已经发布了更好的答案。

标签: python macos printing tkinter printers


【解决方案1】:

这是我刚刚创建的一个程序,它允许您选择打印机并进行打印。

import tkinter as tk
from tkinter.filedialog import askopenfilename
import subprocess
from pprint import pprint
import platform
import sys

def which(program):
    # http://stackoverflow.com/a/377028/3924118
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None


class FilePrinterDialog(tk.Toplevel):

    def __init__(self, root, *args, **kwargs):
        tk.Toplevel.__init__(self, root, *args, **kwargs)
        self.root = root

        self.body = tk.Frame(self, bg="lightblue")
        self.body.pack(expand=True, fill="both")

        self.title_frame = tk.Frame(self.body, pady=5)
        self.title_frame.pack(fill="both", pady=(15, 5))

        self.title = tk.Label(self.title_frame,  text="Let's print!")
        self.title.pack(fill="x")

        # Current selected printer of your system
        self.system_default_destination = self._find_system_default_destination()

        # Finds printer names
        self.printers_names = self._find_printers_names()

        self.selected_file = None  # To hold the selected file's name
        self.data_bytes = None  # Bytes read from the selected file to print
        self.selected_printer = None  # Hols name of selected printer

        # Display them
        self.printers_frame = tk.Frame(self.body, bg="lightblue", padx=10, pady=10)
        self.printers_frame.pack(expand=True, fill="both")
        self._display_printers()

        self.bottom_frame = tk.Frame(self.body, pady=5)
        self.bottom_frame.pack(fill="both", pady=(5, 16))
        self.open_file_chooser = tk.Button(self.bottom_frame,
                                           text="Open file chooser",
                                           command=self._select_file)
        self.open_file_chooser.pack(side="left", padx=10)

        self.print_file = tk.Button(self.bottom_frame,
                                           text="Print",
                                           command=self._print_selected_file)
        self.print_file.pack(side="right", padx=10)


        self._make_modal()

    def _read_file(self):
        # NOT USED!
        if not self.selected_file:
            raise ValueError("No file chosen")
        with open(self.selected_file, "rb") as in_file: # opening for [r]eading as [b]inary
            return in_file.read() # if you only wanted to read 512 bytes, do .read(512)

    def _print_selected_file(self):
        if not self.selected_file:
            print("No file selected yet!")
        else:
            subprocess.call(["lpr", self.selected_file])

    def _select_file(self):
        self.selected_file = askopenfilename(title = "Choose file to print")
        print(self.selected_file)

    def _on_listbox_selection(self, event):
        self.selected_printer = self._find_current_selected_printer()

        # Sets the printer on your system
        subprocess.call(["lpoptions", "-d", self.selected_printer])
        print("Selected printer:", self.selected_printer)

    def _find_current_selected_printer(self):
        curselection = self.listbox.curselection()
        if len(curselection) > 0:
            return self.listbox.get(curselection[0])   
        else:
            return None

    def _display_printers(self):
        self.scrollbar = tk.Scrollbar(self.printers_frame)
        self.scrollbar.pack(side="right", fill="y")

        self.listbox = tk.Listbox(self.printers_frame,
                                  yscrollcommand=self.scrollbar.set,
                                  selectbackground="yellow",
                                  selectmode="single",
                                  height=6)

        for printer_name in self.printers_names:
            self.listbox.insert("end", printer_name)

        # Keep track of selected listbox
        self.listbox.bind("<<ListboxSelect>>", self._on_listbox_selection)

        # Sets first listbox as selected
        self.listbox.select_set(0) # Sets focus
        self.listbox.event_generate("<<ListboxSelect>>")

        self.listbox.pack(side="left", fill="both", expand=True)
        self.scrollbar.config(command=self.listbox.yview)

    def _find_system_default_destination(self):
        return subprocess.getoutput("lpstat -d").split(": ")[1]

    def _find_printers_names(self):
        # Command to obtain printer names based on: https://superuser.com/a/1016825/317323
        return subprocess.getoutput("lpstat -a | awk '{print $1}'").split("\n")

    def _make_modal(self):
        # Makes the window modal
        self.transient(self.root)
        self.grab_set()
        self.wait_window(self)


if __name__ == "__main__":
    if not which("lpoptions") or not which("lpr") or not which("awk") or not which("lpstat"):        
        sys.stderr.write("Requirements: lopotions, lpr, lpstat and awk not satisfied")
    else:
        root = tk.Tk()
        opener = tk.Button(root, text="Open printer chooser", command=lambda: FilePrinterDialog(root))
        opener.pack()
        root.mainloop()

该程序仅在您具有我在程序中指定的所需依赖项时才有效。你应该有这些,因为我也在 Mac OS X (Sierra) 上。

我仅使用.py 文件进行了测试。不幸的是,打印文档的格式并不如您所愿(因为我并不是真正的如何使用lpr 打印文件的专家),但您可以查看lpr 的选项,看看您能做什么去做吧。

另外,我还没有创建所选文件的任何预览,但您可以使用 PIL 来实现这一点(至少对于图像)...

注意:注意,不要在print按钮上点击100次,否则队列中会有100个文件需要打印!您可能想以某种方式解决此问题。

【讨论】:

  • 似乎是我正在寻找的东西。我会研究那个代码! :)
  • @VictorDomingos 不错!如果有任何问题,请告诉我,我们最终可以改进程序(也许也适用于未来的用户);)
猜你喜欢
  • 1970-01-01
  • 2021-02-14
  • 2020-06-11
  • 2017-11-26
  • 2016-10-09
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 2019-08-15
相关资源
最近更新 更多