Convert batch images to PDF documents
1 Introduction
Little Diaosi : Brother Yu, please help, please help.
Xiaoyu : What's the matter? It's such a fuss.
Little Diaosi : My goddess told me that if I convert her photo into a PDF, then come and have supper with me.
Xiaoyu : Then you can do it with the watch, and it will be fine if you do business.
Little Diaosi : No way, I am such a serious person, how can I fool my goddess.
Xiaoyu : Damn... you can say that, but I'm too embarrassed to hear it.
Little Diaosi : Don't make trouble. It must be done for me today, no matter what the request is, I will agree.
Xiaoyu : Really?
Little Diaosi : Seriously!
Xiaoyu : OK!
Little Diaosi : Then, start the whole process?
Xiaoyu : Whole.
2. Code example
2.1 installation
Because we want to convert the picture into PDF, we need to use a third-party library, namely: img2pdf.
Therefore, install it first and code it.
pip install img2pdf
For other installation methods, you can refer to these two articles:
- " Python3, choose Python to automatically install third-party libraries, and say goodbye to pip from now on! ! "
- 《Python3: I import all Python libraries with only one line of code in a low-key manner! "
After the installation is complete, you can write code.
2.2 Sheet conversion
# -*- coding:utf-8 -*-
# @Time : 2023-07-09
# @Author : Carl_DJ
'''
实现功能:
单张图片转换成 PDF
'''
# 单张图片转换
import os
import img2pdf
with open("output_demo.pdf", "wb") as file:
file.write(img2pdf.convert([i for i in os.listdir('path to image') if i.endswith(".jpg")]))
2.3 Batch conversion
# -*- coding:utf-8 -*-
# @Time : 2023-07-09
# @Author : Carl_DJ
'''
实现功能:
图片批量转换成 PDF
'''
# 多张图片转换
from fpdf import FPDF
Pdf = FPDF()
list_of_images = ["demo1.jpg", "demo2.jpg","demo3.jpg"]
for i in list_of_images:
Pdf.add_page()
Pdf.image(i,x,y,w,h)
Pdf.output("output_demo.pdf", "F")
3. Summary
Seeing this, today's sharing is over.
Today, I mainly share the tips of the picture station PDF.
This is quite common in practice.
So, master this little trick and let your goddess eat supper with you every day.
I am a small fish :
- CSDN blog expert ;
- Aliyun expert blogger ;
- 51CTO blog expert ;
- 51 certified lecturer, etc .;
- Certified gold interviewer ;
- Job interview and training planner ;
- Certified expert bloggers in several domestic mainstream technical communities ;
- Winners of the first and second prizes in the evaluation of various mainstream products (Alibaba Cloud, etc.) ;
Follow me and take you to learn more, more professional and prefaced Python technology.