如何写文档格式转换脚本

wen 实用脚本 28

本文目录导读:

如何写文档格式转换脚本

  1. Python脚本方案
  2. 命令行工具方案
  3. 自动化脚本示例
  4. 使用建议
  5. 注意事项

我来介绍几种常见的文档格式转换脚本方案,涵盖Python和命令行工具。

Python脚本方案

基础安装

# 安装必要的库
pip install python-docx  # Word文档处理
pip install PyPDF2       # PDF处理
pip install openpyxl     # Excel处理
pip install markdown     # Markdown处理

示例脚本

1 Word转PDF

# word_to_pdf.py
import os
from docx2pdf import convert
def word_to_pdf(input_file, output_file=None):
    """
    将Word文档转换为PDF
    """
    if output_file is None:
        output_file = os.path.splitext(input_file)[0] + '.pdf'
    try:
        convert(input_file, output_file)
        print(f"转换成功: {output_file}")
        return True
    except Exception as e:
        print(f"转换失败: {e}")
        return False
# 批量转换
def batch_convert(folder_path):
    for file in os.listdir(folder_path):
        if file.endswith('.docx'):
            word_to_pdf(os.path.join(folder_path, file))
if __name__ == "__main__":
    # 使用示例
    word_to_pdf("input.docx", "output.pdf")
    # batch_convert("./word_files")

2 Markdown转HTML/PDF

