public ActionResult Print()
{
Process process = new Process();
string serverPath = Server.MapPath("~");
string filePath = serverPath + @"\Temp\" + "test.pdf";
//
process.StartInfo.UseShellExecute = true;
//wkhtmltopdf.exe應用程式放的位置
process.StartInfo.FileName = serverPath + @"\wkhtmltopdf.exe";
//參數為網址 + " " + 實體檔案位置
process.StartInfo.Arguments = "http://www.google.com.tw" + " " + filePath;
process.Start();
//等待執行完成
process.WaitForExit();
//
return File(filePath, "application/pdf", "工作報告單");
}
後來因為一些問題有看到黑暗大的一篇文章HTML轉PDF - 使用Pechkin套件,發現有人把wkhtmltopdf轉成DLL可用的套件,但同時又看到[ASP.net MVC] 在Web專案上使用Pechkin套件將網頁轉成PDF檔裡面說到此套件的DLL有BUG,原作者有另外更新此DLL。但我在NuGet上找這個套件時又看到TuesPeckin的套件,查看了一下他骨子裡也是同一套,就想說用看看,果然產出的一模一樣。 相關做法如下:
- 先到NuGet上下安裝TuesPechkin,另外看是在32/64位元環境,分別安裝TuesPechkin.Wkhtmltox.Win32/TuesPechkin.Wkhtmltox.Win64
- 引用程式代碼
using TuesPechkin;
public class HtmlToPDF
{
public IConverter Converter { get; private set; }
public IConverter anotherConverter { get; private set; }
public string Url { get; private set; }
public HtmlToPDF(string url)
{
Url = url;
}
public byte[] GetPDF()
{
var doc = new HtmlToPdfDocument();
var objSettings = new ObjectSettings()
{
PageUrl = Url
};
doc.Objects.Add(objSettings);
Converter =
new ThreadSafeConverter(
new RemotingToolset(
new Win32EmbeddedDeployment(
new TempFolderDeployment())));
var result = Converter.Convert(doc);
//
return result;
}
}
public ActionResult Print()
{
HtmlToPDF htmlToPdf = new HtmlToPDF("http://www.google.com.tw");
byte[] pdfFile = htmlToPdf.GetPDF();
//
return File(pdfFile, "application/pdf", "test.pdf");
}
[C#] 網頁Html轉PDF檔(一行程式碼解決)
wkhtmltopdf官網
HTML轉PDF - 使用Pechkin套件
[ASP.net MVC] 在Web專案上使用Pechkin套件將網頁轉成PDF檔
TuesPeckin
沒有留言 :
張貼留言