由于轻社群文章不想被人复制,写的txt|word转化成图片
1将txt 转化为图片
2.将word 转化为 pdf ,同志转化为图片
说明:
公供内人使用,方便她徽商文章保护,代码没有更多的异常控制。
# -*- coding:utf-8 -*-
import os
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import codecs, configparser
from PIL import Image,ImageDraw,ImageFont
import datetime,shutil
from win32com.client import Dispatch, constants, gencache
import sys
import fitz
'''
pip3 install PyMuPDF
pip3 install pypiwin32
pip3 install Pillow
pip3 install PyInstaller
'''
'''
word to pdf
'''
#################word to pdf
def doc2pdf(input, output):
w = Dispatch("Word.Application")
try:
doc = w.Documents.Open(input, ReadOnly=1)
doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
return 0
except Exception as e:
print(str(e))
return 1
finally:
w.Quit(constants.wdDoNotSaveChanges)
# Generate all the support we can.
def GenerateSupport():
# enable python COM support for Word 2007
# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
'''
处理txt转图片
'''
def txt2png(file):
# read configuration
print('read configuration')
config = configparser.ConfigParser()
config.read('config.cfg',encoding="utf8")
bg = config.get('input', 'background')
content = config.get('input', 'content')
encoding = config.get('input', 'encoding')
fontname = config.get('input', 'fontname')
result_path = config.get('input', 'result_path')
test = config.get('input','test')
left = int(config.get('output', 'left'))
top = int(config.get('output', 'top'))
width = int(config.get('output', 'width'))
height = int(config.get('output', 'height'))
fontsize = int(config.get('output', 'fontsize'))
leading = int(config.get('output', 'leading'))
lineHeight = fontsize + leading
filename = config.get('output', 'name')
filetype = config.get('output', 'type')
font = ImageFont.truetype(fontname, fontsize)
# read content
storetmp=[]
with open(file,'rb') as f :
storetmp = f.readlines()
contentpath = os.path.join(os.path.dirname(__file__),content)
with open(contentpath,'wb') as fw:
fw.writelines(storetmp)
#'read content'
print ('txt:',file,contentpath)
f = codecs.open(contentpath, 'rb', encoding='GBK')
try:
text = f.read()
except Exception as e :
print ("got to execept")
f.close()
f = codecs.open(contentpath, 'rb', encoding='utf-8')
text = f.read()
if text[0] == u'\ufeff':
text = text[1:]
f.close()
n_t = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# text process
wraptext = [u"\u3000"]
l = fontsize
for t in text:
fi = t
delta = font.getsize(t)[0]
if t == '\n':
wraptext += [u"\u3000"]
l = fontsize
elif l + delta > width:
wraptext += [t]
l = delta
else:
wraptext[-1] += t
l += delta
# draw text and save
ltop = top
filecounter = 1
pattern = "%s%04d_%s.%s"
filename = filename.split('.')
img = Image.open(bg)
draw = ImageDraw.Draw(img)
# result_path
bpath = os.path.join(os.path.dirname(__file__), result_path)
bpath_old = os.path.join(bpath, 'old')
# print bpath
if not os.path.isdir(bpath):
os.mkdir(bpath)
if not os.path.isdir(bpath_old):
os.mkdir(bpath_old)
for f in os.listdir(bpath):
# print f.endswith('png')
if f.endswith('png'):
try:
src = os.path.join(bpath, f)
dst = os.path.join(bpath_old, f)
shutil.move(src, dst)
except Exception as e:
pass
for i, txt in enumerate(wraptext):
if ltop + lineHeight > height:
name = pattern % (filename[0], filecounter, n_t, filename[1])
name = os.path.join(bpath, name)
print('saving_in \"%s\" ...' % name)
img.save(name, filetype)
filecounter += 1
img = Image.open(bg)
draw = ImageDraw.Draw(img)
ltop = top
draw.text((left, ltop), txt, font=font, fill='black')
ltop += lineHeight
pass
name = pattern % (filename[0], filecounter, n_t, filename[1])
name = os.path.join(bpath, name)
print('saving \"%s\" ...' % name)
img.save(name, filetype)
return filecounter
class Window():
def __init__(self):
self.root = root = tkinter.Tk()
self.menu = tkinter.Menu(root)
self.submenu = tkinter.Menu(self.menu, tearoff=0)
self.submenu.add_command(label='内容付费时代')
root.config(menu=self.submenu)
self.Image = tkinter.StringVar()
self.Image.set('.bmp')
self.mstatus = tkinter.IntVar()
self.fstatus = tkinter.IntVar()
self.mstatus.set(0)
self.fstatus.set(0)
self.status = tkinter.StringVar()
self.status.set("未进行转换")
self.file = None
self.label = tkinter.Label(root, text='选择文件',bg='green',height=1)
self.label.place(x=5, y=5)
self.entryFile = tkinter.Entry(root)
self.entryFile.place(x=60, y=5)
self.BrowserFileButton = tkinter.Button(root,
text='浏览',
command=self.BrowserFile)
self.BrowserFileButton.place(x=220, y=5)
frame = tkinter.Frame(root, )
frame.place(x=10, y=150)
self.ButtonCov = tkinter.Button(root, text='转换成图片', command=self.Conv, )
self.ButtonCov.place(x=120, y=180)
self.statusLabel = tkinter.Label(root, textvariable=self.status, fg='red')
self.statusLabel.place(x=120, y=220)
def BrowserFile(self):
file = tkinter.filedialog.askopenfilename(title='Python player',
filetypes=[ ('docx', '*.docx'),('doc', '*.doc'),('txt', '*.txt'),])
if file:
if not file.endswith('txt') and file.find('doc') == -1 :
#print(os.path.dirname(__file__))
tkinter.messagebox.showwarning(title='Hi', message='文件只能是txt或者word!')
self.entryFile.delete(0, tkinter.END)
return None
self.entryFile.delete(0, tkinter.END)
self.entryFile.insert(tkinter.END, file)
self.file = file
def Conv(self):
convertPicnum = 0
if self.entryFile.get() == '':
tkinter.messagebox.showerror('出错啦', '请选择文件')
return
if self.file:
self.ButtonCov.config(state=tkinter.DISABLED)
file = self.file
if file.endswith('txt'):
convertPicnum = txt2png(self.file)
elif file.find('doc') != -1:
#copy file to
#inputdoc =os.path.join(os.path.dirname(__file__), file.split('/')[-1])
#inputdoc = os.path.dirname(__file__)+'/'+file.split('/')[-1]
inputdoc = os.getcwd() + '\\' + file.split('/')[-1]
print (file,inputdoc,os.path.dirname(__file__),"bbbbbb",file.split('/'))
#print(inputdoc)
if file.replace('/','\\') != inputdoc:
shutil.copy(file,inputdoc)
#store_tmp = unicode(os.path.splitext(inputdoc)[0], 'GBK')
store_tmp = file.split('/')[-1]
outputpdf = os.path.splitext(inputdoc)[0] + '.pdf'
if (not os.path.isabs(inputdoc)):
inputdoc = os.path.abspath(inputdoc)
if (not os.path.isabs(outputpdf)):
outputpdf = os.path.abspath(outputpdf)
try:
if os.path.isfile(outputpdf):
os.unlink(outputpdf)
GenerateSupport()
rc = doc2pdf(inputdoc, outputpdf)
except Exception as e:
printstr(e)
#deal pdf to png
pdffile = outputpdf
doc = fitz.open(pdffile)
strat = 0
totaling = doc.pageCount
#pdf2png = os.path.join(os.path.dirname(__file__), 'pdf2png')
##pdf2png = os.path.dirname(__file__)+'/pdf2png'
pdf2png = os.getcwd() + '\\pdf2png'
#pdf2png_old = os.path.join(pdf2png, 'old')
pdf2png_old = pdf2png+'\\old'
if not os.path.isdir(pdf2png):
os.mkdir(pdf2png)
if not os.path.isdir(pdf2png_old):
os.mkdir(pdf2png_old)
n_t = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
print ("+++"*30)
print(pdf2png,pdf2png_old)
for f in os.listdir(pdf2png):
# print f.endswith('png')
if f.endswith('png'):
try:
src = os.path.join(pdf2png, f)
dst = os.path.join(pdf2png_old, f)
shutil.move(src, dst)
except Exception as e:
print (str(e))
for pg in range(strat, totaling):
page = doc[pg]
zoom = int(100)
rotate = int(0)
trans = fitz.Matrix(zoom / 100.0, zoom / 100.0).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG(pdf2png + '/%s_%s_%s.png' % (store_tmp, n_t, str(pg + 1)))
convertPicnum = totaling
path = pdf2png
os.system("explorer %s" % path)
self.ButtonCov.config(state=tkinter.NORMAL)
self.status.set('成功转换 %d 张图片' % convertPicnum)
return
def center_window(self, width, height):
screenwidth = self.root.winfo_screenwidth()
screenheight = self.root.winfo_screenheight()
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
# print(size)
self.root.geometry(size)
def mainloop(self):
self.center_window(300, 300)
self.root.minsize(300, 300)
self.root.maxsize(300, 300)
self.root.title('菜菜内容转图片')
self.root.mainloop()
if __name__ == "__main__":
window = Window()
window.mainloop()