在Python中操作PDF的常見(jiàn)方法小結(jié)
1. 使用PyPDF2庫(kù)進(jìn)行PDF操作
PyPDF2是一個(gè)流行的Python庫(kù),用于處理PDF文件。它允許你合并、拆分、旋轉(zhuǎn)和提取PDF文檔的內(nèi)容。
以下是一些基本的示例代碼:
import PyPDF2
# 合并兩個(gè)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庫(kù)創(chuàng)建PDF
reportlab是一個(gè)強(qiáng)大的PDF生成庫(kù),它允許從頭開(kāi)始創(chuàng)建PDF文檔,包括文本、圖形和表格。
以下是一個(gè)簡(jiǎn)單的例子:
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庫(kù)進(jìn)行PDF渲染
PyMuPDF是一個(gè)用于渲染PDF文件的庫(kù),可以用于提取文本和圖像信息。
以下是一個(gè)簡(jiǎn)單的示例:
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庫(kù)提取文本信息
PDFMiner是一個(gè)用于提取PDF文本的強(qiáng)大庫(kù),它支持高級(jí)的文本提取和布局分析。
以下是一個(gè)簡(jiǎn)單的示例:
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庫(kù)創(chuàng)建PDF文檔
FPDF是一個(gè)輕量級(jí)的Python庫(kù),用于在PDF文檔中添加文本、圖形和頁(yè)面。
以下是一個(gè)簡(jiǎn)單的創(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庫(kù)將HTML轉(zhuǎn)換為PDF
PDFKit是一個(gè)基于wkhtmltopdf工具的Python庫(kù),可以將HTML內(nèi)容轉(zhuǎn)換為PDF文檔。這在需要?jiǎng)討B(tài)生成報(bào)告或?qū)⒕W(wǎng)頁(yè)內(nèi)容保存為PDF時(shí)非常有用。
以下是一個(gè)簡(jiǎn)單的例子:
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頁(yè)面
PyPDF2不僅可以用于合并和拆分PDF,還可以用于對(duì)PDF頁(yè)面進(jìn)行旋轉(zhuǎn)。
以下是一個(gè)旋轉(zhuǎn)PDF頁(yè)面的簡(jiǎn)單示例:
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庫(kù)進(jìn)行PDF合并
PDFMerger是一個(gè)簡(jiǎn)單易用的庫(kù),專(zhuān)門(mén)用于合并PDF文件。
以下是一個(gè)示例:
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等庫(kù)的應(yīng)用。通過(guò)豐富的示例代碼,學(xué)習(xí)了合并、拆分、文本提取、HTML轉(zhuǎn)換、頁(yè)面旋轉(zhuǎn)和PDF合并等常見(jiàn)操作。這些工具和技術(shù)為處理PDF文件提供了靈活而強(qiáng)大的手段,能夠根據(jù)具體需求選擇適當(dāng)?shù)姆椒ā?/p>
無(wú)論是生成報(bào)告、處理文檔還是轉(zhuǎn)換HTML內(nèi)容,Python的生態(tài)系統(tǒng)都提供了多樣化的解決方案。通過(guò)閱讀本文,不僅可以了解每種方法的基本原理,還能夠通過(guò)示例代碼深入理解其實(shí)際應(yīng)用。在處理PDF的日常任務(wù)中,選擇適當(dāng)?shù)墓ぞ吆图夹g(shù)將極大地提高工作效率。
以上就是在Python中操作PDF的常見(jiàn)方法小結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Python操作PDF的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中進(jìn)程和線(xiàn)程的區(qū)別詳解
這篇文章主要介紹了Python中進(jìn)程和線(xiàn)程的區(qū)別詳解,需要的朋友可以參考下2017-10-10
對(duì)Python 中矩陣或者數(shù)組相減的法則詳解
今天小編就為大家分享一篇對(duì)Python 中矩陣或者數(shù)組相減的法則詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
深入分析python數(shù)據(jù)挖掘 Json結(jié)構(gòu)分析
這篇文章通過(guò)實(shí)例給大家分析總結(jié)了python數(shù)據(jù)挖掘以及Json結(jié)構(gòu)分析的相關(guān)知識(shí)點(diǎn),對(duì)此有興趣的朋友參考下。2018-04-04
python實(shí)現(xiàn)圖像隨機(jī)裁剪的示例代碼
這篇文章主要介紹了python實(shí)現(xiàn)圖像隨機(jī)裁剪的示例代碼,幫助大家更好的理解和使用python處理圖片,感興趣的朋友可以了解下2020-12-12
python基礎(chǔ)while循環(huán)及if判斷的實(shí)例講解
下面小編就為大家?guī)?lái)一篇python基礎(chǔ)while循環(huán)及if判斷的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
5分鐘快速掌握Python定時(shí)任務(wù)框架的實(shí)現(xiàn)
這篇文章主要介紹了5分鐘快速掌握 Python 定時(shí)任務(wù)框架,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
解讀requests.session()獲取Cookies全過(guò)程
這篇文章主要介紹了解讀requests.session()獲取Cookies全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

