2014-02-24 26 views
0

我設法使用pycairo創建pdf報告。封面很好,但我需要改變其方向的第二頁取決於圖的大小。如何使用pycairo設置一個頁面橫向和一個頁面縱向。謝謝。使用pycairo設置PDF文件的橫向方向

這裏是我的函數生成第二頁:

def draw_pedigree(ctx, path_to_image, left, top, container_width, container_height): 
# create a new page to draw a pedigree 
ctx.show_page() 
ctx.save() 

# load image from input path 
image_surface = cairo.ImageSurface.create_from_png(path_to_image) 

img_height = image_surface.get_height() 
img_width = image_surface.get_width() 

print "img_height: %d" % img_height 
print "img_width: %d" % img_width 
print "container_height: %d" % container_height 
print "container_width: %d" % container_width 

if (img_width <= container_width and img_height <= container_height): # this case the image don't need to be scaled or rotated 
    ctx.translate(left, top) 
    ctx.set_source_surface(image_surface) 
    ctx.paint() 
    ctx.restore() 
else: # this case the image need to be scaled 

    # check should image be rotated or not 
    if(float(img_height)/float(img_width) <= 0.875): # rotate the image 
     width_ratio = float(container_height)/float(img_width) 
     height_ratio = float(container_width)/float(img_height) 
     scale_xy = min(height_ratio, width_ratio) 
     print "scale_xy: %f" % scale_xy 

     ctx.translate(545, top) 
     ctx.rotate(math.pi/2) 

     if(scale_xy < 1): 
      ctx.scale(scale_xy, scale_xy) 

     ctx.set_source_surface(image_surface) 
     ctx.paint() 
     ctx.restore() 
    else: # don't rotate the image 
     # calculate proportional scaling 
     width_ratio = float(container_width)/float(img_width) 
     height_ratio = float(container_height)/float(img_height) 
     scale_xy = min(height_ratio, width_ratio) 
     ctx.scale(scale_xy, scale_xy) 
     ctx.translate(left, top) 
     ctx.set_source_surface(image_surface) 
     ctx.paint() 
     ctx.restore() 

enter image description here

+0

到目前爲止,我試圖縮放圖,以便它總是會融入網頁,如果它的寬度過長旋轉。 –

回答

1

的PDF表面具有set_size方法。

# Set A4 portrait page size 
surface.set_size(595, 842) 

# Set A4 landscape page size 
surface.set_size(842, 595) 
+0

謝謝您的評論!我已經嘗試過,但不適用於多個頁面。 –

+0

確保在繪製頁面之前調用set_size。有一個老版本的cairo(1.10.0)在set_size中有一個bug。這已在1.10.2中修復。 – Adrian

+0

當我爲第一頁創建PDFsurface時,我使用set_size(595,842)。然後我通過調用context.show_page()創建第二個頁面。你怎麼能set_size(842,595)只爲第二頁。我之前嘗試過,當我set_site再次全部兩頁將改變。 –