PDF page-stream optimizer library?
Has anyone written a library (or just a program) that optimizes the contents of PDF page streams?  I am talking about things like "delete `q`...`Q` blocks that have no overall effect", "merge adjacent `BT`...`ET` blocks", "track the graphics state and delete operators that set something to the value it already has", maybe even "reorder drawing operations to minimize graphics state changes, when this can be done without changing the appearance of the page".

(I'm asking because R's "grid" graphics + its PDF backend generate ridiculous numbers of pointless operations, like

    q 1 0 0 RG 1 0 0 rg Q

which has no effect whatsoever ... and sometimes you get a few hundred copies of it in a row.)

I ain't picky as to implementation language, but open source is very much preferred, as I may need to hack it up for my particular needs.
PDF page-stream optimizer library?
===

Has anyone written a library (or just a program) that optimizes the contents of PDF page streams?  I am talking about things like "delete `q`...`Q` blocks that have no overall effect", "merge adjacent `BT`...`ET` blocks", "track the graphics state and delete operators that set something to the value it already has", maybe even "reorder drawing operations to minimize graphics state changes, when this can be done without changing the appearance of the page".

(I'm asking because R's "grid" graphics + its PDF backend generate ridiculous numbers of pointless operations, like

    q 1 0 0 RG 1 0 0 rg Q

which has no effect whatsoever ... and sometimes you get a few hundred copies of it in a row.)

I ain't picky as to implementation language, but open source is very much preferred, as I may need to hack it up for my particular needs.