[Question] Undelete an annotation #900
Answered
by
JorjMcKie
PowerSnail
asked this question in
Q&A
Replies: 2 comments 6 replies
-
|
Beta Was this translation helpful? Give feedback.
3 replies
-
Ah, now I see what you want.
There is a low-level code approach available: you can directly change the page object definition.
Edit the text string returned by ``doc.xref_object(page.xref)`` so that the two annotation xrefs change their sequence and replace the page definition with the resulting string.
```python
page_obj = doc.xref_object(page.xref)
# manipulate string page_obj, then:
doc.update_object(page.xref, page_obj)
# do not forget:
page = doc.reload_page(page)
```
The newest PyMuPDF version also allows a more direct change of the /Annots key content – see `doc.xref_get_key()` and `doc.xref_set_key()`.
Example session:
```python
>> page = doc[0]
>> annots = doc.xref_get_key(page.xref, "Annots") # get string of pages annotations
>> annots
('array', '[5 0 R 9 0 R 12 0 R 13 0 R 17 0 R 21 0 R 25 0 R 29 0 R 32 0 R 35 0 R 38 0 R 41 0 R 44 0 R 47 0 R 48 0 R 52 0 R 57 0 R]')
>> # assume we want to exchange places of xref 17 and 35
>> annots_list = annots[1][1:-1].replace(" 0 R","")
>> annots_list
'5 9 12 13 17 21 25 29 32 35 38 41 44 47 48 52 57'
>> annots_list = annots_list.split()
>> # exchange positions of 17 and 35:
>> i1 = annots_list.index("17")
>> i2 = annots_list.index("35")
>> annots_list[i1], annots_list[i2] = annots_list[i2], annots_list[i1]
>> annots_text = "[" + " 0 R ".join(annots_list) + " 0 R]
>> annots_text # confirm it worked
'[5 0 R 9 0 R 12 0 R 13 0 R 35 0 R 21 0 R 25 0 R 29 0 R 32 0 R 17 0 R 38 0 R 41 0 R 44 0 R 47 0 R 48 0 R 52 0 R 57 0 R]'
>> doc.xref_set_key(page.xref, "Annots", annots_text) # store back to the page
>> page = doc.reload_page(page) # reload the page
>> print(doc.xref_object(page.xref)) # and look at changed annot sequence
<<
/Type /Page
/MediaBox [ 0 0 595 842 ]
/Rotate 0
/Resources 3 0 R
/Parent 2 0 R
/Annots [ 5 0 R 9 0 R 12 0 R 13 0 R 35 0 R 21 0 R 25 0 R 29 0 R
32 0 R 17 0 R 38 0 R 41 0 R 44 0 R 47 0 R 48 0 R 52 0 R
57 0 R ]
/Contents [ 8 0 R 11 0 R 15 0 R 16 0 R 19 0 R 20 0 R 23 0 R
24 0 R 27 0 R 28 0 R 31 0 R 34 0 R 37 0 R 40 0 R 43 0 R
46 0 R 51 0 R 55 0 R 56 0 R 59 0 R ]
>
>>
```
|
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
PowerSnail
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The doc of delete_annot says:
Does that mean that there is an easy way to un-delete the annotation, while the file hasn't been saved?
Of course I can re-insert a new annotation, with the same attributes, but the problem is that the order of annotation will not be the same.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions