Установите альбомную ориентацию для файла PDF с помощью pycairo

Мне удалось создать отчет в формате PDF с помощью pycairo. Титульная страница была в порядке, но вторая страница, которую мне нужно изменить, зависит от размера диаграммы. Как я могу установить одну страницу в альбомной ориентации и одну страницу в портретной ориентации с помощью pycairo. Спасибо.

Вот моя функция для создания второй страницы:

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

введите здесь описание изображения


person noob    schedule 24.02.2014    source источник
comment
До сих пор я пытался масштабировать диаграмму, чтобы она всегда помещалась на странице, и поворачивать ее, если ее ширина слишком велика.   -  person noob    schedule 25.02.2014


Ответы (1)


Поверхность PDF имеет метод set_size.

eg

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

# Set A4 landscape page size
surface.set_size(842, 595)
person Adrian    schedule 27.02.2014
comment
Спасибо за ваш комментарий! Я уже пробовал это, но не работает для нескольких страниц. - person noob; 28.02.2014
comment
Убедитесь, что вы вызываете set_size перед рисованием на странице. Была старая версия cairo (1.10.0), в которой была ошибка в set_size. Это было исправлено в 1.10.2. - person Adrian; 28.02.2014
comment
Когда я создаю PDF-поверхность, я устанавливаю_size (595 842) для первой страницы. затем я создаю вторую страницу с помощью вызова context.show_page(). Как вы можете установить_размер (842, 595) только для второй страницы. Я пробовал это раньше, когда я снова set_site, все две страницы изменятся. - person noob; 28.02.2014
comment
set_size установит размер текущей и всех последующих страниц. Если вы хотите, чтобы страница 3 стала портретной, вам нужно будет вызвать set_size на странице 3. - person Adrian; 01.03.2014