Python自動化處理PDF文檔的操作完整指南
PDF(Portable Document Format,便攜式文檔格式)是一種廣泛使用的文檔格式,具有跨平臺、穩(wěn)定性好、安全性高等特點(diǎn)。在辦公自動化中,PDF文檔處理是一項(xiàng)常見需求。本文將介紹如何使用Python實(shí)現(xiàn)PDF文檔的自動化處理,包括讀寫、合并拆分、提取內(nèi)容、添加水印等操作。
使用pymupdf讀寫PDF文件
基本概念
一個(gè)真實(shí)的PDF文件主要由四大部分構(gòu)成,分別是文件頭(Header)、文件主體(Body)、交叉引用表(Cross-Reference Table)和文件尾(Trailer)。了解這些基本結(jié)構(gòu)有助于我們更好地處理PDF文件。
安裝pymupdf
pip install pymupdf
提取文本內(nèi)容
pymupdf庫(也稱為fitz)可以輕松實(shí)現(xiàn)對PDF文件的讀寫操作。以下是提取PDF文本內(nèi)容的示例:
import fitz # pymupdf的導(dǎo)入名稱是fitz
def extract_text_from_pdf(pdf_path):
"""從PDF文件中提取所有文本內(nèi)容"""
# 打開PDF文件
doc = fitz.open(pdf_path)
# 創(chuàng)建一個(gè)空字符串用于存儲文本內(nèi)容
text = ""
# 遍歷每一頁
for page_num in range(len(doc)):
# 獲取當(dāng)前頁面
page = doc[page_num]
# 提取文本
page_text = page.get_text()
# 添加頁碼信息和頁面文本
text += f"\n--- 第 {page_num + 1} 頁 ---\n"
text += page_text
# 關(guān)閉文檔
doc.close()
return text
# 使用示例
pdf_path = "example.pdf" # 替換為實(shí)際的PDF文件路徑
try:
extracted_text = extract_text_from_pdf(pdf_path)
print("提取的文本內(nèi)容:")
print(extracted_text[:500] + "..." if len(extracted_text) > 500 else extracted_text)
# 將提取的文本保存到文件
with open("extracted_text.txt", "w", encoding="utf-8") as f:
f.write(extracted_text)
print("文本已保存到 extracted_text.txt")
except Exception as e:
print(f"提取文本時(shí)出錯(cuò): {e}")
提取圖像
一個(gè)PDF文件通常會包含圖像元素,圖像作為PDF文件中的對象也會記錄在交叉引用表中。在pymupdf庫中,可以通過相應(yīng)的方法獲取交叉引用表中記錄的對象ID編號,并將其稱為xref整數(shù)。
import fitz
import os
def extract_images_from_pdf(pdf_path, output_folder="extracted_images"):
"""從PDF文件中提取所有圖像"""
# 確保輸出文件夾存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 打開PDF文件
doc = fitz.open(pdf_path)
# 用于記錄提取的圖像數(shù)量
image_count = 0
# 遍歷每一頁
for page_num in range(len(doc)):
# 獲取當(dāng)前頁面
page = doc[page_num]
# 獲取頁面上的圖像列表
image_list = page.get_images()
# 遍歷圖像列表
for img_index, img in enumerate(image_list):
# 獲取圖像的xref
xref = img[0]
# 獲取圖像信息
base_image = doc.extract_image(xref)
image_bytes = base_image["image"]
image_ext = base_image["ext"]
# 生成輸出文件名
output_filename = f"{output_folder}/page{page_num + 1}_img{img_index + 1}.{image_ext}"
# 保存圖像
with open(output_filename, "wb") as f:
f.write(image_bytes)
image_count += 1
# 關(guān)閉文檔
doc.close()
return image_count
# 使用示例
pdf_path = "example.pdf" # 替換為實(shí)際的PDF文件路徑
try:
num_images = extract_images_from_pdf(pdf_path)
print(f"成功提取了 {num_images} 張圖像到 'extracted_images' 文件夾")
except Exception as e:
print(f"提取圖像時(shí)出錯(cuò): {e}")
添加水印
import fitz
def add_watermark_to_pdf(input_pdf, output_pdf, watermark_text):
"""為PDF文件添加文字水印"""
# 打開PDF文件
doc = fitz.open(input_pdf)
# 遍歷每一頁
for page_num in range(len(doc)):
# 獲取當(dāng)前頁面
page = doc[page_num]
# 獲取頁面尺寸
rect = page.rect
# 創(chuàng)建一個(gè)透明的水印文本
# 設(shè)置字體大小、顏色和透明度
text_color = (0.5, 0.5, 0.5) # 灰色
alpha = 0.3 # 透明度
fontsize = 24
# 在頁面中心添加水印
tw = fitz.TextWriter(rect)
tw.append((rect.width/2, rect.height/2), watermark_text, fontsize=fontsize, color=text_color)
tw.write_text(page, opacity=alpha)
# 保存修改后的PDF
doc.save(output_pdf)
doc.close()
return output_pdf
# 使用示例
input_pdf = "example.pdf" # 替換為實(shí)際的PDF文件路徑
output_pdf = "watermarked.pdf"
watermark_text = "機(jī)密文件 - 請勿外傳"
try:
result_pdf = add_watermark_to_pdf(input_pdf, output_pdf, watermark_text)
print(f"已成功添加水印并保存為: {result_pdf}")
except Exception as e:
print(f"添加水印時(shí)出錯(cuò): {e}")
使用pdfplumber提取PDF中表格
PDF文件中通常會有表格元素,如果想提取表格元素中的內(nèi)容,可以使用pdfplumber庫。
安裝pdfplumber
pip install pdfplumber
提取表格數(shù)據(jù)
pdfplumber庫提供的extract_table方法可以輕松提取PDF文件中某頁的所有表格,對于缺少邊界的表格,pdfplumber庫會利用文本位置信息進(jìn)行猜測,從而定位出不可見邊界的位置。
import pdfplumber
import pandas as pd
def extract_tables_from_pdf(pdf_path):
"""從PDF文件中提取所有表格"""
# 打開PDF文件
with pdfplumber.open(pdf_path) as pdf:
all_tables = []
# 遍歷每一頁
for page_num, page in enumerate(pdf.pages):
# 提取表格
tables = page.extract_tables()
if tables:
print(f"在第 {page_num + 1} 頁找到 {len(tables)} 個(gè)表格")
# 處理每個(gè)表格
for table_num, table in enumerate(tables):
# 創(chuàng)建DataFrame
df = pd.DataFrame(table[1:], columns=table[0])
# 添加頁碼和表格編號信息
df['頁碼'] = page_num + 1
df['表格編號'] = table_num + 1
all_tables.append(df)
else:
print(f"在第 {page_num + 1} 頁沒有找到表格")
# 如果找到了表格,合并所有表格
if all_tables:
combined_df = pd.concat(all_tables, ignore_index=True)
return combined_df
else:
return None
# 使用示例
pdf_path = "example_with_tables.pdf" # 替換為包含表格的PDF文件路徑
try:
tables_df = extract_tables_from_pdf(pdf_path)
if tables_df is not None:
print("\n提取的表格數(shù)據(jù):")
print(tables_df.head())
# 將表格數(shù)據(jù)保存到Excel文件
excel_path = "extracted_tables.xlsx"
tables_df.to_excel(excel_path, index=False)
print(f"表格數(shù)據(jù)已保存到: {excel_path}")
else:
print("未在PDF中找到任何表格")
except Exception as e:
print(f"提取表格時(shí)出錯(cuò): {e}")
使用PyPDF2操控PDF文件
PyPDF2是一個(gè)流行的Python庫,用于處理PDF文件。它能完成PDF文件的信息提取、拆分、合并、頁面裁剪、加密/解密等多種操作。
安裝PyPDF2
pip install PyPDF2
合并PDF文件
from PyPDF2 import PdfMerger
def merge_pdfs(pdf_files, output_path):
"""合并多個(gè)PDF文件"""
merger = PdfMerger()
# 添加每個(gè)PDF文件
for pdf in pdf_files:
try:
merger.append(pdf)
print(f"已添加: {pdf}")
except Exception as e:
print(f"添加 {pdf} 時(shí)出錯(cuò): {e}")
# 保存合并后的PDF
merger.write(output_path)
merger.close()
return output_path
# 使用示例
pdf_files = ["document1.pdf", "document2.pdf", "document3.pdf"] # 替換為實(shí)際的PDF文件路徑
output_path = "merged_document.pdf"
try:
result_path = merge_pdfs(pdf_files, output_path)
print(f"已成功合并PDF文件并保存為: {result_path}")
except Exception as e:
print(f"合并PDF文件時(shí)出錯(cuò): {e}")
拆分PDF文件
from PyPDF2 import PdfReader, PdfWriter
import os
def split_pdf(input_pdf, output_folder="split_pages"):
"""將PDF文件拆分為單頁文件"""
# 確保輸出文件夾存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 打開PDF文件
reader = PdfReader(input_pdf)
total_pages = len(reader.pages)
# 獲取文件名(不含擴(kuò)展名)
base_name = os.path.splitext(os.path.basename(input_pdf))[0]
# 拆分每一頁
for page_num in range(total_pages):
writer = PdfWriter()
writer.add_page(reader.pages[page_num])
# 生成輸出文件名
output_filename = f"{output_folder}/{base_name}_page_{page_num + 1}.pdf"
# 保存單頁P(yáng)DF
with open(output_filename, "wb") as output_file:
writer.write(output_file)
print(f"已保存第 {page_num + 1} 頁到: {output_filename}")
return total_pages
# 使用示例
input_pdf = "example.pdf" # 替換為實(shí)際的PDF文件路徑
try:
num_pages = split_pdf(input_pdf)
print(f"已成功將 {input_pdf} 拆分為 {num_pages} 個(gè)單頁P(yáng)DF文件")
except Exception as e:
print(f"拆分PDF文件時(shí)出錯(cuò): {e}")
加密和解密PDF
from PyPDF2 import PdfReader, PdfWriter
def encrypt_pdf(input_pdf, output_pdf, password):
"""加密PDF文件"""
reader = PdfReader(input_pdf)
writer = PdfWriter()
# 復(fù)制所有頁面
for page in reader.pages:
writer.add_page(page)
# 設(shè)置密碼和加密選項(xiàng)
writer.encrypt(password)
# 保存加密后的PDF
with open(output_pdf, "wb") as output_file:
writer.write(output_file)
return output_pdf
def decrypt_pdf(input_pdf, output_pdf, password):
"""解密PDF文件"""
reader = PdfReader(input_pdf)
# 檢查PDF是否加密
if reader.is_encrypted:
# 嘗試使用密碼解密
if reader.decrypt(password) != 1:
raise ValueError("密碼不正確")
else:
print("警告: 輸入的PDF文件未加密")
writer = PdfWriter()
# 復(fù)制所有頁面
for page in reader.pages:
writer.add_page(page)
# 保存解密后的PDF
with open(output_pdf, "wb") as output_file:
writer.write(output_file)
return output_pdf
# 使用示例 - 加密
input_pdf = "example.pdf" # 替換為實(shí)際的PDF文件路徑
encrypted_pdf = "encrypted_document.pdf"
password = "secure123" # 設(shè)置密碼
try:
result_path = encrypt_pdf(input_pdf, encrypted_pdf, password)
print(f"已成功加密PDF文件并保存為: {result_path}")
except Exception as e:
print(f"加密PDF文件時(shí)出錯(cuò): {e}")
# 使用示例 - 解密
decrypted_pdf = "decrypted_document.pdf"
try:
result_path = decrypt_pdf(encrypted_pdf, decrypted_pdf, password)
print(f"已成功解密PDF文件并保存為: {result_path}")
except Exception as e:
print(f"解密PDF文件時(shí)出錯(cuò): {e}")
使用wkhtmltopdf將網(wǎng)頁轉(zhuǎn)為PDF
wkhtmltopdf是一個(gè)開源工具,可以將HTML頁面轉(zhuǎn)換為PDF文檔。它可以通過命令行直接使用,也可以通過Python的pdfkit庫進(jìn)行調(diào)用。
安裝wkhtmltopdf和pdfkit
首先,需要安裝wkhtmltopdf工具:
- 在macOS上:
brew install wkhtmltopdf - 在Windows上:從官方網(wǎng)站下載安裝程序
- 在Linux上:
sudo apt-get install wkhtmltopdf(Ubuntu/Debian)或sudo yum install wkhtmltopdf(CentOS/RHEL)
然后,安裝pdfkit Python庫:
pip install pdfkit
將網(wǎng)頁轉(zhuǎn)換為PDF
import pdfkit
def url_to_pdf(url, output_pdf):
"""將URL指向的網(wǎng)頁轉(zhuǎn)換為PDF"""
try:
# 配置wkhtmltopdf路徑(如果不在系統(tǒng)PATH中)
# config = pdfkit.configuration(wkhtmltopdf='/path/to/wkhtmltopdf')
# pdfkit.from_url(url, output_pdf, configuration=config)
# 如果wkhtmltopdf在系統(tǒng)PATH中
pdfkit.from_url(url, output_pdf)
print(f"已成功將 {url} 轉(zhuǎn)換為PDF: {output_pdf}")
return output_pdf
except Exception as e:
print(f"轉(zhuǎn)換網(wǎng)頁到PDF時(shí)出錯(cuò): {e}")
return None
def html_to_pdf(html_file, output_pdf):
"""將HTML文件轉(zhuǎn)換為PDF"""
try:
pdfkit.from_file(html_file, output_pdf)
print(f"已成功將 {html_file} 轉(zhuǎn)換為PDF: {output_pdf}")
return output_pdf
except Exception as e:
print(f"轉(zhuǎn)換HTML文件到PDF時(shí)出錯(cuò): {e}")
return None
def html_string_to_pdf(html_content, output_pdf):
"""將HTML字符串轉(zhuǎn)換為PDF"""
try:
pdfkit.from_string(html_content, output_pdf)
print(f"已成功將HTML內(nèi)容轉(zhuǎn)換為PDF: {output_pdf}")
return output_pdf
except Exception as e:
print(f"轉(zhuǎn)換HTML字符串到PDF時(shí)出錯(cuò): {e}")
return None
# 使用示例 - 從URL創(chuàng)建PDF
url = "https://www.example.com" # 替換為實(shí)際的URL
output_pdf = "webpage.pdf"
url_to_pdf(url, output_pdf)
# 使用示例 - 從HTML文件創(chuàng)建PDF
html_file = "example.html" # 替換為實(shí)際的HTML文件路徑
output_pdf = "from_html_file.pdf"
html_to_pdf(html_file, output_pdf)
# 使用示例 - 從HTML字符串創(chuàng)建PDF
html_content = """<!DOCTYPE html>
<html>
<head>
<title>測試頁面</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>這是一個(gè)由HTML字符串生成的PDF文檔。</p>
</body>
</html>"""
output_pdf = "from_html_string.pdf"
html_string_to_pdf(html_content, output_pdf)
將網(wǎng)頁轉(zhuǎn)換為圖片
除了轉(zhuǎn)換為PDF,wkhtmltoimage工具(wkhtmltopdf的一部分)還可以將網(wǎng)頁轉(zhuǎn)換為圖片:
import subprocess
def url_to_image(url, output_image):
"""將URL指向的網(wǎng)頁轉(zhuǎn)換為圖片"""
try:
# 執(zhí)行wkhtmltoimage命令
command = ["wkhtmltoimage", url, output_image]
subprocess.run(command, check=True)
print(f"已成功將 {url} 轉(zhuǎn)換為圖片: {output_image}")
return output_image
except subprocess.CalledProcessError as e:
print(f"轉(zhuǎn)換網(wǎng)頁到圖片時(shí)出錯(cuò): {e}")
return None
except Exception as e:
print(f"發(fā)生錯(cuò)誤: {e}")
return None
# 使用示例
url = "https://www.example.com" # 替換為實(shí)際的URL
output_image = "webpage.jpg"
url_to_image(url, output_image)
從Word/Excel導(dǎo)出PDF報(bào)告
從Word導(dǎo)出PDF
from docx2pdf import convert
def word_to_pdf(input_docx, output_pdf=None):
"""將Word文檔轉(zhuǎn)換為PDF"""
try:
# 如果未指定輸出PDF路徑,則使用相同的文件名但擴(kuò)展名為.pdf
if output_pdf is None:
output_pdf = input_docx.replace(".docx", ".pdf")
# 轉(zhuǎn)換Word文檔為PDF
convert(input_docx, output_pdf)
print(f"已成功將 {input_docx} 轉(zhuǎn)換為PDF: {output_pdf}")
return output_pdf
except Exception as e:
print(f"轉(zhuǎn)換Word到PDF時(shí)出錯(cuò): {e}")
return None
# 使用示例
input_docx = "example.docx" # 替換為實(shí)際的Word文檔路徑
word_to_pdf(input_docx)
從Excel導(dǎo)出PDF
import win32com.client
import os
def excel_to_pdf(input_excel, output_pdf=None):
"""將Excel文件轉(zhuǎn)換為PDF(僅適用于Windows系統(tǒng))"""
try:
# 如果未指定輸出PDF路徑,則使用相同的文件名但擴(kuò)展名為.pdf
if output_pdf is None:
output_pdf = input_excel.replace(".xlsx", ".pdf").replace(".xls", ".pdf")
# 獲取絕對路徑
input_excel = os.path.abspath(input_excel)
output_pdf = os.path.abspath(output_pdf)
# 創(chuàng)建Excel應(yīng)用程序?qū)嵗?
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
# 打開Excel文件
workbook = excel.Workbooks.Open(input_excel)
# 將工作簿導(dǎo)出為PDF
workbook.ExportAsFixedFormat(0, output_pdf)
# 關(guān)閉工作簿和Excel應(yīng)用程序
workbook.Close()
excel.Quit()
print(f"已成功將 {input_excel} 轉(zhuǎn)換為PDF: {output_pdf}")
return output_pdf
except Exception as e:
print(f"轉(zhuǎn)換Excel到PDF時(shí)出錯(cuò): {e}")
return None
# 使用示例(僅適用于Windows系統(tǒng))
# input_excel = "example.xlsx" # 替換為實(shí)際的Excel文件路徑
# excel_to_pdf(input_excel)
實(shí)際應(yīng)用場景
場景一:批量處理發(fā)票PDF
import os
import fitz
import re
from datetime import datetime
import pandas as pd
def process_invoice_pdfs(invoice_folder, output_excel):
"""批量處理發(fā)票PDF,提取關(guān)鍵信息并生成匯總表"""
# 存儲提取的發(fā)票信息
invoices_data = []
# 獲取文件夾中的所有PDF文件
pdf_files = [f for f in os.listdir(invoice_folder) if f.lower().endswith('.pdf')]
for pdf_file in pdf_files:
pdf_path = os.path.join(invoice_folder, pdf_file)
print(f"處理: {pdf_path}")
try:
# 打開PDF文件
doc = fitz.open(pdf_path)
# 提取第一頁文本(假設(shè)發(fā)票信息在第一頁)
text = doc[0].get_text()
# 使用正則表達(dá)式提取關(guān)鍵信息
# 注意:以下正則表達(dá)式需要根據(jù)實(shí)際發(fā)票格式進(jìn)行調(diào)整
invoice_number = re.search(r'發(fā)票號碼[::](\s*\d+)', text)
invoice_number = invoice_number.group(1).strip() if invoice_number else "未知"
invoice_date = re.search(r'開票日期[::](\s*\d{4}[年/-]\d{1,2}[月/-]\d{1,2})', text)
invoice_date = invoice_date.group(1).strip() if invoice_date else "未知"
amount = re.search(r'金額[::]\s*¥?\s*(\d+\.\d{2})', text)
amount = amount.group(1).strip() if amount else "0.00"
# 將信息添加到列表
invoices_data.append({
'文件名': pdf_file,
'發(fā)票號碼': invoice_number,
'開票日期': invoice_date,
'金額': float(amount),
})
# 關(guān)閉文檔
doc.close()
except Exception as e:
print(f"處理 {pdf_file} 時(shí)出錯(cuò): {e}")
# 創(chuàng)建DataFrame并保存為Excel
if invoices_data:
df = pd.DataFrame(invoices_data)
# 添加總計(jì)行
total_amount = df['金額'].sum()
df.loc[len(df)] = ['總計(jì)', '', '', total_amount]
# 保存為Excel
df.to_excel(output_excel, index=False)
print(f"已成功處理 {len(invoices_data)} 個(gè)發(fā)票PDF并保存匯總表到: {output_excel}")
return output_excel
else:
print("未找到有效的發(fā)票PDF文件")
return None
# 使用示例
invoice_folder = "invoices" # 替換為實(shí)際的發(fā)票PDF文件夾路徑
output_excel = "invoice_summary.xlsx"
# process_invoice_pdfs(invoice_folder, output_excel)
場景二:自動生成PDF報(bào)告
import pandas as pd
import matplotlib.pyplot as plt
import fitz
import os
from datetime import datetime
def generate_sales_report_pdf(sales_data_excel, output_pdf):
"""根據(jù)銷售數(shù)據(jù)生成PDF報(bào)告"""
# 讀取銷售數(shù)據(jù)
df = pd.read_excel(sales_data_excel)
# 創(chuàng)建臨時(shí)HTML文件
html_path = "temp_report.html"
# 生成圖表
plt.figure(figsize=(10, 6))
df.groupby('產(chǎn)品')['銷售額'].sum().plot(kind='bar')
plt.title('各產(chǎn)品銷售額對比')
plt.ylabel('銷售額')
plt.tight_layout()
chart_path = "sales_chart.png"
plt.savefig(chart_path)
# 計(jì)算匯總數(shù)據(jù)
total_sales = df['銷售額'].sum()
avg_sales = df['銷售額'].mean()
max_product = df.loc[df['銷售額'].idxmax()]['產(chǎn)品']
max_sales = df['銷售額'].max()
# 生成HTML報(bào)告
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>銷售數(shù)據(jù)報(bào)告</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 40px; }}
h1 {{ color: #2c3e50; text-align: center; }}
.report-date {{ text-align: right; color: #7f8c8d; }}
.summary {{ background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin: 20px 0; }}
table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }}
th {{ background-color: #3498db; color: white; }}
tr:hover {{ background-color: #f5f5f5; }}
.chart {{ text-align: center; margin: 30px 0; }}
.footer {{ text-align: center; margin-top: 50px; font-size: 12px; color: #7f8c8d; }}
</style>
</head>
<body>
<div class="report-date">生成日期: {datetime.now().strftime('%Y年%m月%d日')}</div>
<h1>銷售數(shù)據(jù)報(bào)告</h1>
<div class="summary">
<h2>銷售摘要</h2>
<p>總銷售額: ¥{total_sales:,.2f}</p>
<p>平均銷售額: ¥{avg_sales:,.2f}</p>
<p>最暢銷產(chǎn)品: {max_product} (¥{max_sales:,.2f})</p>
</div>
<h2>銷售數(shù)據(jù)明細(xì)</h2>
<table>
<tr>
<th>產(chǎn)品</th>
<th>銷售量</th>
<th>銷售額</th>
<th>日期</th>
</tr>
"""
# 添加表格數(shù)據(jù)
for _, row in df.iterrows():
html_content += f"""
<tr>
<td>{row['產(chǎn)品']}</td>
<td>{row['銷售量']}</td>
<td>¥{row['銷售額']:,.2f}</td>
<td>{row['日期']}</td>
</tr>
"""
# 添加圖表和頁腳
html_content += f"""
</table>
<div class="chart">
<h2>銷售圖表</h2>
<img src="{chart_path}" alt="銷售數(shù)據(jù)圖表" style="max-width: 100%;">
</div>
<div class="footer">
<p>此報(bào)告由Python自動生成 | 僅供內(nèi)部使用</p>
</div>
</body>
</html>
"""
# 保存HTML文件
with open(html_path, "w", encoding="utf-8") as f:
f.write(html_content)
# 將HTML轉(zhuǎn)換為PDF
import pdfkit
try:
pdfkit.from_file(html_path, output_pdf)
print(f"已成功生成銷售報(bào)告PDF: {output_pdf}")
# 清理臨時(shí)文件
os.remove(html_path)
os.remove(chart_path)
return output_pdf
except Exception as e:
print(f"生成PDF報(bào)告時(shí)出錯(cuò): {e}")
return None
# 使用示例
sales_data_excel = "sales_data.xlsx" # 替換為實(shí)際的銷售數(shù)據(jù)Excel文件路徑
output_pdf = "sales_report.pdf"
# generate_sales_report_pdf(sales_data_excel, output_pdf)
通過以上代碼示例和應(yīng)用場景,你可以輕松掌握Python PDF文檔自動化的各種技巧,大幅提高工作效率。無論是提取文本和圖像、合并拆分PDF、添加水印,還是從網(wǎng)頁或Office文檔生成PDF報(bào)告,Python都能幫你輕松應(yīng)對。
以上就是Python自動化處理PDF文檔的操作完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python自動化處理PDF的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python+PyQt5實(shí)現(xiàn)開發(fā)Memcached客戶端
這篇文章主要介紹了如何使用Python和PyQt5來制作一個(gè)Memcached客戶端,以便我們可以輕松地與Memcached服務(wù)器進(jìn)行交互,感興趣的小伙伴可以了解一下2023-06-06
五分鐘學(xué)會怎么用python做一個(gè)簡單的貪吃蛇
這篇文章主要介紹了五分鐘學(xué)會怎么用python做一個(gè)簡單的貪吃蛇,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01
Python實(shí)現(xiàn)讀取Excel表數(shù)據(jù)并轉(zhuǎn)為JSON格式文件
這篇文章主要為大家詳細(xì)介紹了Python如何使用pandas庫讀取Excel表并將其轉(zhuǎn)為JSON格式文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考下2025-04-04
python使用PyCharm進(jìn)行遠(yuǎn)程開發(fā)和調(diào)試

