可以使用 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()