秃头小妹0 2021-08-17 09:39 采纳率: 50%
浏览 20
已结题

为什么我在多个图片转换PDF时,只能保存于一次吗


import os

import PIL
from reportlab.lib import utils
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas

from image_split import ClipType
from reportlab.lib.pagesizes import A4, landscape, portrait
from PIL import Image
from reportlab.platypus import SimpleDocTemplate, Image, PageBreak
from reportlab.platypus import PageTemplate, Frame


# ----------------------------------------------------------------------

def create_pdf(filename, path, page, cliptype, imageformat):
    """
    """
    if cliptype == ClipType.ALL:
        imgDoc = canvas.Canvas(filename)  # pagesize=letter
        imgDoc.setPageSize(A4)
        document_width, document_height = A4
    for page in range(page):
        print 'create_pdf', page
        image_file = PIL.Image.open(os.path.join(path, '{0}.{1}.{2}'.format(page, '1', imageformat)))
        image_width, image_height = image_file.size
        if not (image_width > 0 and image_height > 0):
            raise Exception
        image_aspect = image_height / float(image_width)
        print_width = document_width
        print_height = document_width * image_aspect
        imgDoc.drawImage(ImageReader(image_file), document_width - print_width,
                         document_height - print_height, width=print_width,
                         height=print_height, preserveAspectRatio=True)
        # Story.append(Image(image_file, width, height))
        imgDoc.showPage()
        imgDoc.save()
    print "%s created" % filename


# ----------------------------------------------------------------------
if __name__ == "__main__":
    cliptype = ClipType.MARGIN_ONLY
    pdfsavepath = r".\tmp\pdf\484d8037a509648a8e09fc0466b06f38\tongjixuexifangfa{0}.pdf".format(cliptype)
    subimagepath = r".\tmp\pdf\484d8037a509648a8e09fc0466b06f38\subimage{0}".format(cliptype)
    create_pdf(pdfsavepath, subimagepath, 20, cliptype, 'jpg')

img

  • 写回答

1条回答 默认 最新

  • 程序媛一枚~ Python领域新星创作者 2021-08-17 11:15
    关注

    是的,要想写入多张照片,把第40行代码 imgDoc.save()移到for循坏外就可以了哦~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月4日
  • 已采纳回答 8月27日
  • 创建了问题 8月17日

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程