在内存中创buildPDF而不是物理文件

如何在内存stream中创buildPDF,而不是使用itextsharp创build物理文件。

下面的代码是创build实际的PDF文件。

相反,如何创build一个byte []并将其存储在byte []中,以便通过函数返回

using iTextSharp.text; using iTextSharp.text.pdf; Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create)); doc.Open();//Open Document to write Paragraph paragraph = new Paragraph("This is my first line using Paragraph."); Phrase pharse = new Phrase("This is my second line using Pharse."); Chunk chunk = new Chunk(" This is my third line using Chunk."); doc.Add(paragraph); doc.Add(pharse); doc.Add(chunk); doc.Close(); //Close document 

使用内存stream切换文件stream。

 MemoryStream memStream = new MemoryStream(); PdfWriter wri = PdfWriter.GetInstance(doc, memStream); ... return memStream.ToArray(); 
 using iTextSharp.text; using iTextSharp.text.pdf; Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); byte[] pdfBytes; using(var mem = new MemoryStream()) { using(PdfWriter wri = PdfWriter.GetInstance(doc, mem)) { doc.Open();//Open Document to write Paragraph paragraph = new Paragraph("This is my first line using Paragraph."); Phrase pharse = new Phrase("This is my second line using Pharse."); Chunk chunk = new Chunk(" This is my third line using Chunk."); doc.Add(paragraph); doc.Add(pharse); doc.Add(chunk); } pdfBytes = mem.ToArray(); } 

我从来没有使用过iTextPDF,但听起来很有趣,所以我接受了挑战,并自己做了一些研究。 以下是如何通过内存stream式传输PDF文档。

 protected void Page_Load(object sender, EventArgs e) { ShowPdf(CreatePDF2()); } private byte[] CreatePDF2() { Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50); using (MemoryStream output = new MemoryStream()) { PdfWriter wri = PdfWriter.GetInstance(doc, output); doc.Open(); Paragraph header = new Paragraph("My Document") {Alignment = Element.ALIGN_CENTER}; Paragraph paragraph = new Paragraph("Testing the iText pdf."); Phrase phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here."); Chunk chunk = new Chunk("This is a chunk."); doc.Add(header); doc.Add(paragraph); doc.Add(phrase); doc.Add(chunk); doc.Close(); return output.ToArray(); } } private void ShowPdf(byte[] strS) { Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now); Response.BinaryWrite(strS); Response.End(); Response.Flush(); Response.Clear(); } 

在你的代码有new FileStream ,传入你已经创build的MemoryStream 。 (不要只是在调用PdfWriter.GetInstance时候内联创build它,以后可以引用它。)

然后在完成写入之后调用MemoryStream上的ToArray()以获得一个byte[]

 using (MemoryStream output = new MemoryStream()) { PdfWriter wri = PdfWriter.GetInstance(doc, output); // Write to document // ... return output.ToArray(); } 

我没有使用iTextSharp,但我怀疑这些types中的一些实现了IDisposable – 在这种情况下,您应该using语句创build它们。