2

我正在输出流上生成、保存和写入 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();

4

1 回答 1

1

使用此代码并设置您的 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();
于 2013-07-05T10:16:18.570 回答