Вывод данных в PDF из GridView имеет проблемы с кодированием - PullRequest
2 голосов
/ 12 августа 2011

Я генерирую PDF (используя iTextSharp) из сетки, представленной на странице, но при выводе PDF возникают проблемы с кодировкой. Например это на странице:

Aplicação para posicionar

В PDF выглядит так:

Aplicação para posicionar

Я генерирую это непосредственно из таблицы, так как мне нужен пользовательский ввод (например, флажки), поэтому я не могу читать эти данные из базы данных. Я предполагаю, что какое-то кодирование / декодирование в порядке, но я совершенно растерялся.

Этапы создания PDF:

BaseFont helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
Font helvetica14 = new Font(helvetica, 14, Font.NORMAL);
Font helvetica12BOLDITALIC = new Font(helvetica, 12, Font.BOLDITALIC);
Font helvetica8BOLDITALIC = new Font(helvetica, 8, Font.BOLDITALIC);
Font helvetica6 = new Font(helvetica, 6, Font.NORMAL);

//Create PDF document
Document doc = new Document(PageSize.A4);
MemoryStream outputStream = new MemoryStream();
PdfWriter.GetInstance(doc, outputStream);
doc.Open();


        //Add title
        doc.Add(new Paragraph(importantlblTitleGlobal + "\n\n\n\n", helvetica14));

        //Copy the Api Transaction table
        if (detailsApiTransactionRowCount > 1)
        {
            //Create PDF table
            PdfPTable tableDetailsInput = new PdfPTable(detailsApiTransactionCellCount);


            //Create title table
            PdfPCell cell = new PdfPCell(new Phrase("Api Transaction List", helvetica12BOLDITALIC));
            cell.BackgroundColor = new BaseColor(128, 128, 128);
            cell.Colspan = detailsApiTransactionCellCount;
            cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            tableDetailsInput.AddCell(cell);

            string[] headers = { "Transaction Name", "Transaction Description" };
            for (iteratorCell = 0; iteratorCell < detailsApiTransactionCellCount; iteratorCell++)
            {
                PdfPCell newCell = new PdfPCell(new Phrase(headers[iteratorCell], helvetica8BOLDITALIC));
                newCell.BackgroundColor = new BaseColor(192, 192, 192);
                tableDetailsInput.AddCell(newCell);
            }

            //Create content table
            for (iteratorRow = 0; iteratorRow < detailsApiTransactionRowCount; iteratorRow++)
            {
                for (iteratorCell = 0; iteratorCell < detailsApiTransactionCellCount; iteratorCell++)
                {
                    Phrase newPhrase = new Phrase(apiTransactionListGrid.Rows[iteratorRow].Cells[iteratorCell].Text, helvetica6);
                    tableDetailsInput.AddCell(newPhrase);
                }
            }

            doc.Add(tableDetailsInput);
        }


        //Line break
        doc.Add(new Paragraph("\n\n\n"));

        //Copy the INPUT/OUTPUT table
        if (detailsInputOutputRowCount > 0)
        {
            //Create PDF table
            PdfPTable tableDetailsInputOutput = new PdfPTable(detailsInputOutputCellCount);


            //Create title table
            PdfPCell cell = new PdfPCell(new Phrase("Input/Output Details", helvetica12BOLDITALIC));
            cell.BackgroundColor = new BaseColor(128, 128, 128);
            cell.Colspan = detailsInputOutputCellCount;
            cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            tableDetailsInputOutput.AddCell(cell);


            //Create headers table
            string[] headers = { "Name", "Format", "Description", "Observation", "isInput", "isOutput", "SpecialType" };
            for (iteratorCell = 0; iteratorCell < detailsInputOutputCellCount; iteratorCell++)
            {
                PdfPCell newCell = new PdfPCell(new Phrase(headers[iteratorCell], helvetica8BOLDITALIC));
                newCell.BackgroundColor = new BaseColor(192, 192, 192);
                tableDetailsInputOutput.AddCell(newCell);
            }

            for (iteratorRow = 0; iteratorRow < detailsInputOutputRowCount; iteratorRow++)
            {
                for (iteratorCell = 0; iteratorCell < detailsInputOutputCellCount; iteratorCell++)
                {
                    switch (iteratorCell)
                    {
                        case 3:
                            {
                                if (apiInputOutputGrid.Rows[iteratorRow].Cells[iteratorCell].Text == "&nbsp;")
                                    tableDetailsInputOutput.AddCell(new Phrase("", helvetica6));
                                else
                                    tableDetailsInputOutput.AddCell(new Phrase(apiInputOutputGrid.Rows[iteratorRow].Cells[iteratorCell].Text, helvetica6));
                            }
                            break;
                        case 4:
                            {
                                if (iteratorRow >= 9)
                                {
                                    Phrase newPhrase = new Phrase("", helvetica6);
                                    if (booleanIsInput[iteratorRow])
                                    {
                                        newPhrase = new Phrase("X", helvetica6);
                                        tableDetailsInputOutput.AddCell(newPhrase);
                                    }
                                    else
                                        tableDetailsInputOutput.AddCell(newPhrase);
                                }
                                else
                                {
                                    Phrase newPhrase = new Phrase("", helvetica6);
                                    PdfPCell newCell = new PdfPCell(newPhrase);
                                    newCell.BackgroundColor = new BaseColor(192, 192, 192);
                                    tableDetailsInputOutput.AddCell(newCell);
                                }
                            }
                            break;
                        case 5:
                            {
                                if (iteratorRow >= 9)
                                {
                                    Phrase newPhrase = new Phrase("", helvetica6);
                                    if (booleanIsOutput[iteratorRow])
                                    {
                                        newPhrase = new Phrase("X", helvetica6);
                                        tableDetailsInputOutput.AddCell(newPhrase);
                                    }
                                    else
                                        tableDetailsInputOutput.AddCell(newPhrase);
                                }
                                else
                                {
                                    Phrase newPhrase = new Phrase("", helvetica6);
                                    PdfPCell newCell = new PdfPCell(newPhrase);
                                    newCell.BackgroundColor = new BaseColor(192, 192, 192);
                                    tableDetailsInputOutput.AddCell(newCell);
                                }
                            }
                            break;
                        case 6:
                            {
                                tableDetailsInputOutput.AddCell(new Phrase(specialType[iteratorRow], helvetica6));
                            }
                            break;
                        default:
                            tableDetailsInputOutput.AddCell(new Phrase(apiInputOutputGrid.Rows[iteratorRow].Cells[iteratorCell].Text, helvetica6));
                            break;
                    }
                }
            }

            doc.Add(tableDetailsInputOutput);
        }



                //CloseDocument
                doc.Close();

                //Clear the response buffer'
                Response.Clear();

                //Set the output type as a PDF'
                Response.ContentType = "application/pdf";

                //Disable caching'
                Response.AddHeader("Expires", "0");
                Response.AddHeader("Cache-Control", "");

                //Set the filename'
                string filename = "filename.pdf";
                filename = filename.Replace(' ', '_');
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

                //Set the length of the file so the browser can display an accurate progress bar'
                Response.AddHeader("Content-length", outputStream.GetBuffer().Length.ToString());

                //Write the contents of the memory stream'
                Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length);

                //Close the response stream'
                Response.End();

