700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python批量图片转pdf 将TIFF图像批量转换为PDF ImageMagick Python

python批量图片转pdf 将TIFF图像批量转换为PDF ImageMagick Python

时间:2020-06-09 03:21:55

相关推荐

python批量图片转pdf 将TIFF图像批量转换为PDF ImageMagick Python

这里是我创建的一个纯python实现,它不依赖ImageMagick。它只依赖于PIL和reportlab。它可以在谷歌应用程序引擎这样的受限环境下运行。def TIFF2PDF(tiff_str, max_pages = 200):

'''

Convert a TIFF Image into a PDF.

tiff_str: The binary representation of the TIFF.

max_pages: Break after a number of pages. Set to None to have no limit.

'''

import PIL

import reportlab

import reportlab.lib.pagesizes as pdf_sizes

from cStringIO import StringIO

logging.info("TIFF2PDF")

# Open the Image in PIL

tiff_img = PIL.Image.open(StringIO(tiff_str))

# Get tiff dimensions from exiff data. The values are swapped for some reason.

height, width = tiff_img.tag[0x101][0], tiff_img.tag[0x100][0]

# Create our output PDF

out_pdf_io = StringIO()

c = reportlab.pdfgen.canvas.Canvas(out_pdf_io, pagesize = pdf_sizes.letter)

# The PDF Size

pdf_width, pdf_height = pdf_sizes.letter

# Iterate through the pages

page = 0

while True:

try:

tiff_img.seek(page)

except EOFError:

break

logging.info("Converting tiff page: %s"%page)

# Stretch the TIFF image to the full page of the PDF

if pdf_width * height / width <= pdf_height:

# Stretch wide

c.drawInlineImage(tiff_img, 0, 0, pdf_width, pdf_width * height / width)

else:

# Stretch long

c.drawInlineImage(tiff_img, 0, 0, pdf_height * width / height, pdf_height)

c.showPage()

if max_pages and page > max_pages:

logging.error("Too many pages, breaking early")

break

page += 1

logging.info("Saving tiff image")

c.save()

return out_pdf_io.getvalue()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。