【发布时间】:2015-08-05 14:11:32
【问题描述】:
【问题讨论】:
-
投票结束您的问题,因为它要求我们推荐一个图书馆,这是不允许的。相反,您应该进行自己的研究。谷歌搜索“c# create PDF”给了我很多方便的结果。
【问题讨论】:
你可以试试这个工具,它非常适合 HTML 到 pdf 的转换 http://wkhtmltopdf.org/
这里是将 HTML 字符串转换为 PDF 字节的代码。
public byte[] Convert(string source, string commandLocation)
{
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = commandLocation;
psi.WorkingDirectory = @"D:\" ;// Path.GetDirectoryName(psi.FileName);
// run the conversion utility
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
// note: that we tell wkhtmltopdf to be quiet and not run scripts
string args = "-q -n ";
args += "--disable-smart-shrinking ";
args += "";
args += "--outline-depth 0 ";
args += "--page-size A4 ";
args += " - -";
psi.Arguments = args;
p = Process.Start(psi);
try
{
using (StreamWriter stdin = p.StandardInput)
{
stdin.AutoFlush = true;
stdin.Write(source);
}
//read output
byte[] buffer = new byte[32768];
byte[] file;
using (var ms = new MemoryStream())
{
while (true)
{
int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
ms.Write(buffer, 0, read);
}
file = ms.ToArray();
}
p.StandardOutput.Close();
// wait or exit
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
if (returnCode == 0)
return file;
else
LogManager.Log("Could not create PDF, returnCode:" + returnCode);
}
catch (Exception ex)
{
LogManager.Log("Could not create PDF", ex);
}
finally
{
p.Close();
p.Dispose();
}
return null;
}
这里的“source”是 HTML 代码,而 commandLocation 是 wkhtmltopdf.exe 的完整文件路径,您可以从上面的链接下载。 此函数返回 byte[] 即 pdf 文件,您可以将其保存在磁盘上或通过编写 Response.Write(byte); 返回到浏览器 并更改 MIMIE 类型。
【讨论】:
如果为解决方案付费不会破坏交易,那么我建议使用ABCPdf,您可以使用 API 甚至从视图发送 HTML,如下所示:
public static byte[] PdfForHtml(string html)
{
// Create ABCpdf Doc object
var doc = new Doc();
// Add passed in HTML to ABCpdf Doc object
int theID = doc.AddImageHtml(html);
// Loop through document to create, potentially, multi-page PDF
while (true)
{
if (!doc.Chainable(theID))
{
break;
}
doc.Page = doc.AddPage();
theID = doc.AddImageToChain(theID);
}
// Flatten the PDF
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Flatten();
}
// Get PDF as byte array to eventually pass back
// in controller action method
var pdfbytes = doc.GetData();
doc.Clear();
return pdfbytes;
}
现在您需要一种方法来生成 HTML,该 HTML 将作为原始视图返回,如下所示:
public static string RenderViewToString(Controller controller,
string viewName,
object model,
string masterName)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext,
viewName,
masterName);
var viewContext = new ViewContext(controller.ControllerContext,
viewResult.View,
controller.ViewData,
controller.TempData,
sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
最后,您需要创建一个控制器操作方法来使用上述两种方法,如下所示:
public ActionResult BuildPdf(YourModel model)
{
// Return view if there is an error
if (!ModelState.IsValid)
{
return View(model);
}
// Render view output to string
var report = RenderViewToString(this, "BuildPdf", model, "BuildPdf");
// Convert string to PDF using ABCpdf
var pdfBytes = PdfForHtml(report);
// Return file result
return File(pdfBytes,
System.Net.Mime.MediaTypeNames.Application.Pdf,
"Your_PDF_File_Name_Here.pdf");
}
}
【讨论】:
将其发送到虚拟打印机或使用转换器库,例如iTextSharp。
【讨论】: