sunil kumar Ответов: 1

В документе нет страниц.


I got this error in online server, Exception Details: System.IO.IOException: The document has no pages.


Что я уже пробовал:

<pre><pre> byte[] bytes = null;
           var cssText = File.ReadAllText(MapPath("~/css/bootstrap.min.css"));

            //Read our HTML as a .Net stream
            using (var sr = new StringReader(htmlTable.ToString()))
            {
                //try
                //{
                //Standard PDF setup using a MemoryStream, nothing special
                // using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
                using (var ms = new MemoryStream())
                {

                    using (var pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f))
                    {

                        //Bind a parser to our PDF document
                        using (var htmlparser = new HTMLWorker(pdfDoc))
                        {

                            //Bind the writer to our document and our final stream
                            using (var w = PdfWriter.GetInstance(pdfDoc, ms))
                            {

                                pdfDoc.Open();

                                //Parse the HTML directly into the document
                                htmlparser.Parse(sr);

                                pdfDoc.Close();

                                //Grab the bytes from the stream before closing it
                                bytes = ms.ToArray();
                            }
                        }
                    }
                }
                //}
                //catch (Exception ex)
                //{

                //}
            }

            //Assuming that the above worked we can now finally modify the HTTP response
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=xyz.pdf");
            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            //Send the bytes from the PDF
            Response.BinaryWrite(bytes);
            Response.End();

Richard MacCutchan

Где происходит ошибка?

sunil kumar

локально он работает , но ошибка в Интернете, я думаю, что ошибка здесь происходит
использование (var htmlparser = new HTMLWorker(pdfDoc))

RickZeeland

Какую библиотеку PDF вы используете ?

Maciej Los

Похоже, что iTextSharp уже используется ;)

sunil kumar

с помощью iTextSharp.текст;
с помощью iTextSharp.текст.HTML-код.simpleparser;
с помощью iTextSharp.текст.формат PDF;

1 Ответов

Рейтинг:
0

Maciej Los

Pdf-документ пуст, потому что вы ничего в него не вложили.

pdfDoc.Open();
//Parse the HTML directly into the document
htmlparser.Parse(sr); //we don't know what Parse method returns, but result is not written into a pdf document
pdfDoc.Close();


Чтобы иметь возможность что-то написать, вы должны использовать Add() метод. Ниже фрагмент кода добавляет таблицу с пользовательским стилем шрифта:
//define fonts
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, false);
Font bf = new Font(bfTimes, 11);
Font headerf = new Font(bfTimes, 9, Font.ITALIC | Font.BOLD, BaseColor.WHITE);
Font sf = new Font(bfTimes, 9, Font.NORMAL);
//add table
colcount = 3;
table = new PdfPTable(colcount);
widths = new float[] { 1f, 1f, 1f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;
//add headers
for(int c=1; c<=colcount;c++)
{
	s = $"Header {c}";
	PdfPCell header = new PdfPCell(new Phrase(s, headerf));
	header.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
	header.BackgroundColor = BaseColor.DARK_GRAY;
	table.AddCell(header);
}
//add rows
for(int r=1; r<=5; r++)
{
	for(int c=1; c<=colcount;c++)
	{
		s = $"Col {c} Row {r}";
		cell = new PdfPCell(new Phrase(s, sf));
		cell.BackgroundColor = r % 2 == 0 ? BaseColor.WHITE : BaseColor.LIGHT_GRAY;
		table.AddCell(cell);
	}
}
pdfdoc.Add(table);


RickZeeland

Правдоподобно +5 !

Maciej Los

Спасибо, Рик.

sunil kumar

Здесь htmltable который является htmldata и работает локально но ошибка в интернете

using (var sr = new StringReader(htmlTable.Метод toString()))

Maciej Los

Итак, отладьте свою программу, чтобы узнать, что происходит.
Примечание: у меня нет доступа к вашему компьютеру, я не могу читать прямо с вашего экрана и не могу решить вашу проблему на основе такой небольшой части информации.

Richard Deeming

Я думаю HTMLWorkerParse метод записывает в Document передается его конструктору и ничего не возвращает. :)

Maciej Los

Это вполне возможно...