在Python中操作PDF的常見方法小結(jié)
1. 使用PyPDF2庫進行PDF操作
PyPDF2是一個流行的Python庫,用于處理PDF文件。它允許你合并、拆分、旋轉(zhuǎn)和提取PDF文檔的內(nèi)容。
以下是一些基本的示例代碼:
import PyPDF2
# 合并兩個PDF文件
def merge_pdfs(file1, file2, output):
pdf_writer = PyPDF2.PdfFileWriter()
pdf_reader1 = PyPDF2.PdfFileReader(file1)
pdf_reader2 = PyPDF2.PdfFileReader(file2)
for page_num in range(pdf_reader1.numPages):
page = pdf_reader1.getPage(page_num)
pdf_writer.addPage(page)
for page_num in range(pdf_reader2.numPages):
page = pdf_reader2.getPage(page_num)
pdf_writer.addPage(page)
with open(output, 'wb') as merged_file:
pdf_writer.write(merged_file)
# 拆分PDF文件
def split_pdf(input_file, output_folder):
pdf_reader = PyPDF2.PdfFileReader(input_file)
for page_num in range(pdf_reader.numPages):
pdf_writer = PyPDF2.PdfFileWriter()
page = pdf_reader.getPage(page_num)
pdf_writer.addPage(page)
output_file = f'{output_folder}/page_{page_num + 1}.pdf'
with open(output_file, 'wb') as single_page_file:
pdf_writer.write(single_page_file)
# 調(diào)用示例
merge_pdfs('document1.pdf', 'document2.pdf', 'merged_document.pdf')
split_pdf('large_document.pdf', 'output_folder')
2. 使用reportlab庫創(chuàng)建PDF
reportlab是一個強大的PDF生成庫,它允許從頭開始創(chuàng)建PDF文檔,包括文本、圖形和表格。
以下是一個簡單的例子:
from reportlab.pdfgen import canvas
def create_pdf(output_file):
c = canvas.Canvas(output_file)
c.drawString(72, 800, "Hello, this is a sample PDF created with reportlab.")
c.showPage()
c.save()
# 調(diào)用示例
create_pdf('sample_reportlab.pdf')
3. 使用PyMuPDF庫進行PDF渲染
PyMuPDF是一個用于渲染PDF文件的庫,可以用于提取文本和圖像信息。
以下是一個簡單的示例:
import fitz # PyMuPDF的Python綁定
def extract_text_images(pdf_file):
doc = fitz.open(pdf_file)
for page_num in range(doc.page_count):
page = doc[page_num]
# 提取文本
text = page.get_text("text")
print(f"Text on page {page_num + 1}:\n{text}\n")
# 提取圖像
for img_index, img in enumerate(page.get_images(full=True)):
img_index += 1
base_image = doc.extract_image(img)
image_bytes = base_image["image"]
image_name = f"page_{page_num + 1}_image_{img_index}.png"
with open(image_name, "wb") as image_file:
image_file.write(image_bytes)
# 調(diào)用示例
extract_text_images('document.pdf')
4. 使用PDFMiner庫提取文本信息
PDFMiner是一個用于提取PDF文本的強大庫,它支持高級的文本提取和布局分析。
以下是一個簡單的示例:
from pdfminer.high_level import extract_text
def extract_text_from_pdf(pdf_file):
text = extract_text(pdf_file)
print(f"Text extracted from the PDF:\n{text}")
# 調(diào)用示例
extract_text_from_pdf('document.pdf')
5. 使用FPDF庫創(chuàng)建PDF文檔
FPDF是一個輕量級的Python庫,用于在PDF文檔中添加文本、圖形和頁面。
以下是一個簡單的創(chuàng)建PDF文檔的示例:
from fpdf import FPDF
class PDFGenerator(FPDF):
def header(self):
self.set_font('Arial', 'B', 12)
self.cell(0, 10, 'My PDF Document', 0, 1, 'C')
def chapter_title(self, num, label):
self.set_font('Arial', 'B', 12)
self.cell(0, 10, 'Chapter %d : %s' % (num, label), 0, 1, 'L')
def chapter_body(self, body):
self.set_font('Arial', '', 12)
self.multi_cell(0, 10, body)
# 創(chuàng)建PDF文檔
pdf = PDFGenerator()
pdf.add_page()
pdf.chapter_title(1, 'Introduction')
pdf.chapter_body('This is the introduction to my PDF document.')
pdf.chapter_title(2, 'Chapter 1')
pdf.chapter_body('This is the content of chapter 1.')
# 保存PDF文檔
pdf.output('generated_document.pdf')
6. 使用PDFKit庫將HTML轉(zhuǎn)換為PDF
PDFKit是一個基于wkhtmltopdf工具的Python庫,可以將HTML內(nèi)容轉(zhuǎn)換為PDF文檔。這在需要動態(tài)生成報告或?qū)⒕W(wǎng)頁內(nèi)容保存為PDF時非常有用。
以下是一個簡單的例子:
import pdfkit
def html_to_pdf(html_content, output_pdf):
pdfkit.from_string(html_content, output_pdf)
# 調(diào)用示例
html_content = "<html><body><h1>Hello, PDFKit!</h1><p>This is a sample HTML content.</p></body></html>"
html_to_pdf(html_content, 'html_to_pdf_output.pdf')
7. 使用PyPDF2旋轉(zhuǎn)PDF頁面
PyPDF2不僅可以用于合并和拆分PDF,還可以用于對PDF頁面進行旋轉(zhuǎn)。
以下是一個旋轉(zhuǎn)PDF頁面的簡單示例:
import PyPDF2
def rotate_pdf(input_pdf, output_pdf, rotation_angle):
pdf_writer = PyPDF2.PdfFileWriter()
pdf_reader = PyPDF2.PdfFileReader(input_pdf)
for page_num in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
page.rotateClockwise(rotation_angle)
pdf_writer.addPage(page)
with open(output_pdf, 'wb') as rotated_file:
pdf_writer.write(rotated_file)
# 調(diào)用示例
rotate_pdf('document.pdf', 'rotated_document.pdf', 90)
8. 使用PDFMerger庫進行PDF合并
PDFMerger是一個簡單易用的庫,專門用于合并PDF文件。
以下是一個示例:
from PyPDF2 import PdfMerger
def merge_pdfs_with_pdfmerger(files, output_file):
merger = PdfMerger()
for pdf_file in files:
merger.append(pdf_file)
merger.write(output_file)
merger.close()
# 調(diào)用示例
pdf_files = ['file1.pdf', 'file2.pdf', 'file3.pdf']
merge_pdfs_with_pdfmerger(pdf_files, 'merged_files.pdf')
總結(jié)
在本文中,我們分享了Python中操作PDF的多種方法,涵蓋了PyPDF2、reportlab、PyMuPDF、PDFMiner、FPDF、PDFKit、PyPDF2、PDFMerger等庫的應(yīng)用。通過豐富的示例代碼,學(xué)習(xí)了合并、拆分、文本提取、HTML轉(zhuǎn)換、頁面旋轉(zhuǎn)和PDF合并等常見操作。這些工具和技術(shù)為處理PDF文件提供了靈活而強大的手段,能夠根據(jù)具體需求選擇適當(dāng)?shù)姆椒ā?/p>
無論是生成報告、處理文檔還是轉(zhuǎn)換HTML內(nèi)容,Python的生態(tài)系統(tǒng)都提供了多樣化的解決方案。通過閱讀本文,不僅可以了解每種方法的基本原理,還能夠通過示例代碼深入理解其實際應(yīng)用。在處理PDF的日常任務(wù)中,選擇適當(dāng)?shù)墓ぞ吆图夹g(shù)將極大地提高工作效率。
以上就是在Python中操作PDF的常見方法小結(jié)的詳細內(nèi)容,更多關(guān)于Python操作PDF的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
深入分析python數(shù)據(jù)挖掘 Json結(jié)構(gòu)分析
這篇文章通過實例給大家分析總結(jié)了python數(shù)據(jù)挖掘以及Json結(jié)構(gòu)分析的相關(guān)知識點,對此有興趣的朋友參考下。2018-04-04
python基礎(chǔ)while循環(huán)及if判斷的實例講解
下面小編就為大家?guī)硪黄猵ython基礎(chǔ)while循環(huán)及if判斷的實例講解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
5分鐘快速掌握Python定時任務(wù)框架的實現(xiàn)
這篇文章主要介紹了5分鐘快速掌握 Python 定時任務(wù)框架,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
解讀requests.session()獲取Cookies全過程
這篇文章主要介紹了解讀requests.session()獲取Cookies全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

