图像绘制为reportlab pdf大于pdf纸张尺寸

时间:2016-03-09 15:38:53

标签: python pdf reportlab pypdf2

我正在编写一个程序,该程序将所有图片放在给定的文件夹中并将它们聚合成pdf。我遇到的问题是,当绘制图像时,它们的尺寸更大,并且奇怪地向左旋转。我到处搜索过,甚至在reportlab文档中都找不到任何内容。

以下是代码:

import os
from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
from StringIO import StringIO


def main():
    images = image_search()
    output = PdfFileWriter()
    for image in images:
        Image_file = Image.open(image)     # need to convert the image to the specific size first.
    width, height = Image_file.size
    im_width = 1 * cm
    # Using ReportLab to insert image into PDF
    watermark_str = "watermark" + str(images.index(image)) + '.pdf'
    imgDoc = canvas.Canvas(watermark_str)

    # Draw image on Canvas and save PDF in buffer
    # define the aspect ratio first
    aspect = height / float(width)

    ## Drawing the image
    imgDoc.drawImage(image, 0,0, width = im_width, height = (im_width * aspect))    ## at (399,760) with size 160x160
    imgDoc.showPage()
    imgDoc.save()
    # Get the watermark file just created
    watermark = PdfFileReader(open(watermark_str, "rb"))

    #Get our files ready

    pdf1File = open('sample.pdf', 'rb')
    page = PdfFileReader(pdf1File).getPage(0)
    page.mergePage(watermark.getPage(0))


    #Save the result

    output.addPage(page)
    output.write(file("output.pdf","wb"))

#The function which searches the current directory for image files.
def image_search():
    found_images = []
    for doc in os.listdir(os.curdir):
        image_ext = ['.jpg', '.png', '.PNG', '.jpeg', '.JPG']
        for ext in image_ext:
            if doc.endswith(ext):
                found_images.append(doc)
    return found_images

main()

我还尝试使用im_width变量进行缩放和指定宽高比,这会产生相同的输出。

1 个答案:

答案 0 :(得分:2)

在对您的目标产生一些混淆之后,我发现目标是对当前文件夹中的图像进行PDF概述。为此,我们实际上并不需要IStartup,因为Reportlab提供了我们所需的一切。

请参阅以下代码,并将评论作为指南:

 final IWorkbench workbench = PlatformUI.getWorkbench();
 workbench.getDisplay().asyncExec(new Runnable() {
   public void run() {
     IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
     if (window != null) {
       // do something
     }
   }
 });