# markdown_converter.py
import markdown
import pdfkit
import os
def md_to_html(md_file, html_file=None):
    """Markdown转HTML"""
    if html_file is None:
        html_file = os.path.splitext(md_file)[0] + '.html'
    with open(md_file, 'r', encoding='utf-8') as f:
        md_content = f.read()
    # 转换Markdown为HTML
    html_content = markdown.markdown(md_content, extensions=['extra', 'codehilite'])
    # 添加基本样式
    styled_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Document</title>
        <style>
            body {{ max-width: 800px; margin: 0 auto; padding: 20px; }}
            pre {{ background: #f4f4f4; padding: 10px; border-radius: 5px; }}
            code {{ background: #f4f4f4; padding: 2px 5px; }}
        </style>
    </head>
    <body>
        {html_content}
    </body>
    </html>
    """
    with open(html_file, 'w', encoding='utf-8') as f:
        f.write(styled_html)
    print(f"已转换: {html_file}")
# 需要安装wkhtmltopdf: https://wkhtmltopdf.org/
def md_to_pdf(md_file, pdf_file=None):
    """Markdown转PDF (需要wkhtmltopdf)"""
    if pdf_file is None:
        pdf_file = os.path.splitext(md_file)[0] + '.pdf'
    # 先转HTML
    html_file = md_file + '.html'
    md_to_html(md_file, html_file)
    # HTML转PDF
    try:
        pdfkit.from_file(html_file, pdf_file)
        os.remove(html_file)  # 删除临时HTML
        print(f"已转换: {pdf_file}")
    except Exception as e:
        print(f"PDF转换失败: {e}")
        print(f"保留临时HTML: {html_file}")
if __name__ == "__main__":
    md_to_html("README.md")
    # md_to_pdf("README.md")

3 批量格式转换器

# batch_converter.py
import os
import argparse
import subprocess
from pathlib import Path
class DocumentConverter:
    def __init__(self, input_dir=".", output_dir="converted"):
        self.input_dir = Path(input_dir)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
    def convert_single(self, file_path, target_format):
        """转换单个文件"""
        input_path = Path(file_path)
        if not input_path.exists():
            print(f"文件不存在: {file_path}")
            return False
        output_path = self.output_dir / f"{input_path.stem}.{target_format}"
        if input_path.suffix == '.docx' and target_format == 'pdf':
            return self._convert_docx_to_pdf(input_path, output_path)
        elif input_path.suffix == '.md' and target_format == 'html':
            return self._convert_md_to_html(input_path, output_path)
        elif input_path.suffix == '.txt' and target_format == 'pdf':
            return self._convert_txt_to_pdf(input_path, output_path)
        else:
            print(f"不支持的转换: {input_path.suffix} -> .{target_format}")
            return False
    def _convert_docx_to_pdf(self, input_path, output_path):
        """Word转PDF"""
        try:
            from docx2pdf import convert
            convert(str(input_path), str(output_path))
            print(f"✅ {input_path.name} -> {output_path.name}")
            return True
        except Exception as e:
            print(f"❌ 转换失败 {input_path.name}: {e}")
            return False
    def _convert_md_to_html(self, input_path, output_path):
        """Markdown转HTML"""
        import markdown
        try:
            with open(input_path, 'r', encoding='utf-8') as f:
                md_content = f.read()
            html = markdown.markdown(md_content, extensions=['extra'])
            full_html = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8">{input_path.stem}</title>
<style>body {{ margin: 40px auto; max-width: 800px; }}</style>
</head><body>{html}</body></html>"""
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(full_html)
            print(f"✅ {input_path.name} -> {output_path.name}")
            return True
        except Exception as e:
            print(f"❌ 转换失败 {input_path.name}: {e}")
            return False
    def _convert_txt_to_pdf(self, input_path, output_path):
        """文本转PDF"""
        try:
            from fpdf import FPDF
            pdf = FPDF()
            pdf.add_page()
            pdf.add_font('DejaVu', '', 'DejaVuSans.ttf', uni=True)
            pdf.set_font('DejaVu', '', 12)
            with open(input_path, 'r', encoding='utf-8') as f:
                for line in f:
                    pdf.cell(200, 10, txt=line.encode('latin-1', 'ignore').decode('latin-1'), ln=True)
            pdf.output(str(output_path))
            print(f"✅ {input_path.name} -> {output_path.name}")
            return True
        except Exception as e:
            print(f"❌ 转换失败 {input_path.name}: {e}")
            return False
    def batch_convert(self, pattern="*", target_format="pdf"):
        """批量转换"""
        count = 0
        for file in self.input_dir.glob(pattern):
            if file.is_file():
                if self.convert_single(file, target_format):
                    count += 1
        print(f"\n完成! 成功转换 {count} 个文件")
# 命令行接口
def main():
    parser = argparse.ArgumentParser(description='文档格式转换工具')
    parser.add_argument('input', help='输入文件或目录')
    parser.add_argument('--format', '-f', default='pdf', 
                       choices=['pdf', 'html', 'docx', 'txt'],
                       help='目标格式')
    parser.add_argument('--output', '-o', default='converted',
                       help='输出目录')
    parser.add_argument('--batch', '-b', action='store_true',
                       help='批量模式')
    args = parser.parse_args()
    converter = DocumentConverter(output_dir=args.output)
    if args.batch:
        if os.path.isdir(args.input):
            pattern = f"*.{args.format.replace('pdf', 'docx').replace('html', 'md')}"
            converter.input_dir = Path(args.input)
            converter.batch_convert(pattern, args.format)
    else:
        converter.convert_single(args.input, args.format)
if __name__ == "__main__":
    main()

命令行工具方案

1 Pandoc (全能文档转换器)

# 安装
# macOS: brew install pandoc
# Ubuntu: sudo apt-get install pandoc
# Windows: 下载安装包
# 基本用法
pandoc input.md -o output.html           # MD转HTML
pandoc input.md -o output.pdf            # MD转PDF (需LaTeX)
pandoc input.docx -o output.md           # Word转Markdown
pandoc input.html -o output.docx         # HTML转Word
# 批量转换脚本

批量转换脚本

#!/bin/bash
# batch_convert.sh
# 将当前目录所有md文件转换为html
for file in *.md; do
    if [ -f "$file" ]; then
        filename="${file%.*}"
        pandoc "$file" -o "${filename}.html"
        echo "转换: $file -> ${filename}.html"
    fi
done
# 转换所有docx为pdf (使用LibreOffice)
for file in *.docx; do
    if [ -f "$file" ]; then
        libreoffice --headless --convert-to pdf "$file"
        echo "转换: $file"
    fi
done

2 LibreOffice命令行

# 安装LibreOffice
# 批量转换所有Office文档为PDF
libreoffice --headless --convert-to pdf *.docx *.xlsx *.pptx
# 指定输出目录
libreoffice --headless --convert-to pdf --outdir ./pdf_output/ *.docx
# 指定格式转换
libreoffice --headless --convert-to "pdf:writer_pdf_Export" input.docx

自动化脚本示例

# auto_converter.py
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ConverterHandler(FileSystemEventHandler):
    def __init__(self, target_format="pdf"):
        self.target_format = target_format
    def on_created(self, event):
        if event.is_directory:
            return
        file_ext = os.path.splitext(event.src_path)[1].lower()
        supported_exts = ['.docx', '.md', '.txt', '.html']
        if file_ext in supported_exts:
            print(f"检测到新文件: {event.src_path}")
            time.sleep(1)  # 等待文件写入完成
            # 自动转换
            output_file = event.src_path + f".{self.target_format}"
            if file_ext == '.docx':
                self.convert_docx(event.src_path, output_file)
            elif file_ext == '.md':
                self.convert_md(event.src_path, output_file)
    def convert_docx(self, input_file, output_file):
        try:
            from docx2pdf import convert
            convert(input_file, output_file)
            print(f"自动转换: {input_file} -> {output_file}")
        except Exception as e:
            print(f"转换失败: {e}")
def start_monitoring(folder_path=".", target_format="pdf"):
    """监控文件夹,自动转换新文件"""
    event_handler = ConverterHandler(target_format)
    observer = Observer()
    observer.schedule(event_handler, folder_path, recursive=False)
    observer.start()
    print(f"开始监控文件夹: {folder_path}")
    print("按 Ctrl+C 停止监控")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
if __name__ == "__main__":
    # 监控当前目录,自动转换新文件为PDF
    start_monitoring(".", "pdf")

使用建议

安装指南

# 全功能安装
pip install python-docx PyPDF2 openpyxl markdown pdfkit docx2pdf
# 安装系统工具
# macOS
brew install pandoc libreoffice
# Ubuntu
sudo apt-get install pandoc libreoffice-writer
# Windows: 下载安装包
# pandoc: https://pandoc.org/installing.html
# LibreOffice: https://www.libreoffice.org/download/

执行示例

# 使用批处理脚本
python batch_converter.py ./documents --format pdf --batch
# 使用监控脚本
python auto_converter.py
# 使用命令行
chmod +x batch_convert.sh
./batch_convert.sh

注意事项

  1. 中文支持:可能需要安装中文字体
  2. 性能优化:大文件转换时考虑内存使用
  3. 错误处理:添加日志记录失败的转换
  4. 备份原文件:转换前建议备份

这些脚本可以根据具体需求修改和扩展,支持更多的格式转换组合。

抱歉,评论功能暂时关闭!