[C#] 將 DOCX 轉成 PDF 筆記

2022-12-16

今天來測試一下,把 docx 轉成 PDF ,先說結論這篇文沒有完全解決問題

只是寫個筆記,網路上基本上如果要簡單的解決計就是花錢解決

這篇不花錢但是有點麻煩



1. 課金 https://products.aspose.com/pdf/zh-hant/

程式碼範例非常完整,但是如果你沒有課金出來的 PDF 會長這樣


2. 使用內建指令,網路上看到 有一個解法,你可以使用  command line 就解決,就是呼叫 windows 內建的  wordpad 然後 列印出 pdf 


Write /pt MyXML.Zip.docx "Microsoft Print to PDF" "Microsoft Print to PDF" output.pdf
在 C# 中 呼叫的程式碼

string downloadPath = Path.Combine(this.Environment.WebRootPath, "Downloads"); var process = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo { //FileName=AppDomain.CurrentDomain.BaseDirectory+Path.DirectorySeparatorChar+"Wordpad"+Path.DirectorySeparatorChar+ "wordpad.exe", FileName = "Write", Arguments = " /pt test1.docx \"Microsoft Print to PDF\" \"Microsoft Print to PDF\" " + downloadPath + Path.DirectorySeparatorChar + "test6.pdf", UseShellExecute = false, CreateNoWindow = false, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, RedirectStandardOutput = true, RedirectStandardError = true, }, }; process.Start();


但是這招我測試過了,如果你是在 Azure AppService 中,即使你開 Windows 的機器,甚至把 WordPad.exe 搬上去都不行

所以就是本機可以用或是你要開虛擬機


3. 使用 OpenSource 的 LibreOfficePortable 這個  黑大有介紹過

可以參考這篇文章 https://blog.darkthread.net/blog/libreoffice-convert-docx-to-pdf-survey/

我看到解壓縮完要七八百 MB 我就先投降。

筆記一下,目前看到如果是不裝 Office 先只用方法二來解決




當麻許的碎念筆記 2014 | Donma Hsu Design.