Python tkinter如何将画布保存为PostScript并添加到PDF中。

5
我有一个简单的Python tkinter绘画程序(用户使用鼠标在画布上绘制)。我的目标是保存最终的绘画并将其放入包含其他内容的PDF文件中。
经过搜索,我发现只能将画布绘画保存为像这样的postscript文件: canvas.postscript(file="file_name.ps", colormode='color') 所以,我想知道是否有任何方法(任何Python模块?)可以允许我将Postscript文件作为图像插入到PDF文件中。
这是否可能?

1
我会参考这个问题,了解可以实现此功能的模块。祝你好运! - Al.Sal
1个回答

9

此答案中所述,一个可能的解决方法是打开一个子进程来使用Ghostscript

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

另一种解决方案是使用ReportLab,但由于其addPostScriptCommand不太可靠,我认为您需要先使用Python Imaging Library将PS文件转换为图像,然后将其添加到ReportLab 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()

1
这个方法可行,但在生成postscript之前,我必须先在画布上调用update()方法,就像这个答案中所示,否则生成的postscript将是一个1x1的图像。 - Ahmed Akhtar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接