title: Convert HTML String to PDF byte array in Java
body: <p>I need to build a function that receives a html document in the form of a string and should return a pdf document as a <code>byte[]</code>.</p>
  <p>With the following code I can build a pdf document. Ideally, I don't want to generate a pdf document first. Instead, the <code>byte[]</code> should be returned without building the pdf document first. How can I prevent the pdf generation and just return the <code>byte[]</code>?</p>
  <p>I followed this tutorial to get this code so far: <a href="https://www.baeldung.com/pdf-conversions-java" rel="nofollow noreferrer">https://www.baeldung.com/pdf-conversions-java</a></p>
  <pre class="lang-java prettyprint-override"><code>public static byte[] convertHtmlToPdfBytes( String htmlString ) throws IOException, DocumentException {
      Document document = new Document();
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(&quot;temp.pdf&quot;));
      document.open();
  
      InputStream in = IOUtils.toInputStream(htmlString);
  
      XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
      document.close();
      return null;
  }
  </code></pre>