通過將 Word 文檔轉換為 PDF,您可以確保文檔在不同設備上呈現一致,并防止其他人對文檔內容進行非授權修改。此外,在你需要打印文檔時,轉換為PDF還能確保打印輸出的準確性。本文將介紹如何使用Python 庫將Word文檔轉換為PDF格式。
- Python 將 Word DOCX/DOC 轉換為 PDF
- Python 將 Word轉換為加密的PDF
- Python 將 Word轉為 PDF時嵌入字體
?
Python Word庫安裝
本文中使用到的python庫為?Spire.Doc for Python, 它能輕松實現 Word 文檔的創(chuàng)建、讀取、編輯和轉換等功能。要使用此產品,可以通過以下pip 命令將其安裝到你的 VS Code中。
pip install Spire.Doc
詳細安裝教程可參考: 如何在 VS Code中安裝 Spire.XLS for Python
?
Python 將 Word DOCX/DOC 轉換為 PDF
要實現該轉換,僅需加載一個?.doc?或?.docx?文檔,然后使用?Document.SaveToFile(string fileName, FileFormat.PDF) 方法就能將Word轉為PDF格式。完整代碼如下:
from spire.doc import * from spire.doc.common import * # 創(chuàng)建Document對象 document = Document() # 加載Word文檔 document.LoadFromFile("清單.docx") # 將文檔保存為PDF格式 document.SaveToFile("Word轉PDF.pdf", FileFormat.PDF) document.Close()
?
Python 將 Word轉換為加密的PDF
除了簡單的Word轉PDF外,Spire.Doc for Python 還提供了?ToPdfParameterList 類來控制轉換過程。你可以先為生成的PDF設置密碼,然后在轉換時用Document.SaveToFile(string fileName, ToPdfParameterList paramList)?方法來將Word保存為加密的PDF文件。完整代碼如下:
from spire.doc import * from spire.doc.common import * # 創(chuàng)建Document對象 document = Document() # 加載Word文檔 document.LoadFromFile("清單.docx") # 創(chuàng)建ToPdfParameterList對象 parameter = ToPdfParameterList() # 為生成的PDF文件設置打開密碼和權限密碼 openPsd = "abcd" permissionPsd = "1234" parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit) # 將文檔保存為加密的PDF document.SaveToFile("輸出文件.pdf", parameter) document.Close()
?
Python 將 Word轉為 PDF時嵌入字體
將字體嵌入到PDF中能確保文檔在不同設備上正確顯示,避免由于缺少字體而導致的問題。這對于包含自定義字體或特殊字形的文檔尤其重要。Spire.Doc for Python 提供的ToPdfParameterList.IsEmbeddedAllFonts 屬性能幫你實現Word轉 PDF時嵌入字體。完整代碼如下:
from spire.doc import * from spire.doc.common import * # 創(chuàng)建Document對象 document = Document() # 加載Word文檔 document.LoadFromFile("清單.docx") # 創(chuàng)建ToPdfParameterList對象 parameter = ToPdfParameterList() # 將字體嵌入到生成的PDF中 parameter.IsEmbeddedAllFonts = True # 將文檔保存為PDF document.SaveToFile("嵌入字體.pdf", parameter) document.Close()
如果你想在轉換Word到PDF時壓縮圖片以減小生成PDF的文件大小,可通過 Document.JPEGQuality 屬性設置圖片質量。此外,ToPdfParameterList 類還支持在轉換時保留原有書簽,或者按照標題創(chuàng)建新書簽。文章來源:http://www.zghlxwxcb.cn/news/detail-712095.html
# 根據 Word 中的標題創(chuàng)建 PDF 書簽 parames.CreateWordBookmarksUsingHeadings = True # 根據 Word 中的現有書簽創(chuàng)建 PDF 書簽 parames.CreateWordBookmarks = True
?文章來源地址http://www.zghlxwxcb.cn/news/detail-712095.html
到了這里,關于Python 實現Word轉PDF的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!