简体   繁体   English

如何使用simpledoctemplate reportlab软件包将图像移动到pdf页面顶部?

[英]How to move the image to top of page in pdf using simpledoctemplate reportlab package?

//This uses simpledoctemplate to create pdf. //这使用simpledoctemplate创建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 从源代码中,在绘制时,Image尝试获取_offs_x_offs_y属性

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. 要使用SimpleDocTemplate定位图像,可以_offs_y Image对象的_offs_x_offs_y属性覆盖,然后_offs_y其添加到故事中。

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) . reportlab's信纸大小的宽度和高度为(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)) . 因此,可以通过除以((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: 因此,输入图像的起始位置(x)为:

>>> int((612.0/2) - (100/2))
256

Note :- Image size is passed as argument in drawInlineImage method of Canvas . 注意:-图像大小在Canvas drawInlineImage方法中作为参数传递。

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: 生成的PDF如下所示:

report_image.pdf

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

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