Reputation: 555
I am looking for a way to check if a PDF file stored on a shared netwerk is open by another process by user X.
My searches were not satisfying and I am now trying to use the iText7 PDFwriter to check if the PDF is in use. And this works but when the PDF is NOT in use my theory fails.
If the PDF is not in use the closing the writer corrupts my PDF.
My code:
Public Function IsOpen(ByVal oPath As String) As Boolean
Try
Dim oWriter As New PdfWriter(oPath)
oWriter.Close()
Return False
Catch ex As Exception
Return True
End Try
End Function
So my question is. Can I close the PDFwriter without doing anything to the PDF. Cancel the write?
Upvotes: 0
Views: 740
Reputation: 2458
One can write the same content to the file rather than cancel the writing.
Firstly let's write the pdf to memory:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourcePath), new PdfWriter(baos));
pdfDocument.close();
Then let's rewrite the file with the bytes stored in memory:
PdfDocument pdfDoc = new PdfDocument(new PdfReader(new RandomAccessSourceFactory().createSource(baos.toByteArray()), new ReaderProperties()),
new PdfWriter(sourcePath), new StampingProperties().useAppendMode());
pdfDoc.close();
The side effect: during rewriting the pdf may be optimised by iText a bit.
Upvotes: 1