';该文档没有页面';关闭文档时引发错误
本文关键字:文档 错误 | 更新日期: 2023-09-27 18:21:12
我正在输出流上生成、保存和编写PDF。
在对输出流进行写入时,我遇到了一个The document has no page
错误。
问题出在哪里?
string contents;
string fileName = "aaa.pdf";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
hw.AddStyleAttribute("font-size","11px");
abs.RenderControl(hw);
string path = Server.MapPath("../Images/a.png");
contents = sw.ToString();
contents = contents.Replace("../Images/a.png", path);
sw.Close();
hw.Close();
StringReader sr = new StringReader(contents);
System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/pdf/") + fileName, FileMode.Create);
Document pdfDoc = new Document(PageSize.A4, 30,5,35,5);
Document cpdfDoc = new Document(PageSize.A4, 30, 5, 35, 5);
pdfDoc.PageCount = 2;
cpdfDoc.PageCount = 2;
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc,fs);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
fs.Close();
HTMLWorker htmlparser2 = new HTMLWorker(cpdfDoc);
PdfWriter.GetInstance(cpdfDoc, Response.OutputStream);
cpdfDoc.Open();
htmlparser2.Parse(sr);
cpdfDoc.Close();
Response.Write(cpdfDoc);
Response.Flush();
Response.End();
保存时没有问题。我在cpdfDoc.Close();
这条线上出错了。
使用此代码并设置pdf位置。以及图像路径。它正在发挥作用。
string contents = "hi";
string fileName = "aaa.pdf";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
hw.AddStyleAttribute("font-size", "11px");
string path = Server.MapPath("~/Images/a.png");
contents = contents.Replace("~/Images/a.png", path);
sw.Close();
hw.Close();
StringReader sr = new StringReader(contents);
System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/") + DateTime.Now.Ticks, FileMode.Create);
Document pdfDoc = new Document(PageSize.A4, 30, 5, 35, 5);
Document cpdfDoc = new Document(PageSize.A4, 30, 5, 35, 5);
pdfDoc.PageCount = 2;
cpdfDoc.PageCount = 2;
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, fs);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
fs.Close();
HTMLWorker htmlparser2 = new HTMLWorker(cpdfDoc);
PdfWriter.GetInstance(cpdfDoc, Response.OutputStream);
cpdfDoc.Open();
htmlparser2.Parse(sr);
不要使用这条线路
contents = sw.ToString();