Python tkinter 将画布保存为 postscript 并添加到 pdf

Posted

技术标签:

【中文标题】Python tkinter 将画布保存为 postscript 并添加到 pdf【英文标题】:Python tkinter save canvas as postscript and add to pdf 【发布时间】:2013-07-26 11:53:52 【问题描述】:

我有一个简单的 python tkinter 绘图程序(用户使用鼠标在画布上绘图)。我的目标是保存最终绘图并将其放入包含其他内容的 pdf 文件中。

环顾四周,我意识到我只能像这样将画布绘图保存为postscript文件

canvas.postscript(file="file_name.ps", colormode='color')

所以,我想知道是否有任何方法(任何 python 模块?)可以让我将 postscript 文件作为图像插入到 pdf 文件中。

有可能吗?

【问题讨论】:

我会参考this 问题以获取有关可以执行此操作的模块的信息。祝你好运! 【参考方案1】:

正如this answer 中提到的,一种可能的解决方法是打开一个子进程以使用ghostscript:

canvas.postscript(file="tmp.ps", colormode='color')
process = subprocess.Popen(["ps2pdf", "tmp.ps", "result.pdf"], shell=True)

另一种解决方案是使用ReportLab,但由于它的addPostScriptCommand不是很可靠,我认为您必须先使用Python Imaging Library将PS文件转换为图像,然后添加它报告实验室Canvas。不过,我建议使用 ghostscript 方法。

这是我用来查看它是否有效的基本概念证明:

"""
Setup for Ghostscript 9.07:

Download it from http://www.ghostscript.com/GPL_Ghostscript_9.07.html
and add `/path/to/gs9.07/bin/` and `/path/to/gs9.07/lib/` to your path.
"""

import Tkinter as tk
import subprocess
import os

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Canvas2PDF")
        self.line_start = None
        self.canvas = tk.Canvas(self, width=300, height=300, bg="white")
        self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
        self.button = tk.Button(self, text="Generate PDF",
                                command=self.generate_pdf)
        self.canvas.pack()
        self.button.pack(pady=10)

    def draw(self, x, y):
        if self.line_start:
            x_origin, y_origin = self.line_start
            self.canvas.create_line(x_origin, y_origin, x, y)
            self.line_start = None
        else:
            self.line_start = (x, y)

    def generate_pdf(self):
        self.canvas.postscript(file="tmp.ps", colormode='color')
        process = subprocess.Popen(["ps2pdf", "tmp.ps", "result.pdf"], shell=True)
        process.wait()
        os.remove("tmp.ps")
        self.destroy()

app = App()
app.mainloop()

【讨论】:

这行得通,但是,在生成 postscript 之前,我必须在画布上调用 update() 方法,就像在 this other answer 中所做的那样,否则 postscript 会生成 1x1 图像。

以上是关于Python tkinter 将画布保存为 postscript 并添加到 pdf的主要内容,如果未能解决你的问题,请参考以下文章