Python tkinter将canvas保存为postscript并添加到pdf [英] Python tkinter save canvas as postscript and add to pdf

查看:3384
本文介绍了Python tkinter将canvas保存为postscript并添加到pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple python tkinter paint program (user use mouse to draw on the canvas). My objective is to save the final drawing and put it into a pdf file with other contents.

查看后,我意识到,我只能保存画布图为 postscript 这样的文件

After looking around, i realized that i can only save the canvas drawing as postscript file like this

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

所以,我想知道是否有任何方式(任何python模块),将允许我插入postscript

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.

是否有可能?

推荐答案

>正如在此答案中提到的,可能的解决方法是打开子流程以使用 ghostscript

As it is mentioned in this answer, a possible walkaround is to open a subprocess to use 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方法。

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. However, I'd suggest the ghostscript approach.

这是一个概念的基本证明,我用来查看它是否工作:

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

这篇关于Python tkinter将canvas保存为postscript并添加到pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