如何在asp.net中使用iTextSharp创建PDF

时间:2018-01-17 15:07:45

标签: asp.net pdf itext

有人能告诉我如何在asp.net中使用iTextSharp.text创建PDF文件,但标题,字体大小应该符合我们的需要吗?

1 个答案:

答案 0 :(得分:-1)

Document pdfDoc = new Document(PageSize.A4, 25f, 20f, 20f, 10f);

using (MemoryStream memoryStream = new MemoryStream())
{
    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
    Phrase phrase = null;
    PdfPCell cell = null;
    Color color = null;
    pdfDoc.Open();

    int columns = grdGridPrint.Columns.Count;
    // Table and PdfTable classes removed in version 5.XXX
    PdfPTable table = new PdfPTable(columns);
    // table.TotalWidth = 500f;
    phrase = new Phrase();

    phrase.Add(new Chunk("Heading in PDF \n", FontFactory.GetFont("Arial", 14, Font.BOLD, Color.BLACK)));

    phrase.Add(new Chunk("\n", FontFactory.GetFont("Arial", 6, Font.NORMAL, Color.BLACK)));
    cell = ClsPDF.PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
    cell.VerticalAlignment = PdfCell.CHUNK;

    // table.AddCell(cell);
    cell.Colspan = 7;
    // Colspan for Giving Spaces to Heading if you have to show data in grid of 10 columns that time Colspan =10 
    table.AddCell(cell);
    //table.HeaderRows = 1;
    iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, Color.BLACK);
    // padding can only be set for cells, __NOT__ PdfPTable object
    int padding = 2;
    float[] widths = new float[columns];
    for (int x = 0; x < columns; x++)
    {
        widths[x] = (float)grdGridPrint.Columns[x].ItemStyle.Width.Value;
        string cellText = Server.HtmlDecode(grdGridPrint.HeaderRow.Cells[x].Text);
        // Cell and Color classes are gone too
        cell = new PdfPCell(new Phrase(cellText, fontTable))
        {

        };
        table.AddCell(cell);
    }
    // next two lines set the table's __ABSOLUTE__ width
    table.SetTotalWidth(widths);
    table.LockedWidth = true;

    for (int i = 0; i < grdGridPrint.Rows.Count; i++)
    {
        if (grdGridPrint.Rows[i].RowType == DataControlRowType.DataRow)
        {
            for (int j = 0; j < columns; j++)
            {
                string cellText = Server.HtmlDecode(grdGridPrint.Rows[i].Cells[j].Text);
                cell = new PdfPCell(new Phrase(cellText, fontTable))
                {
                    Padding = padding
                };
                //if (i % 2 != 0)
                //{
                //    //cell.BackgroundColor = new System.Drawing.ColorTranslator.FromHtml("#C2D69B");

                //}
                table.AddCell(cell);
            }
        }
    }

    Response.ContentType = "application/pdf";

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    pdfDoc.Add(table);
    pdfDoc.Close();