iTextSharp 製做 PDF文件(顯示錶格,圖片)

根據業務要求,須要把數據庫中的數據在PDF中顯示,查閱了不少資料,選擇iTextSharp.dll來幫助本身完成。通過一天的資料整理,半天的DEMO設計,特把勞動成功作一記錄。javascript

生成PDF文件的代碼:java

/// <summary>
  /// 數據輸出到pdf
  /// </summary>
  /// <param name="selectData"></param>
    void PrintPdf(DataTable dt)
    {
       //第一步 建立Document
        //橫向A4紙張
        Rectangle Rec = new Rectangle(PageSize.A4.Rotate());
        //public Document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);

        Document doc = new Document(Rec,36F,36F,40F,40F);
       

      //第二步  建立Writer實例
         //建立臨時文件
        string Path = Server.MapPath("../TempFile/");
        if (Directory.Exists(Path) == false)
        {
            Directory.CreateDirectory(Path);
        }
        string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
        Path += FileName;
        PdfWriter.GetInstance(doc, new FileStream(Path, FileMode.Create));
       
       //第三步  打開Document
        doc.Open();
      

       //  第四步   寫Document 
  
        PrintPdfTable(ref doc, dt, Rec);
         
    
       //第五步 關閉Document
        doc.Close();
       
        doc.Dispose();
        char[] SChar = new char[] { '/' };
        string Url = Request.Url.ToString();
        string[] sUrl = Url.Split(SChar);
        Url = "";
        for (int i = 0; i <= sUrl.Length - 2; i++)
        {
            Url += sUrl[i];
        }
        Url = "../TempFile/" + FileName;
        Response.Write("<script language=\"javascript\">window.open('" + Url + "');</script>");
    }

表格嵌套:把一個子表做爲元素加入父表的一個單元格,例如:mFirstCellT.AddElement(whiteTable);
單元格中顯示圖片:把圖片做爲單元格的背景圖片,例如:數據庫

        System.Drawing.Image img_1 = System.Drawing.Image.FromFile(path);
        iTextSharp.text.Image img0 = iTextSharp.text.Image.GetInstance(img_1, iTextSharp.text.BaseColor.WHITE);

        PdfPCell fiSecondCell = new PdfPCell();
        
        fiSecondCell.Image = img0;

 設置行高:若是是標準表格,設置單元格的行高就OK了。spa

 設置行寬:在造表的時候,PdfPTable SecondTable = new PdfPTable(new float[] { 30F,60F});就OK。設計

設置表格不顯示邊框:設置單元格     sFirstCell.BorderColor = BaseColor.WHITE;sFirstCell.BorderWidth = 0F;
        code

相關文章
相關標籤/搜索