關於使用腳本將docx轉成pdf在轉成圖片


關於使用腳本將docx轉成pdf在轉成圖片

這里有兩種方法(docx->pdf)

方法1(python腳本)

# 需要導入的
import sys
from win32com.client import Dispatch
import fitz   # pip3 install pymupdf
import os
import requests
import base64
腳本
# word_to_pdf
def word_to_pdf(word_file, pdf_file):
    """
    將word文件轉換成pdf文件
    :param pdf_file:
    :param word_file: word文件
    :return:
    """
    # 獲取word格式處理對象
    word = Dispatch('Word.Application')
    # 以Doc對象打開文件
    doc_ = word.Documents.Open(word_file)
    # 另存為pdf文件
    doc_.SaveAs(pdf_file, FileFormat=17)
    # 關閉doc對象
    doc_.Close()
    # 退出word對象
    word.Quit()

方法2(vbs腳本)

待轉換的docx放在一個文件夾中新建一個script.vbs文件,文件放在待轉換的文件夾中將以下代碼放入scripy.vbs腳本中雙擊vbs腳本即可開始轉換

On Error Resume Next
Const wdExportFormatPDF = 17
Set oWord = WScript.CreateObject("Word.Application")
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set fds=fso.GetFolder(".")
Set ffs=fds.Files
wscript.echo "Word文件正在轉換中,請勿關閉當前窗口..."
For Each ff In ffs
    If (LCase(Right(ff.Name,4))=".doc" Or LCase(Right(ff.Name,4))="docx" ) And Left(ff.Name,1)<>"~" Then
        Set oDoc=oWord.Documents.Open(ff.Path)
        odoc.ExportAsFixedFormat Left(ff.Path,InStrRev(ff.Path,"."))&"pdf",wdExportFormatPDF
        If Err.Number Then
        MsgBox Err.Description
        End If
    End If
Next
odoc.Close
oword.Quit
Set oDoc=Nothing
Set oWord =Nothing
wscript.echo  "Word文件已全部轉換為PDF格式!"
MsgBox "Word文件已全部轉換為PDF格式!"

pdf->png

# pdf_to_png
def pdf_to_png(_pdf, _save_dir):
    _doc = fitz.open(_pdf)
    pdf_name = os.path.splitext(_pdf)[0]
    for pg in range(_doc.pageCount):
        page = _doc[pg]
        rotate = int(0)
        # 每個尺寸的縮放系數為2,這將為我們生成分辨率提高四倍的圖像。
        zoom_x = 2.0
        zoom_y = 2.0
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
        pm = page.getPixmap(matrix=trans, alpha=False)
        # save_dir = pdf.replace('.pdf', '')
        if not os.path.exists(_save_dir):
            os.mkdir(_save_dir)
        pm.writePNG(os.path.join(_save_dir, '%s.png' % pg))

已發布pypi,有問題歡迎指正

# 安裝
pip install ds-my-tools
# 更新
pip install ds-my-tools --upgrade
# 卸載
pip uninstall ds-my-tools
# 使用
from my_tools import *


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM