如何在C#.Net中生成显示SQL记录的PDF文件?

时间:2017-02-08 21:06:02

标签: c# .net winforms pdf-generation

我正在开发库存管理系统(窗体)。 我有一个 .Net windows窗体,它显示所有订单的列表(在dataGridView 中)。
任务是提供打印或通过电子邮件发送订单详细信息的PDF版本的选项。它包含纯文本(例如问候语)和SQL Server表中的值(例如订单号,日期,项目列表)

我正在努力找出最好的方法。

当用户选择订单而不是为所有订单创建和保存PDF时,生成PDF似乎是明智的。 但我正在努力寻找如何继续下去。

2 个答案:

答案 0 :(得分:0)

protected void ExportToPDF(object sender, EventArgs e)
{
    //Get the data from database into datatable

    string strQuery = "select CustomerID, ContactName, City, PostalCode" +
        " from customers";
    SqlCommand cmd = new SqlCommand(strQuery);
    DataTable dt = GetData(cmd);

    //Create a dummy GridView

    GridView GridView1 = new GridView();
    GridView1.AllowPaging = false;
    GridView1.DataSource = dt;
    GridView1.DataBind();

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition",
        "attachment;filename=DataTable.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End(); 
}

答案 1 :(得分:0)

这个问题过于宽泛,基于意见。但通常很少有办法可以做到这一点

  1. Excel互操作(甚至Word) - 加载您的数据excel并调用excel print to pdf
  2. 通常,Crystal Reports或其他报表库提供“另存为pdf”选项。
  3. 创建一个文件(以任何格式)并使用pdf打印机,这是您安装的软件打印机并从您的代码中调用。有免费的打印机。
  4. 使用像iTextSharp这样的专业库来创建代码中的pdf
  5. 毫无疑问 - 有这样的在线服务,您可以转换您的文件
相关问题