//This uses simpledoctemplate to create pdf. Im not able to bring the image to top of the page. Please give a solution
def report_creator():
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
elements = []
im = Image("C:\\Images\photo.jpg")
elements.append(im)
doc = SimpleDocTemplate("C:\\report_image.pdf", pagesize=letter)
doc.build(elements)
if __name__ == "__main__":
report_creator()
print "main"
From source code, when drawing, Image try to get _offs_x
, _offs_y
attributes
def draw(self):
lazy = self._lazy
if lazy>=2: self._lazy = 1
self.canv.drawImage( self._img or self.filename,
getattr(self,'_offs_x',0),
getattr(self,'_offs_y',0),
self.drawWidth,
self.drawHeight,
mask=self._mask,
)
if lazy>=2:
self._img = self._file = None
self._lazy = lazy
To position the image using SimpleDocTemplate, you can overwrite the _offs_x
and _offs_y
attributes of Image object before adding it into story.
im.__setattr__("_offs_x", 0)
im.__setattr__("_offs_y", 0)
The width and height of reportlab's
letter page size is (612.0, 792.0)
. So you can get the the starting position for your input image by dividing ((page's width/2) - (input image's width/2))
.
In this example
page's width = 612.0
input image width = 100
So starting position(x) for input image would be:
>>> int((612.0/2) - (100/2))
256
Note :- Image size is passed as argument in drawInlineImage
method of Canvas
.
from PIL import Image
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
def generate_pdf(c):
"""
letter :- (612.0, 792.0)
"""
im = Image.open("so.png")
c.drawInlineImage(im, 256, 720, width=100, height=60)
c = canvas.Canvas("report_image.pdf", pagesize=letter)
generate_pdf(c)
c.save()
Generated PDF looks like this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.