python 中 img2pdf 模块实例 Python

已认证 八彩五月 2022-7-30 455

import img2pdf

# opening from filename 从文件名打开
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert('test.jpg'))

# opening from file handle 从文件句柄打开
with open("name.pdf","wb") as f1, open("test.jpg") as f2:
	f1.write(img2pdf.convert(f2))

# using in-memory image data 使用内存中的图像数据
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert("\x89PNG...")

# multiple inputs (variant 1) 多个输入(变体 1)
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert("test1.jpg", "test2.png"))

# multiple inputs (variant 2)
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert(["test1.jpg", "test2.png"]))

# convert all files ending in .jpg inside a directory
#转换目录中所有以 .jpg 结尾的文件
dirname = "/path/to/images"
imgs = []
for fname in os.listdir(dirname):
	if not fname.endswith(".jpg"):
		continue
	path = os.path.join(dirname, fname)
	if os.path.isdir(path):
		continue
	imgs.append(path)
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert(imgs))

# convert all files ending in .jpg in a directory and its subdirectories
#转换目录及其子目录中所有以 .jpg 结尾的文件
dirname = "/path/to/images"
imgs = []
for r, _, f in os.walk(dirname):
	for fname in f:
		if not fname.endswith(".jpg"):
			continue
		imgs.append(os.path.join(r, fname))
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert(imgs))


# convert all files matching a glob
#转换与 glob 匹配的所有文件
import glob
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert(glob.glob("/path/to/*.jpg")))

# ignore invalid rotation values in the input images
#忽略输入图像中的无效旋转值
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert('test.jpg'), rotation=img2pdf.Rotation.ifvalid)

# writing to file descriptor
#写入文件描述符
with open("name.pdf","wb") as f1, open("test.jpg") as f2:
	img2pdf.convert(f2, outputstream=f1)

# specify paper size (A4) 指定纸张尺寸 (A4)
a4inpt = (img2pdf.mm_to_pt(210),img2pdf.mm_to_pt(297))
layout_fun = img2pdf.get_layout_fun(a4inpt)
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))

# use a fixed dpi of 300 instead of reading it from the image
#使用 300 的固定 dpi 而不是从图像中读取它
dpix = dpiy = 300
layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))

# create a PDF/A-1b compliant document by passing an ICC profile
#通过传递 ICC 配置文件创建符合 PDF/A-1b 的文档
with open("name.pdf","wb") as f:
	f.write(img2pdf.convert('test.jpg', pdfa="/usr/share/color/icc/sRGB.icc"))

 xiuno建站一站式服务QQ:312215120
最新回复 (0)
返回
首页
插件
搜索