title: How do I add transparency while creating a pdf using PyFPDF
body: <p>I am using Python version of FPDF, PyFPDF to generate PDFs. I want to add transparency to a rectangle I created using PyFPDF.</p>
  
  <p>I found PHP code in fpdf documentation that lets us add transparency - <a href="http://www.fpdf.org/en/script/script74.php" rel="nofollow noreferrer">trasnparency</a>. I tried to follow this and write code in python but it didn't work.</p>
  
  <p>Code snippet found in documentation(in PHP):</p>
  
  <p><strong>source</strong></p>
  
  <pre><code>&lt;?php
  require('fpdf.php');
  
  class AlphaPDF extends FPDF
  {
      var $extgstates = array();
  
      // alpha: real value from 0 (transparent) to 1 (opaque)
      // bm:    blend mode, one of the following:
      //          Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn,
      //          HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
      function SetAlpha($alpha, $bm='Normal')
      {
          // set alpha for stroking (CA) and non-stroking (ca) operations
          $gs = $this-&gt;AddExtGState(array('ca'=&gt;$alpha, 'CA'=&gt;$alpha, 'BM'=&gt;'/'.$bm));
          $this-&gt;SetExtGState($gs);
      }
  
      function AddExtGState($parms)
      {
          $n = count($this-&gt;extgstates)+1;
          $this-&gt;extgstates[$n]['parms'] = $parms;
          return $n;
      }
  
      function SetExtGState($gs)
      {
          $this-&gt;_out(sprintf('/GS%d gs', $gs));
      }
  
      function _enddoc()
      {
          if(!empty($this-&gt;extgstates) &amp;&amp; $this-&gt;PDFVersion&lt;'1.4')
              $this-&gt;PDFVersion='1.4';
          parent::_enddoc();
      }
  
      function _putextgstates()
      {
          for ($i = 1; $i &lt;= count($this-&gt;extgstates); $i++)
          {
              $this-&gt;_newobj();
              $this-&gt;extgstates[$i]['n'] = $this-&gt;n;
              $this-&gt;_out('&lt;&lt;/Type /ExtGState');
              $parms = $this-&gt;extgstates[$i]['parms'];
              $this-&gt;_out(sprintf('/ca %.3F', $parms['ca']));
              $this-&gt;_out(sprintf('/CA %.3F', $parms['CA']));
              $this-&gt;_out('/BM '.$parms['BM']);
              $this-&gt;_out('&gt;&gt;');
              $this-&gt;_out('endobj');
          }
      }
  
      function _putresourcedict()
      {
          parent::_putresourcedict();
          $this-&gt;_out('/ExtGState &lt;&lt;');
          foreach($this-&gt;extgstates as $k=&gt;$extgstate)
              $this-&gt;_out('/GS'.$k.' '.$extgstate['n'].' 0 R');
          $this-&gt;_out('&gt;&gt;');
      }
  
      function _putresources()
      {
          $this-&gt;_putextgstates();
          parent::_putresources();
      }
  }
  ?&gt;
  </code></pre>
  
  <p><strong>usage</strong></p>
  
  <pre><code>&lt;?php
  require('alphapdf.php');
  
  $pdf = new AlphaPDF();
  $pdf-&gt;AddPage();
  $pdf-&gt;SetLineWidth(1.5);
  
  // draw opaque red square
  $pdf-&gt;SetFillColor(255,0,0);
  $pdf-&gt;Rect(10,10,40,40,'DF');
  
  // set alpha to semi-transparency
  $pdf-&gt;SetAlpha(0.5);
  
  // draw green square
  $pdf-&gt;SetFillColor(0,255,0);
  $pdf-&gt;Rect(20,20,40,40,'DF');
  
  // draw jpeg image
  $pdf-&gt;Image('lena.jpg',30,30,40);
  
  // restore full opacity
  $pdf-&gt;SetAlpha(1);
  
  // print name
  $pdf-&gt;SetFont('Arial', '', 12);
  $pdf-&gt;Text(46,68,'Lena');
  
  $pdf-&gt;Output();
  ?&gt;
  </code></pre>
  
  <p>This is what I wrote in python:</p>
  
  <p><strong>source</strong></p>
  
  <pre><code>class EXPDF(FPDF):
  
    def __init__(self, orientation='P', unit='mm', style='A4'):
      super(EXPDF, self).__init__(orientation=orientation, unit=unit, format=style)
      self.page_format = style.lower()
      self.extgstates = {}
  
    def set_alpha(self, alpha, bm='Normal'):
      gs = self.add_ext_gstate({'ca': alpha, 'CA': alpha, 'BM': '/'+bm})
      self.set_ext_gstate(gs)
  
    def add_ext_gstate(self, parms):
      n = len(self.extgstates.keys())+1
      if n not in self.extgstates.keys():
        self.extgstates[n] = { 'parms': parms }
      else:
        self.extgstates[n]['parms'] = parms
      return n
  
    def set_ext_gstate(self, gs):
      self._out(sprintf('/GS%d gs', gs))
  
    def _enddoc(self):
      if self.extgstates and self.pdf_version &lt; '1.4':
        self.pdf_version = '1.4'
      super()._enddoc()
  
    def _putextgstates(self):
      for i in range(1, len(self.extgstates.keys())+1):
        self._newobj()
        self.extgstates[i]['n'] = self.n
        self._out('&lt;&lt;/Type /ExtGState')
        parms = self.extgstates[i]['parms']
        self._out(sprintf('/ca %.3F', parms['ca']))
        self._out(sprintf('/CA %.3F', parms['CA']))
        self._out('/BM'+parms['BM'])
        self._out('&gt;&gt;')
        self._out('endobj')
  
    def _putresourcedict(self):
      super()._putresourcedict()
      self._out('/ExtGState &lt;&lt;')
      for k in self.extgstates:
        self._out('/GS'+str(k)+' '+str(self.extgstates[k]['n'])+' O R')
      self._out('&gt;&gt;')
  
  </code></pre>
  
  <p><strong>usage</strong></p>
  
  <pre><code>pdf = EXPDF()
  pdf.set_alpha(0.5)
  pdf.rectangle(20, 20, 40, 40, 'DF')
  </code></pre>
  
  <p>The code didn't throw any error when I ran it. But when I tried to open the generated pdf in Adobe Acrobat, it said <code>There was a problem reading this document (135)</code>. I tried opening the pdf in google chrome. It opened but the rectangle was still opaque.</p>