title: Convert pdf to byte[] and vice versa with pdfbox
body: <p>I've read the documentation and the examples but I'm having a hard time putting it all together. I'm just trying to take a test pdf file and then convert it to a byte array then take the byte array and convert it back into a pdf file then create the pdf file onto disk.</p>
  
  <p>It probably doesn't help much, but this is what I've got so far:</p>
  
  <pre><code>package javaapplication1;
  
  import java.io.ByteArrayOutputStream;
  import java.io.IOException;
  import org.apache.pdfbox.cos.COSStream;
  import org.apache.pdfbox.exceptions.COSVisitorException;
  import org.apache.pdfbox.pdmodel.PDDocument;
  
  public class JavaApplication1 {
  
      private COSStream stream;
  
      public static void main(String[] args) {
          try {
              PDDocument in = PDDocument.load("C:\\Users\\Me\\Desktop\\JavaApplication1\\in\\Test.pdf");
              byte[] pdfbytes = toByteArray(in);
              PDDocument out;
          } catch (Exception e) {
              System.out.println(e);
          }
      }
  
      private static byte[] toByteArray(PDDocument pdDoc) throws IOException, COSVisitorException {
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          try {
              pdDoc.save(out);
              pdDoc.close();
          } catch (Exception ex) {
              System.out.println(ex);
          }
          return out.toByteArray();
      }
  
      public void PDStream(PDDocument document) {
          stream = new COSStream(document.getDocument().getScratchFile());
      }
  }
  </code></pre>