PDF generator: already opened pdf

In my application I need to write big pdf files. 
A typical scenario:
I start writing a file (already existing file that i would like to replace, e.g. test.pdf). I set filename, then I begin document. I get no error if test.pdf is already opened since I do:
And even if it is under exception control I get:
An unhandled exception occurred at $0000000100113A5F:
EAccessViolation: Access violation
  $0000000100113A5F line 175 of include/winapi.inc
  $0000000100090F65 line 110 of include/custombitmap.inc
  $0000000100090D65 line 56 of include/custombitmap.inc
  $000000010008D1A9 line 382 of include/picture.inc
  $00000001001CA4E8 line 3775 of LCLTMSFNCPDFLibGeneral.pas
  $00000001001C80D4 line 3270 of LCLTMSFNCPDFLibGeneral.pas
  $00000001001CBBE7 line 907 of LCLTMSFNCPDFLibGeneral.pas
  $00000001001BDA69 line 1324 of LCLTMSFNCPDFLibGeneral.pas

Additionally even if I open test.pdf during the writing process (after pdflib.BeginDocument) I get no error since EndDocument is performed.

Is there a way to check if filename is already open and to lock it when I start my pdf using:

I would like to avoid that after all the pdf writing the process fails due to the already opened file. I need to know if the existing pdf is opened or not and if not, lock it in some way. At least I would like to avoid unhandled exceptions


[Lazarus 1.6.2, fpc 3.0.0]


There is currently no feature available that checks if the file is already open, but I assume you could use the approach at the following link : https://stackoverflow.com/questions/17888828/lazarus-how-to-check-if-file-is-in-use

Ok. I will check it.