1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python数学公式pdf文件的转换_python转换文件 多种文件转换为pdf

python数学公式pdf文件的转换_python转换文件 多种文件转换为pdf

时间:2022-11-04 08:57:14

相关推荐

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'))

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。