[reportlab-users] Adding annotations to a pdf

Robin Becker robin at reportlab.com
Tue Dec 11 05:04:27 EST 2018


Hi Pianoslum,

I tried your example (with some minor variations) on my ubuntu 16.04 system. That has Python 3.5.2 and evince 3.18.2, but I cannot 
think that changing to a later python will affect this much. I ran using bit latest source of reportlab and with the latest pypi 
package (in case the manylinux wheel buuild has an effect), but in all cases my annotations seem to work both in the direct 
reportlab output and also after using pypdf2 to merge.

My code looked like this

> $ cat tannot.py
> def main():
>     import io
>     from reportlab.pdfgen import canvas
>     from reportlab.lib.pagesizes import A4
> 
>     packet = io.BytesIO()
>     # create a new PDF with Reportlab
>     canv = canvas.Canvas(packet, pagesize=A4)
>     text = "Hello Cruel World!"
>     x = 10
>     y = 100
>     canv.drawString(x, y, text)
>     w = canv.stringWidth(text)
>     fontSize = canv._fontsize
>     canv.highlightAnnotation("TEST", Rect=[x-1, y-0.2*fontSize-1, x+w+2, y+1.2*fontSize+2], relative=0)
>     canv.highlightAnnotation("TEST1", Rect=[1, 1, 1, 1], relative=1)
>     canv.save()
>     packet.seek(0)
>     with open('tannot.pdf','wb') as _:
>         _.write(packet.getvalue())
> 
>     packet.seek(0)
>     from PyPDF2 import PdfFileWriter, PdfFileReader
>     #move to the beginning of the StringIO buffer
>     new_pdf = PdfFileReader(packet)
>     # read your existing PDF
>     existing_pdf = PdfFileReader(open("initial.pdf", "rb"))
>     output = PdfFileWriter()
>     # add the "watermark" (which is the new pdf) on the existing page
>     page = existing_pdf.getPage(0)
>     page.mergePage(new_pdf.getPage(0))
>     output.addPage(page)
>     # finally, write "output" to a real file
>     with open("final.pdf", "wb") as _:
>         output.write(_)
> 
> if __name__=='__main__':
>     main()

it's not very different from yours, but I allowed myself to actually annotate the drawString area. I did consider that the zero 
sized rectangle (Rect is [x1,y1,x2,y2] so [1,1,1,1] has zero size) might be an issue, but it doesn't cause my evince any problems.

I used A4 as that's the document size I have normally.

Please find attached a zip of my results.

Can you check tannot.pdf/final.pdf with your evince. I am unable to locate the TEST1 annotation, but the other certainly shows for 
me. If it fails for you then we isolate the problem to evince at least. I do have arch at home so will be able to test with 3.7 if 
that's required.
-- 
Robin Becker
-------------- next part --------------
A non-text attachment was scrubbed...
Name: tannot-example.zip
Type: application/x-zip-compressed
Size: 3699 bytes
Desc: not available
URL: <https://pairlist2.pair.net/pipermail/reportlab-users/attachments/20181211/3e646ec3/attachment.bin>


More information about the reportlab-users mailing list