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 に答える