Open Generated pdf file through code directly without saving it onto the disk

瘦欲@ 提交于 2019-12-03 08:52:02

Almost every time that something accepts a FileStream is actually really accepts a generic System.IO.Stream object which FileStream is a subclass of. This means that you can instead use its cousin System.IO.MemoryStream which is what you are looking for:

        byte[] bytes;
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
            using (iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate())) {
                using (iTextSharp.text.pdf.PdfWriter w = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms)) {
                    doc.Open();
                    doc.NewPage();
                    doc.Add(new iTextSharp.text.Paragraph("Hello world"));
                    doc.Close();
                    bytes = ms.ToArray();
                }
            }
        }
        //Do whatever you want with the byte array here

You don't have to create the byte array if you don't want, I was just showing how to create a PDF and give you something ".net-like" for you to work with.

I was able to get it work finally.

  using (var ms = new MemoryStream())
      {
          using (var document = new Document(PageSize.A4,50,50,15,15))
          {
              PdfWriter.GetInstance(document, ms); 
              document.Open();
              document.Add(new Paragraph("HelloWorld"));
              document.Close();
          }
          Response.Clear();
          //Response.ContentType = "application/pdf";
          Response.ContentType = "application/octet-stream";
          Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
          Response.Buffer = true; 
          Response.Clear();
          var bytes = ms.ToArray();
          Response.OutputStream.Write(bytes, 0, bytes.Length);
          Response.OutputStream.Flush();
      } 

This Works for me.

using (var ms = new MemoryStream())
  {

      using (var document = new Document(PageSize.A4,50,50,15,15))
      {

        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, ms);


        // step 3
        document.Open();

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.Parse(new StringReader(--Your HTML--));


        // step 5
        document.Close();
      }  
      Byte[] FileBuffer = ms.ToArray();
      if (FileBuffer != null)
      {
          Response.ContentType = "application/pdf";
          Response.AddHeader("content-length", FileBuffer.Length.ToString());
          Response.BinaryWrite(FileBuffer);
      }

  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!