title: Get byte array from PdfWriter, writing to a memorystream in iTextSharp
body: <p>I have a method, which takes in the following:</p>
  
  <ul>
  <li>Byte array, which is a PDF file</li>
  <li>A "from" size</li>
  <li>A "to" size</li>
  </ul>
  
  <p>The idea is it transforms a PDF file with a specific size, to another size. I want to return a byte array, and want to keep the whole thing in memory.</p>
  
  <p>I create the PdfWriter using a memorystream in the constructor (<code>outPDF</code>), and then does my conversion. After, I want to say <code>outBytes = outPDF.ToArray();</code> .</p>
  
  <p>I tried putting this code in three places, see place A, B and C in the code. In place A, the length of the memorystream is only 255, which doesn't work. My guess is the <code>doc.Close()</code> has to run first. In place B and C, the stream is closed, and cannot be accessed.</p>
  
  <p>My question is therefore:
  How to get a byte array from PdfWriter, writing to a memorystream in iTextSharp</p>
  
  <p><strong>My code</strong>:</p>
  
  <pre><code>public static byte[] ConvertPdfSize(byte[] inPDF, LetterSize fromSize, LetterSize toSize)
          {
              if (fromSize != LetterSize.A4 || toSize != LetterSize.Letter)
              {
                  throw new ArgumentException("Function only supports from size A4 to size letter");
              }
  
              MemoryStream outPDF = new MemoryStream();
              byte[] outBytes;
              using (PdfReader pdfr = new PdfReader(inPDF))
              {
                  using (Document doc = new Document(PageSize.LETTER))
                  {
                      Document.Compress = true;
  
                      PdfWriter writer = PdfWriter.GetInstance(doc, outPDF);
                      doc.Open();
  
                      PdfContentByte cb = writer.DirectContent;
  
                      PdfImportedPage page;
  
                      for (int i = 1; i &lt; pdfr.NumberOfPages + 1; i++)
                      {
                          page = writer.GetImportedPage(pdfr, i);
                          cb.AddTemplate(page, PageSize.LETTER.Width / pdfr.GetPageSize(i).Width, 0, 0, PageSize.LETTER.Height / pdfr.GetPageSize(i).Height, 0, 0);
                          doc.NewPage();
                      }
  
                      // place A
                      doc.Close();
                      // place B
  
                  }
                  pdfr.Close();
                  // place C
              }
  
              return new byte[0];
          }
  </code></pre>