使用Django将图像转换为PDF吗?

时间:2020-10-14 09:07:00

标签: django django-forms django-views

从用户接收多张图像作为输入,并将它们转换为PDF。我不明白如何在Django中实现它。

2 个答案:

答案 0 :(得分:0)

使用此命令安装软件包

pip install img2pdf

下面是实现:

可以使用img2pdf模块提供的img2pdf.convert()函数将图像转换为pdf字节,然后以wb模式打开并用字节写入pdf文件。

# Python3 program to convert image to pfd 
# using img2pdf library 

# importing necessary libraries 
import img2pdf 
from PIL import Image 
import os 

# storing image path 
img_path = "C:/Users/Admin/Desktop/GfG_images/do_nawab.png"

# storing pdf path 
pdf_path = "C:/Users/Admin/Desktop/GfG_images/file.pdf"

# opening image 
image = Image.open(img_path) 

# converting into chunks using img2pdf 
pdf_bytes = img2pdf.convert(image.filename) 

# opening or creating pdf file 
file = open(pdf_path, "wb") 

# writing pdf files with chunks 
file.write(pdf_bytes) 

# closing image file 
image.close() 

# closing pdf file 
file.close() 

# output 
print("Successfully made pdf file") 

答案 1 :(得分:0)

枕头支持PDF格式。文档可用here

from PIL import Image

img = Image.open('/path/to/image.jpg')
img = img.convert('RGB') //This removes alpha channel from .png images.
img.save('/path/to/image.pdf', format="PDF")