我正在编写一个程序,它可以将给定文件夹中的所有图片聚合到一个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
变量进行缩放和指定纵横比,但输出结果相同。
sample.pdf
文件,其中包含我文件夹中底部左侧绘制的图像,宽度为1厘米。我尝试过使用reportlab生成的pdf以及从互联网上随机下载的PDF...所以问题可能与你的reportlab或PyPDF2版本或图像/PDF有关。 - B8vredeoutput.pdf
看起来和sample.pdf
完全一样,唯一的区别是在output.pdf
的左下角有一张小图片。但是请问一下,你能检查一下watermark0.pdf
(以及之后的每个数字)是否正确包含了图片吗? - B8vrede