如何在utf8中将DataGridView转换为pdf

how to convert DataGridView to pdf in utf8

我正在使用 iTextSharp.dll 在 c# 中将 dataGridView 转换为 pdf 它不会将 pdf 转换为 utf8 所以我有 2 个问题那里:

utf8 问题,它还把列从左到右,我怎样才能让它们从右到左

代码如下:

 private void pictureBox10_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog fdialog = new FolderBrowserDialog();
        DialogResult result = fdialog.ShowDialog();
        if (result == DialogResult.OK) // Test result.
        {
            string file = fdialog.SelectedPath;
            //Creating iTextSharp Table from the DataTable data
            PdfPTable pdfTable = new PdfPTable(dataGridViewX2.ColumnCount);
            pdfTable.DefaultCell.Padding = 3;
            pdfTable.WidthPercentage = 100;
            pdfTable.HorizontalAlignment = Element.ALIGN_RIGHT;
            pdfTable.DefaultCell.BorderWidth = 1;

            //Adding Header row
            foreach (DataGridViewColumn column in dataGridViewX2.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                //cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                pdfTable.AddCell(cell);
            }

            //Adding DataRow
            foreach (DataGridViewRow row in dataGridViewX2.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    pdfTable.AddCell(cell.Value.ToString());
                }
            }

            //Exporting to PDF
            string folderPath = file + "\PDFs\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                pdfDoc.Add(pdfTable);
                pdfDoc.Close();
                stream.Close();
            }



        }
    }

尝试 this tutorial 使用 ITextSharpGridView 导出为 PDF:

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    GridView1.AllowPaging = false;
    GridView1.DataBind();

    BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\Arial.ttf", BaseFont.IDENTITY_H, true);

    iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count);
    int[] widths = new int[GridView1.Columns.Count];
    for (int x = 0; x < GridView1.Columns.Count; x++)
    {
        widths[x] = (int)GridView1.Columns[x].ItemStyle.Width.Value;
        string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);

        //Set Font and Font Color
        iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
        font.Color = new Color(GridView1.HeaderStyle.ForeColor);
        iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

        //Set Header Row BackGround Color
        cell.BackgroundColor = new Color(GridView1.HeaderStyle.BackColor);

        //Important for Arabic, Persian or Urdu Text
        cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        table.AddCell(cell);
    }
    table.SetWidths(widths);

    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
        {
            for (int j = 0; j < GridView1.Columns.Count; j++)
            {
                string cellText = Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);

                //Set Font and Font Color
                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                font.Color = new Color(GridView1.RowStyle.ForeColor);
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                //Set Color of row
                if (i % 2 == 0)
                {
                    //Set Row BackGround Color
                    cell.BackgroundColor = new Color(GridView1.RowStyle.BackColor);
                }

                //Important for Arabic, Persian or Urdu Text
                cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                table.AddCell(cell);
            }
        }
    }

    //Create the PDF Document
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    pdfDoc.Add(table);
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

注意:

The iTextSharp DLL supplied with the code sample of this article has been modified to allow GridView Styles, Colors and Formatting. Thus if you use any other copy of iTextSharp the GridView Styles, Colors and Formatting won’t be rendered in the exported PDF.

编辑

作为第二个解决方案,在 this answer, there's a link 中可能会帮助您解决问题。

This GridView exporting library supports RTL

编辑 2

提及第三个解决方案 here 也可能对您有所帮助

When dealing with Unicode characters and iTextSharp there's a couple of things you need to take care of. The first one you did already and that's getting a font that supports your characters. The second thing is that you want to actually register the font with iTextSharp so that its aware of it.

//Path to our font
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"ARIALUNI.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);

Now that we have a font we need to create a StyleSheet object that tells iTextSharp when and how to use it.

//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");

The one non-HTML part that you also need to do is set a special encoding parameter. This encoding is specific to iTextSharp and in your case you want it to be Identity-H. If you don't set this then it default to Cp1252 (WINANSI).

//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);

Lastly, we need to pass our stylesheet to the ParseToList method:

//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST);

Putting that all together, from open to close you'd have:

doc.Open();

//Sample HTML
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(@"<p>This is a test: <strong>α,β</strong></p>");

//Path to our font
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"ARIALUNI.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);

//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);

//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST);

//Loop through each element, don't bother wrapping in P tags
foreach (var element in list) {
    doc.Add(element);
}

doc.Close();

EDIT

In your comment you show HTML that specifies an override font. iTextSharp does not spider the system for fonts and its HTML parser doesn't use font fallback techniques. Any fonts specified in HTML/CSS must be manually registered.

string lucidaTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"l_10646.ttf");
iTextSharp.text.FontFactory.Register(lucidaTff);