0

我喜欢使用 iTextSharp.dll 将 GridView 转换为 PDF。但是我的 GridView 中有西里尔字符,它们没有出现在 pdf 文档中。这是我正在使用的代码

        Response.Clear(); //this clears the Response of any headers or previous output
        Response.Buffer = true; //ma
        Response.ContentType = "application/pdf";
        iTextSharp.text.pdf.BaseFont arial = iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", "Identity-H", iTextSharp.text.pdf.BaseFont.EMBEDDED);
        Response.AddHeader("content-disposition", "attachment;filename=Pregled.pdf");


        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        StringWriter sw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(sw);

        gvTekovenKorisnik.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();

我读到我必须更改 baseFont 但我不知道在更改后将它放在代码中的位置。有人可以帮助我吗?

4

2 回答 2

1

我提出以下变体

protected void btnGridViewToPdf_Click(object sender, EventArgs e)
    {
        GridViewToPdf();
    }
        private void GridViewToPdf()
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Reestr.pdf");
            //подключаепм шрифт
            String FONT_LOCATION = Server.MapPath("~/fonts/arial.ttf");
            BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
            //подключили
            //создаем PDF документ
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);  
            pdfDoc.Open();
            //Создадим таблицу 
            PdfPTable table = new PdfPTable(2);
            //Создадим заголовок
            table.AddCell(new PdfPCell(new Paragraph("\nРеестр закупок\n\n", font)) { Colspan = 2, HorizontalAlignment=1 });
            //столбцы шириной в пропорции - 1/15 и 14/15
            float[] widths = new float[] { 1f, 14f };
            table.SetWidths(widths);
            //оставлять зазор до и после таблицы
            table.SpacingBefore = 10f;
            table.SpacingAfter = 10f;
            PdfPCell cell = new PdfPCell(new Phrase());
            cell.Padding = 5;
            cell.Colspan = 3;
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    Label _lblN = row.FindControl("lblN") as Label;
                    String lblN = _lblN.Text.ToString();
                    Label _lblnameOrder = row.FindControl("lblnameOrder") as Label;
                    String lblnameOrder = _lblnameOrder.Text.ToString();
                    Label _lblsummaOrder = row.FindControl("lblsummaOrder") as Label;
                    String lblsummaOrder = _lblsummaOrder.Text.ToString();

                    ///
                    PdfPCell cell1 = new PdfPCell(new Phrase(lblN, font)) { HorizontalAlignment = 1, VerticalAlignment= 1 };
                    table.AddCell(cell1);
                    ///

                    //table.AddCell(new PdfPCell(new Paragraph(lblN, font)) { HorizontalAlignment = 1 });

                    table.AddCell(new PdfPCell(new Paragraph("Наименование закупки: \n" + lblnameOrder + "\nСумма: \n" + lblsummaOrder, font)));
                }
            }
            pdfDoc.Add(table);
            pdfDoc.Close();
            Response.End();

        }
于 2012-08-02T08:42:34.383 回答
0

我以这种方式更改了我的代码,所以我得到了解决方案

public  string arialFile = AppDomain.CurrentDomain.BaseDirectory + "arial.ttf";

iTextSharp.text.pdf.BaseFont arial = iTextSharp.text.pdf.BaseFont.CreateFont(arialFile, "Identity-H", iTextSharp.text.pdf.BaseFont.EMBEDDED);
iTextSharp.text.Font f = new iTextSharp.text.Font(arial, 12);
//Create a table
PdfPTable table = new PdfPTable(colCount);           
table.HorizontalAlignment = 0;

//create an array to store column widths
int[] colWidths = new int[gvTekovenKorisnik.Columns.Count];

PdfPCell cell;
string cellText;
//create the header row
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
    //set the column width
    //colWidths[colIndex] = (int)gv.Columns[colIndex].ItemStyle.Width.Value;

    //fetch the header text
    cellText = Server.HtmlDecode(gv.HeaderRow.Cells[colIndex].Text);


    cell = new PdfPCell(new Phrase(cellText,f));


    //set the background color for the header cell
    cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#75B082"));

    //add the cell to the table. we dont need to create a row and add cells to the row
    //since we set the column count of the table to 4, it will automatically create row for
    //every 4 cells
    table.AddCell(cell);
}

//export rows from GridView to table
for (int rowIndex = 0; rowIndex < gv.Rows.Count; rowIndex++)
{
    if (gvTekovenKorisnik.Rows[rowIndex].RowType == DataControlRowType.DataRow)
    {
        for (int j = 0; j < colCount; j++)
        {
            //fetch the column value of the current row
            cellText = Server.HtmlDecode(gvTekovenKorisnik.Rows[rowIndex].Cells[j].Text);

            //create a new cell with column value
            cell = new PdfPCell(new Phrase(cellText));

            //Set Color of Alternating row

            //add the cell to the table
            table.AddCell(cell);
        }
    }
}

//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

//open the stream
pdfDoc.Open();

//add the table to the document
pdfDoc.Add(table);

//close the document stream
pdfDoc.Close();

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + "filename=Pregled.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

}

其中 colCount 是在 RowDataBound 方法处理中分配的变量。我在我的项目中从 C:\Windows\Fonts 复制了 arial.ttf 字体。

于 2012-07-14T19:37:56.420 回答