Search code examples
c++macosapplescript

Using c++, write pdf file and open it by Preview app in osx


  1. Wrote the .pdf file to the disk by using fopen and fwrite.

    FILE * fp = fopen("/Users/test/Documents/1.pdf", "w+");
    if (fp) {
        fwrite(pdf_data, size_of_pdf_data, 1, fp);
        fclose(fp);
    }  
    
  2. And then open 1.pdf within Preview.app by using applescript.

    system("osascript -e \'tell app \"Preview\" to open \"/Users/test/Documents/1.pdf\"");
    
  3. when the system function executes, the file permission issue occurred like the following image:

File Permission Issue

Error message

How can I fix this issue? I am using macOS Catalina 10.15.7 and xcode 11.3.1.


Solution

  • AppleScript is 100% completely the wrong tool for this job.

    Were you in ObjC you’d use NSWorkspace. Since you’re in C[++], use LaunchServices’ LSOpenFromURLSpec.