1. 程式人生 > 其它 >C# 將html網頁生成pdf

C# 將html網頁生成pdf

將html文字或者html網頁生成pdf,我常用的2種方式:TuesPechkin    wkhtmltopdf

一、使用TuesPechkin轉pdf

1.首先引用TuesPechkin.dll,我使用的是1.0.3,也可以使用最新穩定版

 

2.程式碼

      /// <summary>
        /// 將網頁轉為pdf檔案
        /// </summary>
        /// <param name="filePath">檔案路徑/目錄</param>
        /// <param name="fileName">檔名</param>
/// <param name="url">網頁url</param> public bool ConvertWebpageToPDF(string filePath, string fileName, string url) { if (Directory.Exists(filePath) == false) Directory.CreateDirectory(filePath); try { HtmlToPdfDocument htmlToPdfDocument
= new HtmlToPdfDocument(); GlobalSettings globalSettings = new GlobalSettings(); globalSettings.ProduceOutline = new bool?(true); //html網頁內容的寬高 double width = 100; double.TryParse(txt_width.Text, out width); double height = 120
; double.TryParse(txt_height.Text, out height); //設定pdf寬高 double proportion = 1.26; width /= proportion; height = Math.Floor(height / proportion); string Width = width.ToString(); string Height = height.ToString(); globalSettings.PaperSize = new PechkinPaperSize(Width, Height); //設定pdf文件四周空白邊距 globalSettings.Margins.Top = 0; globalSettings.Margins.Right = 0; globalSettings.Margins.Bottom = 0; globalSettings.Margins.Left = 0; globalSettings.Margins.Unit = Unit.Centimeters; string pageUrl = url; ObjectSettings objectSettings = new ObjectSettings(); double value = 1; objectSettings.HtmlText = string.Empty; objectSettings.PageUrl = pageUrl; objectSettings.LoadSettings.BlockLocalFileAccess = true; objectSettings.LoadSettings.ZoomFactor = new double?(value); objectSettings.WebSettings.PrintMediaType = new bool?(true); objectSettings.WebSettings.PrintBackground = new bool?(false); htmlToPdfDocument.GlobalSettings = globalSettings; htmlToPdfDocument.Objects.Add(objectSettings); IPechkin pechkin = Factory.Create(); byte[] array = pechkin.Convert(htmlToPdfDocument); string path = string.Empty; if (array == null) { return false; } path = Path.Combine(filePath, fileName); using (FileStream fileStream = new FileStream(path, FileMode.Create)) { fileStream.Write(array, 0, array.Length); fileStream.Flush(); fileStream.Close(); FileStream fs = new FileStream(path, FileMode.Open); byte[] file = new byte[fs.Length]; fs.Read(file, 0, file.Length); fs.Close(); return true; } } catch (Exception ex) { return false; } }

 

 

二、使用TuesPechkin轉pdf

wkhtmltopdf是一個外掛,首先要下載https://wkhtmltopdf.org/downloads.html

 

 

 下載後有使用說明:需要使用cmd安裝到本地目錄

程式碼:

public void wkhtmltopdf(string filePath, string fileName, string url)
        {
            Process p = new Process();
            //wkhtmltopdf外掛安裝的地址
            string dllstr = AppDomain.CurrentDomain.BaseDirectory + "wkhtmltopdf\\wkhtmltopdf.exe";
            //string dllstr = "C:\\Windows\\System32\\wkhtmltopdf.exe";
            if (System.IO.File.Exists(dllstr))
            {
                string savepath = Path.Combine(filePath, fileName);
                p.StartInfo.FileName = dllstr;

                StringBuilder paramsBuilder = new StringBuilder();
                paramsBuilder.Append("--page-width " + txt_width.Text + "mm ");
                paramsBuilder.Append("--zoom 1.2 ");
                paramsBuilder.Append("--disable-smart-shrinking ");
                paramsBuilder.Append("--page-height " + txt_height.Text + "mm ");
                paramsBuilder.Append("--margin-bottom 0mm ");
                paramsBuilder.Append("--margin-left 0mm ");
                paramsBuilder.Append("--margin-right 0mm ");
                paramsBuilder.Append("--margin-top 0mm ");
                paramsBuilder.AppendFormat("\"{0}\" \"{1}\"", url, savepath);
                p.StartInfo.Arguments = paramsBuilder.ToString();
                //p.StartInfo.Arguments = " \"" + url + "\"  \"" + savepath + "\"";

                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;

                p.Start();
                p.WaitForExit();
            }
        }

備註: 

以上2種方法生成pdf效果都非常好,css也能完美支援。

都是通過請求網頁url,將整個網頁生成pdf。

如果你是客戶端,只有html文字,沒有網頁。可以先用html文字在本地生成一個html檔案,本地html檔案也是可以生成的pdf的哦

本地生成html檔案方法可以看我另外一篇:

https://www.cnblogs.com/liuzheng0612/p/16148963.html