title: Convert color PDF to black and white (monochrome) PDF in PHP [for Twilio Fax]
body: <p>I am trying to convert a color pdf to black and white pdf. I am going to use the pdf to send it in <strong>fax</strong> and I am using Twilio and it is explicitly converting the color pdf to monochrome pdf however, I want to do it in my server-side to be able to preview the outcome.</p>
  
  <p>As I have Imagick, and found some topics mainly on Imagick, I wanted to give it a try but I couldn't find the necessary class in Imagick. I found some for grayscale but fax is explicitly black &amp; white (monochrome), so no identical to the fax case.</p>
  
  <p>Closest I could find was: </p>
  
  <p><code>-&gt;transformImageColorSpace(\Imagick::COLORSPACE_SRGB)</code> and </p>
  
  <p><code>-&gt;setImageColorSpace(Imagick::COLORSPACE_GRAY)</code></p>
  
  <p>But these are grayscale, not monochrome.</p>
  
  <hr>
  
  <p>Also, on Imagick formums, I found these commands but I don't want to execute with <code>shell_exec</code> (as I've read there are couple of down-sides)</p>
  
  <pre><code>// I am pretty sure this one should work, but couldn't find how to do it in php:
  convert -density 288 in.pdf -resize 25% out.png  
  
  // thus this one:
  convert -density 600 in.pdf -threshold 15% -type bilevel -compress fax out.pdf
  
  // Also found this one:
  convert -density 288 image.pdf -resize 25% -threshold 50% -type bilevel image.tiff
  </code></pre>
  
  <hr>
  
  <p>How to achieve what I am trying to achieve in php either using above commands or any other php compatible way? How does Twilio do it?</p>
  
  <hr>
  
  <p><strong>Update:</strong></p>
  
  <p>Expected output (how Twilio does it):</p>
  
  <p><a href="https://i.stack.imgur.com/xtF69.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xtF69.png" alt="enter image description here"></a></p>
  
  <p>Using below answer:</p>
  
  <pre><code>$img = new Imagick('path/to/document.pdf');
  $img-&gt;quantizeImage(2,                        // Number of colors
                  Imagick::COLORSPACE_GRAY, // Colorspace
                  50,                        // Depth tree
                  TRUE,                     // Dither
                  FALSE);                   // Error correction
  $img-&gt;writeImage('path/to/output.png')
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/wxC12.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wxC12.png" alt="enter image description here"></a></p>
  
  <hr>
  
  <p>Update 2:</p>
  
  <p>Using <code>$img-&gt;quantizeImage(2, Imagick::COLORSPACE_GRAY, 1, TRUE, FALSE);</code></p>
  
  <p><a href="https://i.stack.imgur.com/DTTKX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DTTKX.png" alt="enter image description here"></a></p>