Есть какие-нибудь намеки?

РЕДАКТИРОВАТЬ: добавить новую строку. Страница UTF-8, когда я определяю базовый шрифт, я не могу найти UTF в константах iTextSharp. РЕДАКТИРОВАТЬ 2: Также я только что проверил свойства файла PDF в Adobe Reader, и он говорит, что это кодировка Ansi.

Спасибо.

Ответы [ 3 ]

2 голосов
/ 12 августа 2011

Попробуйте декодировать текст из сетки, т.е. вместо

apiInputOutputGrid.Rows[iteratorRow].Cells[iteratorCell].Text

используйте (из System.Web):

HttpUtility.HtmlDecode(apiInputOutputGrid.Rows[iteratorRow].Cells[iteratorCell].Text)
0 голосов
/ 12 августа 2011

Либо проблема с кодировкой в ​​компоненте pdf, либо анализ pdf, либо данные, возвращаемые из сетки, которые, вероятно, не являются новой информацией:) Проверьте результаты сетки и посмотрите на каждое поле и т. Д. Есть ли какие-либо из них? закодированы? Что-то такое html-кодирование - поэтому нужно выяснить, является ли он вашим сеточным кодом или кодом PDF.

0 голосов
/ 12 августа 2011

Как насчет добавления этого к вашей функции:

Response.charset="utf-8"

... или какова должна быть кодировка, если не utf-8 - возможно, латинский 1?

В противном случае этот пост SO выглядит так, как будто он может быть связан с вашим: Html в pdf отсутствуют некоторые символы (itextsharp)

...