使用wkhtmltopdf工具生成pdf

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

最開始計劃使用canvas2pdf在前端進行生成。可是canva2pdf轉換的pdf有嚴重的失真問題,而後決定使用wkhtmltopdf工具進行生成。css

思路:服務器準備好模板(html頁面),前臺將數據傳回後臺,將數據把模板中的佔位符替換掉,而後生成臨時html頁面,再使用wkhtmltopdf工具將html頁面轉換成pdfhtml

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

將數據填充到html的過程這裏就不作展現。只展現轉換過程java

//導出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!canvas

wkhtmltopdf的工具參數詳解在這裏 服務器

HTML 轉 PDF 之 wkhtmltopdf 工具精講工具

相關文章
相關標籤/搜索