PDF page overlay with Go
Recently, I had a need to overlay 2 PDFs in Go.
Some background: I had a semi-complex PDF generated off-line with a Python program and I needed to overlay some simple drawing on top, on-demand using some parameters sent from a website. Since I wanted to deploy on Cloud Run (free for my low-traffic app), in order to avoid issues with cold start, I decided to develop the server in Go. The drawing part was simple: I used fpdf, which worked well.
However, I had a bit of trouble to find a way to overlay the generated PDF on top of the complex pre-generated PDF. Also, when I asked Github Copilot, it kept referring me to the Unidoc library, which is not free. At some point, I realized I could simply use pdfcpu and its watermark feature: It supports both images and PDF so it worked for me.
Here is the code:
|
|
The wm.ScaleAbs = true
line is important: Without it, the code worked for documents in US Letter format but not A4. It turned out that without it, the size of the document was converted to integers: In points (1/72 of an inch), it makes no differences for letters (8.5 × 11 inches), but there was a tiny issue with A4.
Afterwards, I found out about the gofpdi library, but since what I had worked, I didn’t switch.
Here is my website that uses this: https://xyl.vellut.com (it is a tool to generate music sheets for toy xylophones, which may have different colors depending on the models).