5

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.

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

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.

Is it possible?

Chris Aung
  • 9,152
  • 33
  • 82
  • 127
  • 1
    I'd refer to [this](http://stackoverflow.com/questions/2252726/how-to-create-pdf-files-in-python) question for info on modules that can do that. Good luck! – Al.Sal Jul 26 '13 at 12:34

1 Answers1

9

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)

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()
Community
  • 1
  • 1
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • 1
    This worked, however, I had to call update() method on the canvas before generating the postscript as done in [this other answer](https://stackoverflow.com/questions/9886274/how-can-i-convert-canvas-content-to-an-image) otherwise the postscript generated a 1x1 image. – Ahmed Akhtar May 23 '18 at 07:07