I did some further testing and when I ran this code on its own it works fine, so the issue might be something else I'm doing in my code, so please ignore for now...
On Mon, Jan 27, 2020 at 11:44 PM Gilad Denneboom <gilad.denneb...@gmail.com> wrote: > Hi all, > > Does anyone see something obvious I'm missing in this code that could > cause a COSStream error when trying to save a document? I basically have an > (ascending) list of page numbers that I want to delete from a document, so > I'm doing it in a reverse loop, but it errors out on the save command. > Here's the relevant code: > > if (pagesToDelete.isEmpty()==false) { > for (int i=pagesToDelete.size()-1; i>=0; i--) { > System.out.println("Removing page: "+pagesToDelete.get(i)); > mergedDoc.removePage(pagesToDelete.get(i)); > } > mergedDoc.save(new File(mergedFilePath.replace(".pdf", "_edited.pdf"))); > } > mergedDoc.close(); > > And the error stack: > Exception in thread "main" java.io.IOException: COSStream has been closed > and cannot be read. Perhaps its enclosing PDDocument has been closed? > at org.apache.pdfbox.cos.COSStream.checkClosed(COSStream.java:83) > at org.apache.pdfbox.cos.COSStream.createRawInputStream(COSStream.java:133) > at > org.apache.pdfbox.pdfwriter.COSWriter.visitFromStream(COSWriter.java:1219) > at org.apache.pdfbox.cos.COSStream.accept(COSStream.java:404) > at org.apache.pdfbox.cos.COSObject.accept(COSObject.java:158) > at org.apache.pdfbox.pdfwriter.COSWriter.doWriteObject(COSWriter.java:526) > at org.apache.pdfbox.pdfwriter.COSWriter.doWriteObjects(COSWriter.java:464) > at org.apache.pdfbox.pdfwriter.COSWriter.doWriteBody(COSWriter.java:448) > at > org.apache.pdfbox.pdfwriter.COSWriter.visitFromDocument(COSWriter.java:1113) > at org.apache.pdfbox.cos.COSDocument.accept(COSDocument.java:449) > at org.apache.pdfbox.pdfwriter.COSWriter.write(COSWriter.java:1386) > at org.apache.pdfbox.pdfwriter.COSWriter.write(COSWriter.java:1273) > at org.apache.pdfbox.pdmodel.PDDocument.save(PDDocument.java:1357) > at org.apache.pdfbox.pdmodel.PDDocument.save(PDDocument.java:1328) > at ***.main(***.java:79) > > I can see the page numbers in the console and the output file is > generated, but is not legible. > Console output: > Removing page: 543 > Removing page: 542 > Removing page: 541 > Removing page: 540 > > PDFBox version is 2.0.18. Java version is 1.8.0_25. OS is Windows 7. > > PS. I'm getting the same result if I specify the parameter of removePage > as a PDPage object instead of an integer. > > Thanks in advance! > Gilad >