简体   繁体   English

将文件夹中的所有文本文档转换为 PDF

[英]Convert all Text Documents from a folder to PDF

I have few text documents in a folder and would like to convert them to PDF Format.我的文件夹中有几个文本文档,想将它们转换为 PDF 格式。 I am able to do it individually with the below code.我可以使用以下代码单独完成。 Is there any way to select all the text files from a folder, convert and save them with the original name (as it was for text documents)?有什么方法可以将文件夹中的所有文本文件 select 转换并使用原始名称保存(就像文本文档一样)? Below is the code I used to convert each file:下面是我用来转换每个文件的代码:


from fpdf import FPDF
pdf = FPDF()

pdf.add_page()
pdf.set_font("Arial", size = 8)

f = open("C:\\Users\\rc06587\\Desktop\\Text Doc\\Sample\\New folder (2)\\exp_000004593_cn23rk__09042020000000_citrixsystemsinc_92080217mr_00384.TXT", "r")

for x in f:
    pdf.cell(10, 4, txt = x, ln = 1, align = 'L')

pdf.output("exp_000004593_cn23rk__09042020000000_citrixsystemsinc_92080217mr_00384.TXT.pdf")

Use os.listdir() to get the files in the directory you want, filter for text files, and then do your conversion.使用os.listdir()获取所需目录中的文件,过滤文本文件,然后进行转换。

from fpdf import FPDF

def convert_one_file(path):
    pdf = FPDF()

    pdf.add_page()
    pdf.set_font("Arial", size = 8)

    f = open(path, "r")

    for x in f:
        pdf.cell(10, 4, txt = x, ln = 1, align = 'L')

    pdf.output(path + ".PDF")
    
path = "..."
for f in os.listdir(path):
    if os.path.isfile(os.sep.join((path, f))) and f.endswith(".txt"):
        convert_one_file(os.sep.join((path, f)))

A more elegant solution would probably be to use pathlib to join the paths.一个更优雅的解决方案可能是使用pathlib来加入路径。

In windows you dont need python or fpdf just use the command line在 windows 你不需要 python 或 fpdf 只需使用命令行

在此处输入图像描述

set any command line desired to rotate through file list and write them to pdf adapt any cmd to suit.设置任何想要在文件列表中旋转的命令行并将它们写入 pdf 适应任何 cmd 以适应。 If text is plain, it will become a searchable text.pdf如果文本是纯文本,它将成为可搜索的文本。pdf

AllTXT2PDF.cmd全部TXT2PDF.cmd

FORFILES /M *.txt /C "cmd /c if @isdir==FALSE write.exe /pt @file \"Microsoft Print to PDF\" \"Microsoft Print to PDF\" \"@file.pdf\""

However as plain text it will be left set default size courier font so for Arial 8 point you need to save as rich text, which is easy enough if you want to style the contents for centering justify colour mixed fonts etc.然而,作为纯文本,它将保留默认大小的 courier 字体,因此对于 Arial 8 磅,您需要另存为富文本格式,如果您想要设置内容样式以居中对齐颜色混合 fonts 等,这很容易。

在此处输入图像描述

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM