###### tags: `python` # python讀取/修改PDF ## 安裝 ```shell= pip3 install pikepdf ``` ## 複製pdf檔 ```python= from pikepdf import Pdf sample_pdf = Pdf.open('Python連結Arduino.pdf') sample_pdf.save('sample2.pdf') ``` ## 取得pdf檔總頁數 ```python= from pikepdf import Pdf pdf = Pdf.open('Python連結Arduino.pdf') print(len(pdf.pages)) ``` ## 倒轉pdf內容(以頁為單位) ```python= from pikepdf import Pdf pdf = Pdf.open('Python連結Arduino.pdf') pdf.pages.reverse() pdf.save('sample3.pdf') ``` ## 刪除pdf某幾頁的內容 ```python= from pikepdf import Pdf pdf = Pdf.open('Python連結Arduino.pdf') del pdf.pages[1:3] pdf.save('sample3.pdf') ``` ## 合併其他pdf檔的內容(所有檔案內容合併到最後面) ```python= from pikepdf import Pdf pdf1 = Pdf.open('Python連結Arduino.pdf') pdf2 = Pdf.open('頭頸癌食譜.pdf') pdf1.pages.extend(pdf2.pages) # 插入所有內容 pdf1.save('sample3.pdf') pdf1.pages.extend(pdf2.pages[1:2]) # 只插入第2頁的內容 pdf1.save('sample4.pdf') ``` ## 合併指定頁數到指定位置之後 ```python= from pikepdf import Pdf pdf1 = Pdf.open('Python連結Arduino.pdf') pdf2 = Pdf.open('頭頸癌食譜.pdf') pdf1.pages.insert(1, pdf2.pages[0]) pdf1.save('sample3.pdf') ``` ## 以檔案2指定的頁碼內容取代檔案1指定的頁碼內容 ```python= from pikepdf import Pdf pdf1 = Pdf.open('Python連結Arduino.pdf') pdf2 = Pdf.open('頭頸癌食譜.pdf') pdf1.pages[2] = pdf2.pages[1] pdf1.save('sample3.pdf') ``` ## 拆解pdf檔成多個pdf檔 ```python= from pikepdf import Pdf pdf = Pdf.open('Python連結Arduino.pdf') for n, page in enumerate(pdf.pages): dst = Pdf.new() dst.pages.append(page) dst.save('{:02d}.pdf'.format(n)) ``` --------- ## 顯示pdf檔內某一頁的內容 ```python= from pikepdf import Pdf pdf = Pdf.open('Python連結Arduino.pdf') page = pdf.pages[0] print(page.__str__) ``` ## word to pdf ```python= import sys import os import comtypes.client wdFormatPDF = 17 in_file = "test.docx" out_file = "test.pdf" def docx2pdf(in_file, out_file): word = comtypes.client.CreateObject('Word.Application') doc = word.Documents.Open(in_file) doc.SaveAs(out_file, FileFormat=wdFormatPDF) doc.Close() word.Quit() docx2pdf(in_file, out_file) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up