简体   繁体   English

Python Tkinter将画布另存为Postscript并添加到pdf

[英]Python tkinter save canvas as postscript and add to pdf

I have a simple python tkinter paint program (user use mouse to draw on the canvas). 我有一个简单的python tkinter绘画程序(用户使用鼠标在画布上绘制)。 My objective is to save the final drawing and put it into a pdf file with other contents. 我的目标是保存最终图形,并将其与其他内容一起放入pdf文件。

After looking around, i realized that i can only save the canvas drawing as postscript file like this 环顾四周后,我意识到我只能将画布图形保存为这样的postscript文件

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

So, i am wondering if there's any way (any python module?) that will allow me to insert the postscript files into pdf file as images. 所以,我想知道是否有任何方式(任何python模块?)可以让我将Postscript文件作为图像插入pdf文件。

Is it possible? 可能吗?

As it is mentioned in this answer , a possible walkaround is to open a subprocess to use ghostscript : 正如在此答案中提到的,可能的解决方法是打开一个子进程以使用ghostscript

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

Another solution would be to use ReportLab , but since its addPostScriptCommand is not very reliable, I think you'll have to use the Python Imaging Library to convert the PS file to an image first, and then add it to the ReportLab Canvas . 另一个解决方案是使用ReportLab ,但是由于其addPostScriptCommand不太可靠,我认为您必须首先使用Python Imaging Library将PS文件转换为图像,然后再将其添加到ReportLab Canvas中 However, I'd suggest the ghostscript approach. 但是,我建议使用ghostscript方法。

This is a basic proof of concept I used to see if it works: 这是我用来查看是否有效的基本概念证明:

"""
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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM