可以使用 pdfkit
功能:
1.wkhtmltopdf主要用于HTML生成PDF。
2.pdfkit是基于wkhtmltopdf的python封装,支持URL,本地文件,文本内容到PDF的转换,其最终还是调用wkhtmltopdf命令。是目前接触到的python生成pdf效果较好的。
‘贰’ python怎么转成pdf
方法一:使用虚拟打印机pdf factory即可,而且其他格式文件只要是能够打印,选择这个虚拟打印机,都可以做成PDF文件,很简单实用;
方法二:用其他虚拟打印机转成PDF文件。
方法三:使用专门的转换软件,把文件转成PDF文件。
‘叁’ python 除了reportlab还有什么模块可以生成pdf文件,并且支持简单的布局设计呢
这次我们用循环实现了一个Mandelbrot图形的计算。在《xialulee大战pythonchallenge—...下
‘肆’ python 怎么将数据整合生成pdf
pdf.py文件如下:
#!/usr/bin/python
from reportlab.pdfgen import canvas
def hello():
c = canvas.Canvas("helloworld.pdf")
c.drawString(100,100,"Hello,World")
c.showPage()
c.save()
hello()
diskreport.py文件如下:
#!/usr/bin/env python
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
def disk_report():
p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE)
# print p.stdout.readlines()
return p.stdout.readlines()
def create_pdf(input, output="disk_report.pdf"):
now = datetime.datetime.today()
date = now.strftime("%h %d %Y %H:%M:%S")
c = canvas.Canvas(output)
textobject = c.beginText()
textobject.setTextOrigin(inch, 11*inch)
textobject.textLines('''Disk Capcity Report: %s''' %date)
for line in input:
textobject.textLine(line.strip())
c.drawText(textobject)
c.showPage()
c.save()
report = disk_report()
create_pdf(report)
‘伍’ Python可以用来自动化办公 实现批量Word转pdf吗
这里需要导入几个模块
from win32com.client import Dispatch # 没有的话输入pip install pywin32命令 即可安装
from os import walk
import os
os是用于文件处理常用的模块,至于Dispatch,它是提供了一个接口, win32提供了多种word转换为其他文件的接口,其中FileFormat=17是转换为pdf格式.
之后转换文件逻辑也很简单,首先需要提取出文件名,word文件的后缀是doc或docx,那么将后缀名替换为pdf即可转换,这里用到replace方法,即replace(‘docx’,‘pdf’).replace(‘doc’,‘pdf’)因为有可能后缀是doc,所以需要2次判断。
值得注意的是,转换的文件夹事先要存在,否则会报错误。
下面是项目的源代码
复制代码
from win32com.client import Dispatch # pip install pywin32
from os import walk
import os
wdFormatPDF = 17 # win32提供了多种word转换为其他文件的接口,其中FileFormat=17是转换为pdf
def doc2pdf(input_file, input_file_name, output_dir):
try:
word = Dispatch('Word.Application')
doc = word.Documents.Open(input_file)
except Exception as e:
print("word无法打开, 发生如下错误:\n{}".format(e))
try:
pdf_file_name = input_file_name.replace(".docx", ".pdf").replace(".doc", ".pdf")
pdf_file = os.path.join(output_dir, pdf_file_name)
doc.SaveAs(pdf_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
print("成功转换\"{}\"".format(input_file_name))
print()
except Exception as e:
print("文件保存失败, 发生如下错误:\n{}".format(e))
if __name__ == "__main__":
path_in=input("请输入word文件夹的路径(绝对路径) 要保证存在 建议复制粘贴")
path_out=input("请输入pdf文件夹的路径(绝对路径) 要保证存在 建议复制粘贴")
doc_files = []
directory = path_in# word文件夹
output_dir =path_out # pdf文件夹
for root, _, filenames in walk(directory): # 第2个返回值是dirs, 用不上使用_占位
for file in filenames:
if file.endswith(".doc") or file.endswith(".docx"):
print("转换{}中......".format(file))
doc2pdf(os.path.join(root, file), file, output_dir)
复制代码
‘陆’ 怎么用python批量将ppt转换成pdf
打开office转换器
选择批量转换
选中文件后
点击需要转换的类型
然后点击确定
‘柒’ VBA 或 python 如何批量将JPG文件转PDF
# -*- coding:utf-8 -*-
#!/usr/bin/env python
import os
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from tkinter import *
import time
# 图片文件名称列表
IMAGEFILES = []
class pdfTk(object):
def __init__(self):
'''用于生成主界面用于填写'''
self.top = Tk()
self.sw = self.top.winfo_screenwidth()
self.sh = self.top.winfo_screenheight()
self.topw = 500
self.toph = 200
self.top.title('图片转pdf生成器')
self.top.geometry("%dx%d+%d+%d" % (self.topw, self.toph, (self.sw - self.topw) / 2, (self.sh - self.toph) / 2))
self._DIRPATH = StringVar(self.top)
self.emptfmone = Frame(self.top, height=50)
self.emptfmone.pack()
self.dirfm = Frame(self.top)
self.descriptLabel = Label(self.dirfm, width=4, text='路径:')
self.descriptLabel.pack(side=LEFT)
self.dirn = Entry(self.dirfm, width=50, textvariable=self._DIRPATH)
#self.dirn.bind('<Return>', self.setPath)
self.dirn.pack(side=LEFT)
self.dirfm.pack()
self.emptfmtwo = Frame(self.top, height=30)
self.emptfmtwo.pack()
self.btnfm = Frame(self.top)
self.converBtn = Button(self.btnfm, width=10, text='生成PDF', command=self.doneAnyThing,
activeforeground='white', activebackground='blue')
self.quitBtn = Button(self.btnfm, width=10, text='退出', command=self.top.quit, activeforeground='white',
activebackground='blue')
self.converBtn.pack(side=LEFT, padx=10)
self.quitBtn.pack(side=LEFT, padx=10)
self.btnfm.pack()
def doneAnyThing(self):
self.getListImages(self._DIRPATH.get())
pdfFile = self.converPath(self._DIRPATH.get()) + self.dateStr() + ".pdf"
self.convertpdf(pdfFile)
def convertpdf(self, pdfFile):
'''多个图片合成一个pdf文件'''
(w, h) = landscape(A4) #
cv = canvas.Canvas(pdfFile, pagesize=landscape(A4))
for imagePath in IMAGEFILES:
cv.drawImage(imagePath, 0, 0, w, h)
cv.showPage()
cv.save()
def getListImages(self, dirPath):
'''读取指定文件夹下所有的JPEG图片,存入列表'''
if dirPath is None or len(dirPath) == 0:
raise ValueError('dirPath不能为空,该值为存放图片的具体路径文件夹!')
if os.path.isfile(dirPath):
raise ValueError('dirPath不能为具体文件,该值为存放图片的具体路径文件夹!')
if os.path.isdir(dirPath):
for imageName in os.listdir(dirPath):
if imageName.endswith('.jpg') or imageName.endswith('.jpeg'):
absPath = self.converPath(dirPath) + imageName
IMAGEFILES.append(absPath)
def converPath(self, dirPath):
'''用于转换路径,判断路径后是否为\\,如果有则直接输出,如果没有则添加'''
if dirPath is None or len(dirPath) == 0:
raise ValueError('dirPath不能为空!')
if os.path.isfile(dirPath):
raise ValueError('dirPath不能为具体文件,该值为文件夹路径!')
if not str(dirPath).endswith("\\"):
return dirPath + "\\"
return dirPath
def dateStr(self):
'''用于生成指定格式的日期,目的是为了拼接字符串'''
return time.strftime("%Y-%m-%d", time.localtime())
def main():
'''该函数主要用于生成PDF文件'''
pdfTk()
mainloop()
if __name__ == '__main__':
'''主函数,进行启动'''
main()