要求:
把.md格式轉為.pdf格式,並批量處理,最后將多個pdf文件合並為一個pdf並以文件名作為書簽名
解決思路:
1.md格式的markdown文件轉為html
為了將 md 格式轉換成 html 文件,我們需要用到 markdown 和 codecs 這兩個庫。
pip install markdown
完整代碼如下:

import markdown import os import codecs head = """<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <style type="text/css"> code { color: inherit; background-color: rgba(0, 0, 0, 0.05); } </style> </head> <body> """ foot = """ </body> </html> """ filepath = "E:/Data/RenZhengfei-master/ALL" savepath = "E:/Data/RenZhengfei-master/ALL-html" if not os.path.isdir(savepath): os.mkdir(savepath) os.chdir(savepath) i = 0 pathDir = os.listdir(filepath) for allDir in pathDir: if (allDir == "pdf"): continue name = allDir print(name) os.chdir(filepath) fp1 = codecs.open(name, mode="r", encoding="utf-8") text = fp1.read() html = markdown.markdown(text) fp1.close() #print(html) fname = name.replace('md', 'html') #f2 = '%s.html' % (fname) os.chdir(savepath) fp2 = codecs.open(fname, "w", encoding="utf-8", errors="xmlcharrefreplace") fp2.write(head + html + foot) fp2.close() print(i)
2.html格式文件轉為pdf
wkhtmltopdf 是一個開源、簡單而有效的命令行 shell 程序,它可以將任何 HTML (網頁)轉換為 PDF 文檔或圖像(jpg、png 等)。
我們首先需要去官網去下載對應的程序到本地環境中 :https://wkhtmltopdf.org/downloads.html
也可以直接使用pip安裝
pip install pdfkit
完整代碼如下:

import time import pdfkit import os wk_path = r'E:/wkhtmltox/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wk_path) filepath = "E:/Data/RenZhengfei-master/ALL-html" savepath = "E:/Data/RenZhengfei-master/ALL-pdf" time1 = time.time() pathDir = os.listdir(filepath) for allDir in pathDir: if (allDir == "pdf"): continue name = allDir print(name) htmlpath=filepath+"\\"+name print(htmlpath) name = name.replace('html', 'pdf') os.chdir(savepath) pdfkit.from_url(htmlpath, name, configuration=config) #pdfkit.from_url(url, name, configuration=config) time2 = time.time() print(str(time2 - time1)+" s")
3.合並多個pdf文件

#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 本腳本用來合並pdf文件,支持帶一級子目錄的 每章內容分別放在不同的目錄下,目錄名為章節名 最終生成的pdf,按章節名生成書簽 ''' import os, sys, codecs from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger import glob def getFileName(filepath): '''獲取當前目錄下的所有pdf文件''' file_list = glob.glob(filepath+"/*.pdf") # 默認安裝字典序排序,也可以安裝自定義的方式排序 # file_list.sort() return file_list def get_dirs(filepath='', dirlist_out=[], dirpathlist_out=[]): # 遍歷filepath下的所有目錄 for dir in os.listdir(filepath): dirpathlist_out.append(filepath + '\\' + dir) return dirpathlist_out def merge_childdir_files(path): '''每個子目錄下合並生成一個pdf''' dirpathlist = get_dirs(path) if len(dirpathlist) == 0: print("當前目錄不存在子目錄") sys.exit() for dir in dirpathlist: mergefiles(dir, dir) def mergefiles(path, output_filename, import_bookmarks=False): #遍歷目錄下的所有pdf將其合並輸出到一個pdf文件中,輸出的pdf文件默認帶書簽,書簽名為之前的文件名 #默認情況下原始文件的書簽不會導入,使用import_bookmarks=True可以將原文件所帶的書簽也導入到輸出的pdf文件中 merger=PdfFileMerger() filelist=getFileName(path) if len(filelist)==0: print("當前目錄及子目錄下不存在pdf文件") sys.exit() for filename in filelist: f=codecs.open(filename,'rb') file_rd=PdfFileReader(f) short_filename=os.path.basename(os.path.splitext(filename)[0]) if file_rd.isEncrypted==True: print('不支持的加密文件:%s'%(filename)) continue merger.append(file_rd,bookmark=short_filename,import_bookmarks=import_bookmarks) print('合並文件:%s'%(filename)) f.close() #out_filename=os.path.join(os.path.abspath(path),output_filename) merger.write(output_filename+".pdf") print('合並后的輸出文件:%s'%(output_filename)) merger.close() if __name__ == "__main__": # 每個章節一個子目錄,先分別合並每個子目錄文件為一個pdf,然后再將這些pdf合並為一個大的pdf,這樣做目的是想生成每個章節的書簽 # 1.指定目錄 # 原始pdf所在目錄 path = "E:\Data\RenZhengfei-master\ALL-pdf" # 輸出pdf路徑和文件名 output_filename = "E:\Data\RenZhengfei-master" # 2.生成子目錄的pdf # merge_childdir_files(path) # 3.子目錄pdf合並為總的pdf mergefiles(path, output_filename)