Export the gridview as PDF using itextsharp

Source: Internet
Author: User

This section describes how to convert the content displayed in the gridview to a PDF document) you can use this program to save the converted PDF file to a specified folder on the server, and then automatically prompt you whether to save the obtained PDF file locally.

Each page of the converted PDF document contains the header of the gridview.

1. Obtain itextsharp. dll (available from the Internet)

2. add reference to this DLL

3. The following describes the conversion class gridviewtopdf. CS and writes a conversion method convertgridviewtopdf ()

Class gridviewtopdf. CS is as follows:

Using System; using System. web; using System. web. UI; using System. web. UI. webControls; //************************************** * *** // introduce the namespace using System. text; using System. IO; using iTextSharp. text; using iTextSharp.text.pdf; //************************************** * *** // <summary> // summary of GridViewToPdf /// </summary> public class GridViewToPdf {public GridViewToPdf () {}# region ConvertGrdiVie Change wToPdf to "GridView" as a PDF document, each page has a header /// <summary> /// convert the GridView to a PDF document /// </summary> /// <param name = "pobjGrdv"> to be converted </param> /// <param name = "PDFFileName"> file name when saving the PDF file on the server </param> /// <param name = "FontPath"> physical path where the font of a PDF image is dumped </param> // <param name = "FontSize"> font size </param> /// <returns> indicates whether the call is successful </param> /returns> public static void ConvertGrdiViewToPdf (GridView pobjGrdv, string PDFFileName, string FontPath, Float FontSize) {// the file name string strFileName = PDFFileName + "when the server saves the PDF file ". pdf "; // all data in the GridView is output to pobjGrdv. allowPaging = false; // *************************** int countColumns = pobjGrdv. columns. count; int countRows = pobjGrdv. rows. count; if (countColumns! = 0 & amp; countRows! = 0) {// initialize a target Document class // document Document = new Document (); // The vertical layout mode. The size is A4, the four margins are 25 Document document = new Document (PageSize. a4, 0, 0, 0, 0); // horizontal layout mode. The size is A4 and the surrounding margin is 50 // Document doc = new Document (PageSize. a4.rotate (), 50, 50, 50, 50); // call the PDF Writing Method stream. // note that FileMode-Create indicates that if the target file does not exist, it is created. If yes, It is overwritten. Specified writer = Specified writer. getInstance (document, new FileStream (HttpContext. current. server. mapPath (strFileName), FileMode. create); try {// Create the font BaseFont baseFont = BaseFont in the PDF document. createFont (FontPath, BaseFont. IDENTITY_H, BaseFont. NOT_EMBEDDED); // create a Font font Font = new Font (baseFont, FontSize) based on the font path and Font size attributes ); // Add a footer // HeaderFooter footer = new HeaderFooter (new Phrase (footertxt), true); HeaderFoo Ter footer = new HeaderFooter (new Phrase ("--", font), new Phrase ("--", font); footer. border = Rectangle. NO_BORDER; // do not display two crosslines footer. alignment = Rectangle. ALIGN_CENTER; // center the page number in the document. footer = footer; // open the target document Object document. open (); // ************************** // create a PdfPTable in PDF format based on the data table content table = new PdfPTable (countColumns ); // iTextSharp. text. table table = new iTextSharp. text. table (pobjGrdv. C Olumns. count); // Add a header // set the background color of the header // table. defaultCell. backgroundColor = Color. GRAY; // OK // table. defaultCell. backgroundColor = // (iTextSharp. text. color) System. drawing. color. fromName ("# 3399FF"); // NG table. defaultCell. backgroundColor = iTextSharp. text. color. LIGHT_GRAY; // table. defaultCell. backgroundColor = System. drawing. color. dodgerBlue; // Add the header for (int j = 0; j <countColumns; j ++) {table. add Cell (new Phrase (pobjGrdv. headerRow. cells [j]. text, font); // OK} // tell the program that this line is the header. When the page number is greater than 1, the program automatically adds the header to you. Table. headerRows = 1; // Add data // set the table body background color table. defaultCell. backgroundColor = Color. WHITE; // traverse the data row of the original gridview for (int I = 0; I <countRows; I ++) {for (int j = 0; j <countColumns; j ++) {table. addCell (new Phrase (pobjGrdv. rows [I]. cells [j]. text, font) ;}}// Add the converted table data document to the target document. add (table) ;}catch (Exception) {throw ;}finally {// close the target file document. close (); // Close the write stream writer. close () ;}// a prompt box is displayed. Whether the user downloads and saves the file to the local try {// here is the location of your file in the project. The String FullFileName = System is written in the root directory. web. httpContext. current. server. mapPath (strFileName); FileInfo DownloadFile = new FileInfo (FullFileName); System. web. httpContext. current. response. clear (); System. web. httpContext. current. response. clearHeaders (); System. web. httpContext. current. response. buffer = false; System. web. httpContext. current. response. contentType = "applica Tion/octet-stream "; System. web. httpContext. current. response. appendHeader ("Content-Disposition", "attachment; filename =" + System. web. httpUtility. urlEncode (DownloadFile. fullName, System. text. encoding. UTF8); System. web. httpContext. current. response. appendHeader ("Content-Length", DownloadFile. length. toString (); System. web. httpContext. current. response. writeFile (DownloadFile. fullName);} catch (effecti On) {throw;} finally {System. web. httpContext. current. response. flush (); System. web. httpContext. current. response. end () ;}} else {System. web. httpContext. current. response. write ("<script type = 'text/javascript '> alert ('data is empty, not worth exporting pdf! '); </Script> ") ;}// then, you can call it in the Event code of the button to call the conversion. // assume that the name of the passed GridView is GridView1. // assume that the name of the file to be saved is the ID of the GridView. // assume that the font is used. use simsun (select a directory based on your computer's actual situation) // assume the font size is 14 // GridViewToPdf. convertGridViewToPdf (this. gridView1, // this. gridView1.ID. toString (), "c: \ winnt \ FONTS \ simsun. ttc, 1 ", 14); # endregion}

4. Call Method for external use:

Using system. io; using itextsharp. text; /// <summary> /// export to PDF /// </Summary> /// <Param name = "sender"> </param> /// <Param name = "E"> </param> protected void button_export1__click (Object sender, eventargs e) {try {// assume that the ID of the gridview is gridview_checkstat success = false; gridview_checkstat.allowsorting = false; // the query condition string materialtype = this.txt materialtype is obtained from the page. text; string depottype = This. dropdownlist_depottype.selectedvalue; string depotid = This. dropdownlist_depot.selectedvalue; string goodsname = this.txt goodsname. text. trim (); // fill in the data source gridview_checkstat.datasource = checkstatbll. getcheckstatbycondition (materialtype, depotid, depottype, goodsname); // bind the data source gridview_checkstat.databind (); // call the preceding conversion method // pass the following method gridviewtopdf to the bound gridview. convertgridviewtopdf (this. gridview_checkstat, this. gridview_checkstat.id.tostring (), @ "C: \ WINDOWS \ fonts \ msyh. TTF ", 8);} catch (incluentexception de) {response. write (de. tostring ());}}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.