python数学公式pdf文件的转换_python转换文件 多种文件转换为pdf
1.office文件
這里用的是win32com, 需要注意已經安裝的python版本是32位還是64位。
安裝后導入
from win32com.client import Dispatch, constants, gencache, DispatchEx
(1) word轉PDF
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
w = DispatchEx("Word.Application")
doc = w.Documents.Open(docFile, ReadOnly=1)
doc.ExportAsFixedFormat(targetFile, constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
w.Quit(constants.wdDoNotSaveChanges)
(2) excel轉PDF
xlApp = DispatchEx("Excel.Application")
xlApp.Visible = False #進程可見,False是它暗自進行
xlApp.DisplayAlerts = 0 #不跳出來。
books = xlApp.Workbooks.Open(excelFile,False)
books.ExportAsFixedFormat(0, targetFile)
books.Close(False)
xlApp.Quit()
(3) ppt轉PDF
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
p = Dispatch("PowerPoint.Application")
ppt = p.Presentations.Open(pptFile, False, False, False)
ppt.ExportAsFixedFormat(targetFile, 2, PrintRange=None)
p.Quit()
2. 圖片文件
需要安裝PIL 和 reportlab
安裝完導入
from PIL import Image
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
圖片轉PDF
(w, h) = landscape(A4)
c = canvas.Canvas(self.getPdfName(fileName), pagesize = landscape(A4))
(xsize, ysize) = Image.open(fileName).size
ratx = xsize / w
raty = ysize / h
ratxy = xsize / (1.0 * ysize)
if ratx > 1:
ratx = 0.99
if raty > 1:
raty = 0.99
rat = ratx
if ratx < raty:
rat = raty
widthx = w * rat
widthy = h * rat
widthx = widthy * ratxy
posx = (w - widthx) / 2
if posx < 0:
posx = 0
posy = (h - widthy) / 2
if posy < 0:
posy = 0
c.drawImage(fileName, posx, posy, widthx, widthy)
c.showPage()
c.save()
3. html文件
需要安裝pdfkit
安裝后導入
import pdfkit
html轉PDF
options={
'page-size':'Letter',
'margin-top':'0.75in',
'margin-right':'0.75in',
'margin-bottom':'0.75in',
'margin-left':'0.75in',
'encoding':"UTF-8",
'no-outline':None
}
pdfkit.from_file(htmlFile, targetFile, options)
需要注意的是:pdfkit需要和wkhtmltopdf配合使用。
安裝后需要配置環境變量,將wkhtmltopdf.exe所在目錄加上path中。
4. 文本文件
能用記事本等打開的文本文件,如txt文件,也可以用pdfkit工具來轉換成pdf文件。
需要注意的是:
(1) 對于其它格式的文件,可以保存為txt文件之后再轉換,因為有些不能被識別。
(2) 對于較大的文本文件,可以切割成多個文件,分別轉換后,再把生成的多個pdf文件合并成一個pdf文件。
合并pdf文件可以用PyPDF2
安裝后導入
from PyPDF2.pdf import PdfFileWriter, PdfFileReader
合并
pdf_output = PdfFileWriter()
files = []
for pdf in pdfList:
f = open(pdf, 'rb')
files.append(f)
pdf_input = PdfFileReader(f)
# 獲取 pdf 共用多少頁
page_count = pdf_input.getNumPages()
for i in range(page_count):
pdf_output.addPage(pdf_input.getPage(i))
pdf_output.write(open(targetFile, 'wb'))
總結
以上是生活随笔為你收集整理的python数学公式pdf文件的转换_python转换文件 多种文件转换为pdf的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php打包压缩下载多大,php多文件打包
- 下一篇: 6-4 二叉树的非递归遍历 (25分)_