Reputation: 71
I'm using reportlab to draw a PDF normaly used for printing. How can i save the canvas as a PNG image instead, without using additional binary tools to convert the generated pdf?
I assume i need to convert it to a reportlab Drawing, but don't see a way to do so.
from reportlab.pdfgen import canvas
c = canvas.Canvas("form.pdf", pagesize=(100, 50))
c.drawString(20, 20, 'Example …')
c.save() # but as image
Upvotes: 1
Views: 4880
Reputation: 56660
I found the suggestion in Yan Weitao's answer very helpful. Here's the equivalent of the example in your question:
from reportlab.graphics.renderPM import drawToFile
from reportlab.graphics.shapes import Drawing, String
drawing = Drawing(width=100, height=50)
drawing.contents.append(String(20, 20, 'Example …'))
drawToFile(drawing, 'example.png')
After digging into the drawToFile()
function, I think you might be able to use the reportlab.graphics.renderPM.PMCanvas
class instead of the standard canvas. It has a saveToFile()
method, but my first attempt just generated a blank image, so you'll have to do some experimenting.
Upvotes: 0
Reputation: 3308
It seems that there're no functions in reportlab
package to convert Canvas
object to PNG image. But you can use another packages (f.e. pdf2image) to convert Canvas
to PNG image.
Installation
To use pdf2image
package you should install poppler
and pdf2image
packages. You can find installation instructions here (section "How to install")
After installation you can solve your problem using this approach:
from reportlab.pdfgen import canvas
from pdf2image import convert_from_bytes
c = canvas.Canvas("form.pdf", pagesize=(100, 50))
c.drawString(20, 20, 'Example …')
image = convert_from_bytes(c.getpdfdata())[0]
image.save('form.png')
Upvotes: 0
Reputation: 11
From the 'reportlab-userguide', I found a piece of code, not sure it is useful?
from reportlab.graphics import renderPM
d = Drawing(400, 200)
d.add(Rect(50, 50, 300, 100, fillColor=colors.yellow))
d.add(String(150, 100, 'Hello World', fontSize=18, fillColor=colors.red))
d.add(String(180, 86, 'Special characters \
\xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xce\xb1\xce\xb2',
fillColor=colors.red))
renderPM.drawToFile(d, 'example1.png', 'PNG')
Upvotes: 1