使用wkhtmltopdf工具生成pdf


背景:將前台頁面轉換成pdf文檔保存到服務器

最開始計划使用canvas2pdf在前端進行生成。但是canva2pdf轉換的pdf有嚴重的失真問題,然后決定使用wkhtmltopdf工具進行生成。

思路:服務器准備好模板(html頁面),前台將數據傳回后台,將數據把模板中的占位符替換掉,然后生成臨時html頁面,再使用wkhtmltopdf工具將html頁面轉換成pdf

這里注意:模板中使用到的圖片和引用css的路徑需要使用絕對路徑(帶盤符如:c:\a.jpg 或者為localhost:5555/src/a.css)否則wkhtmltopdf工具會找不到引用資源。

將數據填充到html的過程這里就不做展示。只展示轉換過程

//導出html
            string outputDir = ConvertPdfHelper.GetAbsolutePath("outputDir", false);
            DateTime now = DateTime.Now;
            string filePath = now.ToString("yyyy/MM/dd") + "/" + salesOrderNo + ".html";
            string temphtmlPath = Path.Combine(outputDir, filePath);
            string pdfPath = temphtmlPath.Replace(".html", ".pdf");
            //保證文件夾存在
            FileInfo fileInfo = new FileInfo(temphtmlPath);
            fileInfo.Directory.Create();
            string wtHtmlToPdfEXEPath = ConvertPdfHelper.GetAbsolutePath("htmltopdfTool", false);
            using (StreamWriter writer = new StreamWriter(temphtmlPath, false, Encoding.UTF8))
            {
                writer.WriteLine(layoutSb);
                writer.Flush();
                writer.Close();
            }
            //轉pdf
            string switches = "";
            switches += "--margin-top 0mm --margin-bottom 0mm --margin-right 0mm --margin-left 0mm ";

            switches += "--page-size A5 ";
            switches += "--orientation Landscape ";

            switches += "--javascript-delay 1000 ";
            switches += "--image-quality 50 --lowquality ";
            switches += "--disable-smart-shrinking ";
            switches += " " + temphtmlPath + " " + pdfPath + "";
            ProcessStartInfo startInfo = new ProcessStartInfo(wtHtmlToPdfEXEPath, switches);
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            //將輸出信息重定向
            startInfo.RedirectStandardOutput = true;
            Process process = Process.Start(startInfo);
            process.WaitForExit();

Done!

wkhtmltopdf的工具參數詳解在這里 

HTML 轉 PDF 之 wkhtmltopdf 工具精講

 


免責聲明!

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



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