web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics AX (Archived)

How to close a pdf file by code

(0) ShareShare
ReportReport
Posted on by

Hi All,

I am generating a pdf after running a report and saving it into a shared drive then mailing it the customers. All m doing this via code.

currently, m facing an issue, i.e., I am not able to delete the file once it's generated as getting an error "It's used by another process or User".  Please suggest how this can be resolved.

Please find code as below:

To Save as PDF:

public static void saveReport()
{
    Args args = new Args();
    PrintJobSettings pjs = new PrintJobSettings();
    SysReportRun reportRun;
    filename mFile;
    QuotationId qId;
    Voucher  custAcc;

    //str path ="\\"+"\\pmfcgrb24\\TempQuotePDF";
    str path = "\\"+"\\pmfcgrb24\\temppricelistPDF";
    test_PrintDataCustPrcList testPr;
    tmp_InventTableModule tmpModule;
    testFinalReport testFinRep;
    #define.error("Error While Insert records in a table required to print Customer Price List")
    ;

    //testPr = test_PrintDataCustPrcList::findByName(curUserID());
    winAPI::createDirectory(path);

    //if (testPr)
    //{
        ttsbegin;
        delete_from testPr
            where testPr.CurUserId == curUserId();
        ttscommit;
    //}

    while select testPr
    where testPr.CurUserId == XUserInfo::find(false, curUserId()).name// && testPr.CheckCust == NoYes::Yes
    {
        if (testPr)
        {
            //mFile =path+"\\"+strfmt("%1 %2",testPr.tmpCustAccount,systemDateget())+".pdf";
            //mFile =path+"\\"+strfmt("%1",testPr.tmpCustName)+".pdf";
            mFile = path+"\\"+testPr.tmpCustName+".pdf";
            new InteropPermission(InteropKind::ClrInterop);
            new FileIOPermission(mFile,'rw').assert();
            pjs.fileName(mFile);
            pjs.setTarget(PrintMedium::File);
            pjs.format(PrintFormat::PDF);
            pjs.preferredFileFormat(PrintFormat::PDF);
            args.name(reportstr("pmf_CustPrcListNewDesgn"));

            try
            {
                ttsbegin;
                testFinRep.tmpCustName=testPr.tmpCustName;
                testFinRep.tmpCustAccount=testPr.tmpCustAccount;
                testFinRep.ItemId=testPr.ItemId;
                testFinRep.tmpItemName=testPr.tmpItemName;
                testFinRep.tmpItemGroupId=testPr.tmpItemGroupId;
                testFinRep.tmpExtItem=testPr.tmpExtItem;
                testFinRep.FilterDates=testPr.FilterDates;
                testFinRep.tmpNewPriceDate=testPr.tmpNewPriceDate;
                //testFinRep.CurUserId = XUserInfo::find(false, curUserId()).name;
                testFinRep.CurUserId = testPR.CurUserId;
                testFinRep.STDMinLineCharge = testPr.STDMinLineCharge;
                testFinRep.tmpMinLotCharge = testPr.tmpMinLotCharge;
                testFinRep.Division = testPr.Division;
                testFinRep.Price = testPr.Price;
                testFinRep.PriceUnit = testPr.PriceUnit;
                testFinRep.tmpPrice = testPr.tmpPrice;
                testFinRep.PriceDate = testPr.PriceDate;
                testFinRep.viewPrice = testPr.viewPrice;
                testFinRep.viewNewPrice = testPr.viewNewPrice;
                testFinRep.priceIncreaseDate = testPr.priceIncreaseDate;
                testFinRep.doNotPrintNewPrice = testPr.doNotPrintNewPrice;
                testFinRep.insert();
            ttscommit;
            }
            catch
            {
                throw error(#error);
            }
         }
     }
            args.record(testFinRep);
            reportRun = classFactory.reportRunClass(args);
            reportRun.printJobSettings(pjs.packPrintJobSettings());
            reportRun.report().interactive(false);
            reportRun.init();
            reportRun.run();
            new FileIOPermission(mFile,'rw').notifyAll();
}


To Email the PDF:

public static void emailReport()
{
    ClrObject                               clrObj;
    SMTPMail.Mail                           mail;
     System.Exception                       clrEx;
     str                                    sText;
     str                                    sDate;
    test_PrintDataCustPrcList               testMail;
    ContactPerson                           conTactPers;
    System.Net.Mail.MailMessage             mailMessage;
    PrintJobSettings                        printset;
    System.Net.Mail.Attachment              attachment;
    System.Net.Mail.AttachmentCollection    attachementCollection;
    System.Net.Mail.SmtpClient              smtpClient;
    System.Net.Mail.MailAddress             mailAddressFrom;
    System.Net.Mail.MailAddress             mailAddressTo;
    str                                     strBody;
    str                                     strSMTPServer;
    str                                     strFileName;
    str                                     fromAddr,toAddr;
    //str                                     path ="\\"+"\\pmfcgrb24\\TempQuotePDF";
    str path = "\\"+"\\pmfcgrb24\\temppricelistPDF";
    FileIOPermission                        perm;
    COM                                     c;
    ReportRun                               r;
    Args _ag= new Args("pmf_CustPrcListNewDesgn");
    SysEmailParameters parameters = SysEmailParameters::find(false);
    // To Email
    InteropPermission permission = new InteropPermission(InteropKind::ClrInterop);

    SysMailer   mailer;
    ;

    permission.assert();
    permission.demand();

    clrObj = new SMTPMail.Mail();
    mail = clrObj;

    while select testMail
    where testMail.CurUserId == XUserInfo::find(false, curUserId()).name //&& testMail.CheckCust == NoYes::Yes
    {
        if (testMail)
        {
            select firstonly conTactPers
                where conTactPers.CustAccount == testMAil.tmpCustAccount;
            try
            {
                // preparing parameters
                if (parameters)
                {
                    mail.set_server(parameters.SMTPRelayServerName);
                    mail.set_port(parameters.SMTPPortNumber);
                    /*mail.set_user("sa-grb13");
                    mail.set_pass("S3viceMet1mbeRs");*/
                    mail.set_user(parameters.SMTPUserName);
                    mail.set_pass(SysEmailParameters::password());
                    if(parameters.NTLM == 1)
                    mail.set_NTLM(true);
                }
                mail.set_subject(strfmt("%1 - Price List - %2",testMAil.tmpCustName,testMail.tmpNewPriceDate));
                mail.set_body("Pioneer Metal Finishing - Customer Price List Attached.");
                //mail.set_sentFrom(fromAddr);
                //if (contactPers.Email)
                //{
                    mail.set_sentFrom("NoReply@pioneermetal.com");
                    mail.set_sendToString(conTactPers.Email);
                    //strFileName = path+"\\"+strfmt("%1 %2",testMail.tmpCustName,systemDateget())+".pdf";
                    //strFileName = path+"\\"+strfmt("%1",testMail.tmpCustName)+".pdf";
                    strFileName = path+"\\"+conTactPers.Name+".pdf";
                    mail.set_attachmentString(strFileName);
                    mail.set_extension('.pdf');
                    mail.run();
                //}
            }
            catch (Exception::CLRError)
            {
                clrEx = CLRInterop::getLastException();
                while ( clrEx )
                {
                    sText = clrEx.get_Message();
                    error( sText );
                    clrEx = clrEx.get_InnerException();
                }
            }
       }
    }
    permission.notifyAll();
     CodeAccessPermission::revertAssert();
}


Please give me any suggestion, 

Regards,

Nishu

*This post is locked for comments

I have the same question (0)
  • Community Member Profile Picture
    on at

    Hi,

    The reason for the above error is that, abode.exe process would have been in use when are trying to delete the file. So, you need to kill the process.

    You can optimize & minimize your code for sending PDF using the code in any of the below links:

    1. www.msdynamicsax.info/.../send-e-mail-through-code-with.html

    2. ismailozcan68.wordpress.com/.../comment-page-1

    Or if you still need to use the same code, refer the below link to kill the process using X++ code:

    jkmsdax2012.wordpress.com/.../how-to-open-pdf-files-from-ax-using-x-in-ax-2012

    Please mark this answer as verified if it helped you!!!

  • Suggested answer
    Sheikh Sohail Profile Picture
    6,125 on at

    Why you are generating PDF? you can directory send PDF via binary attachment.

    Have you check this blog? its specially design for D365FO where we couldn't create & save file.

    d365technext.blogspot.com/.../email-ssrs-report-as-attachment-d365fo.html

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the March Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics AX (Archived)

#1
CP04-islander Profile Picture

CP04-islander 39

#2
Michel ROY Profile Picture

Michel ROY 14

#3
imran ul haq Profile Picture

imran ul haq 8

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans