Search and replace placeholder text in PDF with Python
<p>I need to generate a customized PDF copy of a template document.
The easiest way - I thought - was to create a source PDF that has some placeholder text where customization needs to happen , ie <code>&lt;first_name&gt;</code> and <code>&lt;last_name&gt;</code>, and then replace these with the correct values.</p>

<p>I've searched high and low, but is there really no way of basically taking the source template PDF, replace the placeholders with actual values and write to a new PDF?</p>

<p>I looked at PyPDF2 and ReportLab but neither seem to be able to do so.
Any suggestions? Most of my searches lead to using a Perl app, CAM::PDF, but I'd prefer to keep it all in Python.</p>

<p>There is no direct way to do this that will work reliably. PDFs are not like HTML: they specify the positioning of text character-by-character. They may not even include the whole font used to render the text, just the characters needed to render the specific text in the document. No library I've found will do nice things like re-wrap paragraphs after updating the text. PDFs are for the most part a display-only format, so you'll be much better off using a tool that turns markup into a PDF than updating the PDF in-place.</p>

<p>If that's not an option, you can create a <a href="http://www.adobe.com/devnet/acrobat/fdftoolkit.html" rel="nofollow">PDF form</a> in something like Acrobat, then use a PDF manipulation library like <a href="http://itextpdf.com/" rel="nofollow">iText (AGPL)</a> or <a href="https://pdfbox.apache.org/" rel="nofollow">pdfbox</a>, which has a nice clojure wrapper called <a href="https://github.com/dotemacs/pdfboxing#fill-in-pdf-forms" rel="nofollow">pdfboxing</a> that can handle some of that.</p>

<p>From my experience, Python's support for writing to PDFs is pretty limited. Java has, by far, the best language support. Also, you get what you pay for, so it would probably be worth paying for a iText license if you're using this for commercial purposes. I've had pretty good results writing python wrappers around PDF-manipulation CLI tools like pdfboxing and ghostscript. That will probably be <em>much</em> easier for your use case than trying to shoehorn this into Python's PDF ecosystem.</p>

python pdf