【发布时间】:2016-03-09 15:38:52
【问题描述】:
我正在编写一个程序,它获取给定文件夹中的所有图片并将它们聚合成 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 有关。 -
它可以正常工作,但 1962x2362 的图像尺寸没有正确合并到 pdf 中。它转向一侧,只显示了一部分。 @B8vrede
-
这很奇怪,我只是用精确尺寸的图像进行了尝试,它再次工作得很好。您是否尝试将其合并到不同的 PDF 中?您将图像合并到的 PDF 实际上是旋转的 PDF 的可能性很小。
-
我注意到你说你的输出是 sample.pdf,我的输出是 output.pdf。有没有可能是我们没有得到相同结果的原因? @B8vrede
-
哦不,这只是一个混淆,我指的是
output.pdf看起来和sample.pdf一模一样,唯一的区别是@左下角有一个小图像987654326@。但是可以检查一下您的watermark0.pdf(以及之后的所有其他数字)是否以正确的方式包含图像?
标签: python pdf reportlab pypdf2