title: How to stop PdfDocument.writeTo() function upon user's request
body: <p>I am using the following code to create a PDF document using Android <code>PdfDocument</code> and write to a file. The <code>createDocument()</code> function is called in a non-Ui thread (using <code>AsyncTask</code>), and the user can request to stop this operation (facilitated through <code>shouldStop()</code>).</p>
  <p>When there are many pages, <code>doc.writeTo(out)</code> takes a considerable amount of time to complete. I want to be able to cancel <code>doc.writeTo</code> operation as well, depending on whether the user has requested to stop. Note, per Android <a href="https://cs.android.com/android/platform/superproject/+/master:frameworks/base/graphics/java/android/graphics/pdf/PdfDocument.java;l=175;drc=19294005eee57bdf12437351ef50206dc093e2f0;bpv=1;bpt=1?q=PdfDocument&amp;ss=android%2Fplatform%2Fsuperproject" rel="nofollow noreferrer">source code</a> <code>doc.writeTo</code> calls <a href="http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/jni/android/graphics/pdf/PdfDocument.cpp#138" rel="nofollow noreferrer">this</a> native function.</p>
  <p>Is there anyway to facilitate stopping <code>doc.writeTo</code> while it is being executed?</p>
  <pre><code>void createDocument() {
      PdfDocument doc = new PdfDocument();
      for (int i = 0; i &lt; data.getSize(); i++) {
          PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(100, 100, i + 1).create();
          PdfDocument.Page page = doc.startPage(pageInfo);
          // draw something on page
          doc.finishPage(page);
          if (shouldStop()) return;   // shouldStop() will return true if user has requested from another thread to cancel creating the doc
      }
      OutputStream out = new FileOutputStream(path);
      doc.writeTo(out);  // ---&gt;&gt;&gt; PROBLEMATIC TIME CONSUMING LINE, want to stop writing if user requests
      doc.close();
      out.close();
  }
  </code></pre>