【问题标题】:how to convert DataGridView to pdf in utf8如何在 utf8 中将 DataGridView 转换为 pdf
【发布时间】:2016-01-03 05:17:33
【问题描述】:

我使用iTextSharp.dll 在c# 中将dataGridView 转换为pdf 它不会将pdf 设为utf8,所以我有两个问题:

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();
            }



        }
    }

【问题讨论】:

  • 找一个波斯语支持​​的 dll 代替
  • @AlexJolig 感谢您的重播。你的意思是没有办法将它保存为 UTF8?

标签: c# datagridview itextsharp


【解决方案1】:

尝试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 */
}

请注意:

本文代码示例提供的 iTextSharp DLL 具有 已修改为允许 GridView 样式、颜色和格式。因此,如果 您使用 iTextSharp 的任何其他副本 GridView 样式、颜色和 格式不会在导出的 PDF 中呈现。

编辑

作为第二种解决方案,在this answer 中有一个link 可以帮助您解决问题。

This GridView exporting library 支持 RTL

编辑 2

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

在处理 Unicode 字符和 iTextSharp 时,有几个 你需要照顾的事情。你已经做过的第一个和 那就是获得支持您的字符的字体。第二件事 是你想用 iTextSharp 实际注册字体,这样 它意识到这一点。

//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);

现在我们有了字体,我们需要创建一个StyleSheet 对象 告诉 iTextSharp 何时以及如何使用它。

//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");

您还需要做的一个非 HTML 部分是设置一个特殊的 encoding 参数。此编码特定于 iTextSharp 并在 您希望它是Identity-H。如果你不设置这个然后 默认为Cp1252 (WINANSI)。

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

最后,我们需要将样式表传递给ParseToList 方法:

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

将所有这些放在一起,从打开到关闭,您将拥有:

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

编辑

在您的评论中,您显示了指定覆盖字体的 HTML。 iTextSharp 不会在系统中搜索字体及其 HTML 解析器 不使用字体后备技术。 HTML/CSS 中指定的任何字体 必须手动注册。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2015-09-24
    • 2013-06-12
    • 2016-12-08
    • 2017-11-15
    • 2013-06-06
    • 2018-12-08
    相关资源
    最近更新 更多