-3

Using c# in a console application, How to delete last page of PDF file without re-writing the PDF file again ?

I Know How to do it with re-writing the PDF into new one except last page, but I tried doing it without re-writing the PDF Again, using iTextSharp but i failed, so i need help.

Thanks

  • 3
    Is this SO answer not helpful? http://stackoverflow.com/questions/7246137/itextsharp-trimming-pdf-documents-pages –  Feb 18 '16 at 14:01
  • 1
    @DntQuitPls thanks for your fast reply but this link isn't the answer I excepted as I am asking about deleting the page **WITHOUT** re-writing the PDF file again.. I still need help – Ahmed Kajoo Feb 18 '16 at 14:05
  • It can't be done. Not with iTextSharp and not with any other library. You always need a second file, which can be temporary, and when you are done you rename the temp file. – Amedee Van Gasse Feb 18 '16 at 14:28
  • 1
    What do you mean by "without re-writing"? Do you mean changing the file in place, as opposed to creating a new file to replace the existing one? –  Feb 18 '16 at 14:30
  • This question is the equivalent of "I want to make an omelette without breaking eggs." It's the kind of questions you expect on April 1st. Maybe @AhmedKajoo uses a different Calendar than we do. – Bruno Lowagie Feb 19 '16 at 10:12

1 Answers1

0

I quess the simplest way is to mark the object of the last page as free in the cross-reference table. If you have "old-style" cross-reference table which is in the end of file and looks like

xref
0 42
0000000003 65535 f
0000000017 00000 n
0000000081 00000 n
...

then all you need to do is change the n of the appropriote object record to f.

If you have file which uses cross-reference stream then it's bit more complicated as the stream is typically compressed and while you only change one/few bytes in it after recompressing it it's length might change so that it wouldn't fit to the original space.

So the safest bet seems to be to make an incremental update to the file which marks the last page object as free. This would mean to add to the end of the original file new cross-reference info where the desired page object is marked as free. Or perhaps better would be to write new version of the Page Tree object...

These solutions require that you know the object id of the last page, I don't know the itextsharp so I don't know would it help you to find it. You might have to analyse the file yourselt to find the id.

ain
  • 22,394
  • 3
  • 54
  • 74