下载PDF或excel有很多方法,Excel很简单,但是PDF通常在CSS和其他很多方面有问题。我对此做了更多的研究,发现使用CutyCapt.exe将网页捕获为PDF或图像更方便。
CutyCapt是什么?
CutyCapt是一个小型的跨平台命令行工具,用于捕获WebKit将web页面呈现为各种矢量和位图格式的方法,包括SVG、PDF、PS、PNG、JPEG、TIFF、GIF和BMP。请参阅IECapt以获取基于Internet Explorer的类似工具。
要求
- 创建PDF的过程是使用一个名为CutyCapt.exe的可执行文件来完成的,下载exe并将其添加到解决方案中。
- 如果我们使用ASP.NET创建项目时,可在重定向页面上调用exe,这个页面将是空白的,在页面加载中有以下代码。
实现
- 创建一个文件名和路径:为了使文件名唯一,我更推荐使用GUID(这是开发人员根据需求和逻辑做出的选择),然后将文件URL添加到一个字符串中。
string filename = Guid.NewGuid() + ".pdf"; //unique file name
// url of the pdf file name
string url = “http://example.org” +"/CutyCapt/" + filename;
- 可执行文件的位置:cutycap.exe的位置被分配给一个字符串。
//location of Executable
string cutycaptLocation = "D:\\CutyCapt";
- 命令创建:用于在ASP中创建命令。NET中,我们使用ProcessStartInfo对象。将不同的参数作为属性赋给对象,如下所示:
a. CreateNoWindow
b. WorkingDirectory
c. FileName
d. Arguments
- 需要转换成PDF格式的网页链接
- 目标文件夹
e. UseShellExecute
// Command for execution
System.Diagnostics.ProcessStartInfo pi = new System.Diagnostics.ProcessStartInfo();
pi.CreateNoWindow = false;
pi.WorkingDirectory = cutycaptLocation;
pi.FileName = cutycaptLocation + "\\CutyCapt.exe";
pi.Arguments = "--url=" + link + " --out-format=pdf -out=" + System.IO.Path.GetFullPath(Server.MapPath("~/CutyCapt")) + "\\" + filename;
pi.UseShellExecute = false;
- 进程执行:ASP中的进程对象.Net用于执行进程,以获取创建的信息。
try {
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using(System.Diagnostics.Process exeProcess = System.Diagnostics.Process.Start(pi)) {
exeProcess.WaitForExit();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
- 重定向到PDF:创建PDF后,浏览器会重定向到加载创建的PDF的PDF链接。
Response.Redirect(url);