pip3 install img2pdf
如果是linux系统或者是mac系统的话,就需要打开终端然后在命令前加上sudo参数表示管理员权限去下载安装这个库。
2.安装完成之后新建一个python脚本来编写代码,首先就是将这两个模块都给导入进来,示例如下:
import os
import img2pdf
3.然后使用with关键字创建出一个上下文管理器结构并且打开一个pdf文件,使用它的原因就在于可以在代码执行完毕之后自动的释放资源并关闭文件,示例如下:
with open("Output.pdf", "wb") as file:
有没有这个pdf文件都可以,如果没有的话会在文件路径内自动去创建。
4.最后就是需要调用该文件对象的write()方法来将图片数据写入进去了,在这个方法里面会调用convert()将一个文件路径内后缀名为jpg的图片全部以二进制流的方式读取出来,示例如下:
file.write(img2pdf.convert([i for i in os.listdir('文件路径') if i.endswith(".jpg")]))
以上就是关于“Python怎么将图片保存为pdf格式?Python图片合成为pdf的代码如何写”的全部内容了,希望对你有所帮助。
我经常需要使用LibreOffice将许多(>1000).docx文档导出为PDF。这是一个示例文档:test.docx。以下代码可以工作,但是在Windows上却相当慢(每个PDF文档平均3.3秒):1
2
3
4
5
6
7
8
9
10
11
12
13
import subprocess, docx, time # first do: pip install python-docx
for i in range(10):
doc = docx.Document('test.docx')
for paragraph in doc.paragraphs:
paragraph.text = paragraph.text.replace('{{num}}', str(i))
doc.save('test%i.docx' % i) # these 4 previous lines are super fast - a few ms
t0 = time.time()
subprocess.call(r'C:\\Program Files\\LibreOffice\\program\\soffice.exe --headless --convert-to pdf test%i.docx --outdir . --nocrashreport --nodefault --nofirststartwizard --nolockcheck --nologo --norestore"' % i)
print('PDF generated in %.1f sec' % (time.time()-t0))
# for linux:
# (0.54 seconds on average, so it's 6 times better than on Windows!)
# subprocess.call(['/usr/bin/soffice', '--headless', '--convert-to', 'pdf', '--outdir', '/home/user', 'test%i.docx' % i])
如何在Windows上加快PDF导出速度?
我怀疑在"Start LibreOffice/Writer, (do the job), Close LibreOffice" "Start LibreOffice/Writer, (do the job), Close LibreOffice" "Start LibreOffice/Writer, (do the job), Close LibreOffice"等上浪费了很多时间。
注释:
作为比较:此处:https://bugs.documentfoundation.org/show_bug.cgi?id=92274导出时间据说是90ms或810ms。
soffice.exe替换为swriter.exe:相同的问题:平均3.3秒
1
subprocess.call(r'C:\\Program Files\\LibreOffice\\program\\swriter.exe --headless --convert-to pdf test%i.docx --outdir ."' % i)
相关讨论
在macOS和Linux上相同
实际上,所有时间都浪费在启动/退出LibreOffice上。我们可以一次调用soffice.exe:
传递许多docx文档
1
2
3
4
5
6
7
8
9
10
import subprocess, docx
for i in range(1000):
doc = docx.Document('test.docx')
for paragraph in doc.paragraphs:
paragraph.text = paragraph.text.replace('{{num}}', str(i))
doc.save('test%i.docx' % i)
# all PDFs in one pass:
subprocess.call(['C:\\Program Files\\LibreOffice\\program\\swriter.exe',
'--headless', '--convert-to', 'pdf', '--outdir', '.'] + ['test%i.docx' % i for i in range(1000)])
总共107秒,因此每个PDF平均约为107毫秒!
注意事项:
它不适用于10,000个文档,因为命令行参数的长度将超过32k个字符,如此处所述
我想知道是否有可能采用一种更具交互性的方式来无头使用LibreOffice:
启动Writer无头,保持启动状态
向该过程发送类似open test1.docx的 *** 作
发送 *** 作export to pdf,然后关闭docx
发送open test2.docx,然后导出,依此类推。
...
退出Writer headless
这适用于MS Office的COM(组件对象模型):使用python的.doc到pdf,但我想知道LibreOffice是否存在类似的东西。答案似乎是否定的:LibreOffice / OpenOffice是否支持COM模型
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)