2

I am using Visual Studio 2013, c# Windows Application, iTextSharp:

I can easily create/save a pdf file and write to it but is there a way to just use a pdf file and write to it without first saving it? I don't want to be creating a temporary pdf file every-time someone runs a report. Thanks in Advance !!

Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10,10,42,35);

PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Test.pdf", 
FileMode.Create));

doc.Open();

\\\\ Then I do a bunch of stuff, then do a close


doc.Close();
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
John
  • 21
  • 1
  • 3

1 Answers1

-2

You can use a MemoryMappedFile and write to it and it is not disk based.

using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("INMEMORYPDF.pdf", 1000000))
{
    PDFPageMargins margins = new PDFPageMargins(10, 10, 10, 10);
    var document = new Document((_pageWidth > 540) ? PageSize.A4.Rotate() : PageSize.A4, margins.Left, margins.Right, margins.Top, margins.Bottom);
    using (MemoryMappedViewStream stream = mmf.CreateViewStream())
    {                       

        PdfWriter.GetInstance(document, stream);
        document.Open();
        //MODIFY DOCUMENT
        document.Close();                    
    }
    byte[] content;
    using (MemoryMappedViewStream stream = mmf.CreateViewStream())
    {
        BinaryReader rdr = new BinaryReader(stream);
        content = new byte[mmf.CreateViewStream().Length];
        rdr.Read(content, 0, (int)mmf.CreateViewStream().Length);
    }
    return content;            
}
Ross Bush
  • 14,648
  • 2
  • 32
  • 55
  • 1
    Why use mmf when one can just use MemoryStream instead? – NineBerry Dec 01 '16 at 20:59
  • Well, for one a mmf can be shared between processes by passing handles or pointers. – Ross Bush Dec 01 '16 at 21:01
  • For using the mmf you have to specify a maximum size. Choose this size too low, it will fail when the PDF needs more memory. Choose this size too high, it will fail when the address space in the process cannot provide enough continuous memory. – NineBerry Dec 01 '16 at 21:07
  • Still no valid reason this is invalid. I answered the OP's question and this code can be used in an application that needs large memory allocations that mimics a file. The file can the be used in inter-process communication. – Ross Bush Dec 01 '16 at 21:07
  • @NineBerry - Thanks for the comment. You are correct. The way CreateNew is implemented an upfront size requirement is necessary. – Ross Bush Dec 01 '16 at 21:09