ALV to PDF to Email

Can someone tell me how we can convert an ALV report to PDF and send it as an attachment to the external emial.
Please help me.
Thanks,
Sneha Singh.

I wrote a program that you can pass an ALV report and a variant and it will send the results as a PDF or HTML attachment.  Here it is...
REPORT  ZEMAILREPORT.
DATA: BEGIN OF MAIL_TO OCCURS 0,
        SMTP_ADDR LIKE SOLI-LINE.
DATA: END OF MAIL_TO.
DATA: I_ABAPLIST  LIKE ABAPLIST OCCURS 0 WITH HEADER LINE.
DATA: I_CONTENT_BIN LIKE W3HTML OCCURS 0 WITH HEADER LINE.
DATA: W_DOC_DATA LIKE SODOCCHGI1.
DATA: W_SENT_TO_ALL LIKE SONV-FLAG.
DATA: W_LINE_SIZE TYPE I.
DATA: I_PACKING_LIST LIKE SOPCKLSTI1 OCCURS 0 WITH HEADER LINE,
      I_ATTACHMENT LIKE SOLISTI1 OCCURS 0 WITH HEADER LINE,
      I_RECEIVERS LIKE SOMLRECI1 OCCURS 0 WITH HEADER LINE.
DATA: W_PDF_BYTECOUNT TYPE I.
DATA: W_SPOOL_ID LIKE TSP01-RQIDENT.
DATA: W_BUFFER TYPE STRING.
*DATA: SPOOL PARAMETERS pri_params.
DATA: W_PRINT_PARAMETERS TYPE PRI_PARAMS,
      W_VALID_FLAG(1) TYPE C,
      W_LIST_TEXT LIKE PRI_PARAMS-PRTXT.
DATA: I_PDF LIKE TLINE OCCURS 0 WITH HEADER LINE.
SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-002.
PARAMETERS: P_REPRT LIKE RS38M-PROGRAMM OBLIGATORY.
PARAMETERS: P_VARI LIKE RSVAR-VARIANT OBLIGATORY.
PARAMETERS: P_TITLE LIKE SODOCCHGI1-OBJ_DESCR OBLIGATORY.
PARAMETERS: P_FILNAM LIKE SODOCCHGI1-OBJ_DESCR OBLIGATORY.
SELECTION-SCREEN END OF BLOCK B1.
SELECTION-SCREEN BEGIN OF BLOCK B2 WITH FRAME TITLE TEXT-001.
SELECT-OPTIONS:
  S_EMAIL FOR MAIL_TO-SMTP_ADDR OBLIGATORY NO INTERVALS.
SELECTION-SCREEN END OF BLOCK B2.
SELECTION-SCREEN BEGIN OF BLOCK B3 WITH FRAME TITLE TEXT-003.
PARAMETERS: P_HTML RADIOBUTTON GROUP GF DEFAULT 'X',
            P_PDF RADIOBUTTON GROUP GF.
SELECTION-SCREEN END OF BLOCK B3.
START-OF-SELECTION.
  IF P_HTML = 'X'.
    SUBMIT (P_REPRT) USING SELECTION-SET P_VARI
            EXPORTING LIST TO MEMORY AND RETURN.
    CALL FUNCTION 'LIST_FROM_MEMORY'
      TABLES
        LISTOBJECT = I_ABAPLIST
      EXCEPTIONS
        NOT_FOUND  = 1
        OTHERS     = 2.
    IF SY-SUBRC <> 0.
      MESSAGE I000(OO) WITH 'Output for report'
                            P_REPRT
                            'not found'.
      EXIT.
    ENDIF.
    CALL FUNCTION 'WWW_HTML_FROM_LISTOBJECT'
EXPORTING
  REPORT_NAME         =
  TEMPLATE_NAME       = 'WEBREPORTING_REPORT'
      TABLES
        HTML                = I_CONTENT_BIN
        LISTOBJECT          = I_ABAPLIST.
  ELSE.
    W_LIST_TEXT = P_TITLE.
    CALL FUNCTION 'GET_PRINT_PARAMETERS'
      EXPORTING
        ARCHIVE_MODE           = '1'
        NO_DIALOG              = 'X'
        DESTINATION            = SPACE
        IMMEDIATELY            = 'X'
        LIST_TEXT              = W_LIST_TEXT
      IMPORTING
        OUT_PARAMETERS         = W_PRINT_PARAMETERS
         OUT_ARCHIVE_PARAMETERS = W_ARCHI_PARAMETERS
        VALID                  = W_VALID_FLAG
      EXCEPTIONS
        INVALID_PRINT_PARAMS   = 2
        OTHERS                 = 4.
    PERFORM DETERMINE_SPOOL_NAME CHANGING W_PRINT_PARAMETERS-PLIST.
    IF SY-SUBRC <> 0.
      MESSAGE E000(OO) WITH 'Can not determine print'
                            'parameters needed for'
                            'PDF conversion'.
    ENDIF.
    SUBMIT (P_REPRT) USING SELECTION-SET P_VARI
            TO SAP-SPOOL
            SPOOL PARAMETERS W_PRINT_PARAMETERS
            WITHOUT SPOOL DYNPRO
           COVER TEXT P_TITLE
           IMMEDIATELY SPACE
           KEEP IN SPOOL ' '
            AND RETURN.
    COMMIT WORK AND WAIT.
    PERFORM GET_SPOOL_NUMBER USING W_PRINT_PARAMETERS-PLIST
                          CHANGING W_SPOOL_ID.
    IF W_SPOOL_ID IS INITIAL.
      MESSAGE I000(OO) WITH 'Output for report'
                            P_REPRT
                            'not found'.
      EXIT.
    ELSE.
      CALL FUNCTION 'CONVERT_ABAPSPOOLJOB_2_PDF'
        EXPORTING
          SRC_SPOOLID                    = W_SPOOL_ID
      NO_DIALOG                      =
      DST_DEVICE                     =
      PDF_DESTINATION                =
      IMPORTING
        PDF_BYTECOUNT                  = W_PDF_BYTECOUNT
      PDF_SPOOLID                    =
      LIST_PAGECOUNT                 =
      BTC_JOBNAME                    =
      BTC_JOBCOUNT                   =
       TABLES
         PDF                            = I_PDF
       EXCEPTIONS
         ERR_NO_ABAP_SPOOLJOB           = 1
         ERR_NO_SPOOLJOB                = 2
         ERR_NO_PERMISSION              = 3
         ERR_CONV_NOT_POSSIBLE          = 4
         ERR_BAD_DESTDEVICE             = 5
         USER_CANCELLED                 = 6
         ERR_SPOOLERROR                 = 7
         ERR_TEMSEERROR                 = 8
         ERR_BTCJOB_OPEN_FAILED         = 9
         ERR_BTCJOB_SUBMIT_FAILED       = 10
         ERR_BTCJOB_CLOSE_FAILED        = 11
         OTHERS                         = 12
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE 'E' NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ELSE.
*CALL FUNCTION 'SX_TABLE_LINE_WIDTH_CHANGE'
      EXPORTING
        line_width_src              = 134
        line_width_dst              = 255
      TABLES
        content_in                  = i_pdf
        content_out                 = l_attachment
      EXCEPTIONS
        err_line_width_src_too_long = 1
        err_line_width_dst_too_long = 2
        err_conv_failed             = 3
        OTHERS                      = 4.
    IF sy-subrc NE 0.
      MESSAGE s000(0k) WITH 'Conversion Failed'.
      EXIT.
    ENDIF.
Transfer the 132-long strings to 255-long strings
        LOOP AT I_PDF.
          TRANSLATE I_PDF USING ' ~'.
          CONCATENATE W_BUFFER I_PDF INTO W_BUFFER.
        ENDLOOP.
        TRANSLATE W_BUFFER USING '~ '.
        DO.
          I_CONTENT_BIN = W_BUFFER.
          APPEND I_CONTENT_BIN.
          SHIFT W_BUFFER LEFT BY 255 PLACES.
          IF W_BUFFER IS INITIAL.
            EXIT.
          ENDIF.
        ENDDO.
      ENDIF.
    ENDIF.
  ENDIF.
  W_DOC_DATA-OBJ_NAME = 'List'.
  W_DOC_DATA-OBJ_DESCR = P_TITLE.
  W_DOC_DATA-SENSITIVTY = 'O'.
  W_DOC_DATA-OBJ_LANGU = SY-LANGU.
Add the recipient(s) email address
  REFRESH I_RECEIVERS.
  LOOP AT S_EMAIL.
    CLEAR I_RECEIVERS.
    I_RECEIVERS-RECEIVER   = S_EMAIL-LOW.
    I_RECEIVERS-REC_TYPE   = 'U'.
    I_RECEIVERS-COM_TYPE   = 'INT'.
    I_RECEIVERS-NOTIF_DEL  = 'X'.
    I_RECEIVERS-NOTIF_NDEL = 'X'.
    APPEND I_RECEIVERS.
  ENDLOOP.
  CLEAR I_PACKING_LIST.
  REFRESH I_PACKING_LIST.
  I_PACKING_LIST-TRANSF_BIN = 'X'.
  I_PACKING_LIST-HEAD_START = 0.
  I_PACKING_LIST-HEAD_NUM = 0.
  I_PACKING_LIST-BODY_START = 0.
  I_PACKING_LIST-BODY_NUM = 0.
  I_PACKING_LIST-DOC_TYPE = 'RAW'.
  I_PACKING_LIST-OBJ_DESCR = P_FILNAM.
  APPEND I_PACKING_LIST.
  I_PACKING_LIST-TRANSF_BIN = 'X'.
  I_PACKING_LIST-HEAD_START = 0.
  I_PACKING_LIST-HEAD_NUM = 0.
  I_PACKING_LIST-BODY_START = 1.
  IF P_HTML = 'X'.
    I_PACKING_LIST-DOC_TYPE = 'HTM'.
  ELSE.
    I_PACKING_LIST-DOC_TYPE = 'PDF'.
  ENDIF.
  DESCRIBE TABLE I_CONTENT_BIN LINES I_PACKING_LIST-BODY_NUM.
  CLASS CL_ABAP_CHAR_UTILITIES DEFINITION LOAD.
  IF CL_ABAP_CHAR_UTILITIES=>CHARSIZE > 1. " system is Unicode
    W_LINE_SIZE = 510.
  ELSE.
    W_LINE_SIZE = 255.
  ENDIF.
  READ TABLE  I_CONTENT_BIN INDEX I_PACKING_LIST-BODY_NUM.
  IF P_HTML = 'X'.
    I_PACKING_LIST-DOC_SIZE = ( I_PACKING_LIST-BODY_NUM - 1 ) * W_LINE_SIZE
                     + STRLEN( I_CONTENT_BIN ).
  ELSE.
    I_PACKING_LIST-DOC_SIZE = W_PDF_BYTECOUNT.
  ENDIF.
  APPEND I_PACKING_LIST.
  CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
   EXPORTING
     DOCUMENT_DATA              = W_DOC_DATA
      PUT_IN_OUTBOX              = 'X'
     COMMIT_WORK                = 'X'
   IMPORTING
     SENT_TO_ALL                = W_SENT_TO_ALL
   TABLES
     PACKING_LIST               = I_PACKING_LIST
     CONTENTS_BIN               = I_CONTENT_BIN
     contents_txt               = i_attachment
     RECEIVERS                  = I_RECEIVERS
   EXCEPTIONS
     TOO_MANY_RECEIVERS         = 1
     DOCUMENT_NOT_SENT          = 2
     DOCUMENT_TYPE_NOT_EXIST    = 3
     OPERATION_NO_AUTHORIZATION = 4
     PARAMETER_ERROR            = 5
     X_ERROR                    = 6
     ENQUEUE_ERROR              = 7
     OTHERS                     = 8.
*&      Form  get_spool_number
      text
     -->P_REPID    text
     -->P_UNAME    text
     -->P_RQIDENT  text
FORM GET_SPOOL_NUMBER USING P_SPOOL_NAME
                CHANGING P_RQIDENT.
  DATA: W_TSP01 LIKE TSP01.
  CLEAR: P_RQIDENT.
  SELECT * INTO W_TSP01
         FROM TSP01 UP TO 1 ROWS
    WHERE  RQ2NAME = P_SPOOL_NAME
  ORDER BY RQCRETIME DESCENDING.
  ENDSELECT.
  IF SY-SUBRC = 0.
    P_RQIDENT = W_TSP01-RQIDENT.
  ENDIF.
ENDFORM." get_spool_number
*&      Form  DETERMINE_SPOOL_NAME
      text
     <--P_W_SPOOL_NAME  text
FORM DETERMINE_SPOOL_NAME  CHANGING P_SPOOL_NAME.
  CLEAR: P_SPOOL_NAME.
  CALL FUNCTION 'NUMBER_GET_NEXT'
    EXPORTING
      NR_RANGE_NR                   = '01'
      OBJECT                        = 'ZSPOOLNAME'
    QUANTITY                      = '1'
    SUBOBJECT                     = ' '
    TOYEAR                        = '0000'
    IGNORE_BUFFER                 = ' '
    IMPORTING
      NUMBER                        = P_SPOOL_NAME
    QUANTITY                      =
    RETURNCODE                    =
   EXCEPTIONS
     INTERVAL_NOT_FOUND            = 1
     NUMBER_RANGE_NOT_INTERN       = 2
     OBJECT_NOT_FOUND              = 3
     QUANTITY_IS_0                 = 4
     QUANTITY_IS_NOT_1             = 5
     INTERVAL_OVERFLOW             = 6
     BUFFER_OVERFLOW               = 7
     OTHERS                        = 8
  IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE 'E' NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
  ENDIF.
ENDFORM.                    " DETERMINE_SPOOL_NAME
*Selection-texts
*P_FILNAM     Name of attachment
*P_HTML     Html
*P_PDF     PDF
*P_REPRT     Program Name
*P_TITLE     Email Subject
*P_VARI     Variant Name
*S_EMAIL     Email address
*Text symbols
*001     Email address to send report output
*002     Report parameters
*003     Format options

Similar Messages

  • Block List ALV Output Send As Email Attachment

    Hi,  All The ABAP Gurus,
    I have made a block ALV Report. I want that this output should be converted into .xls with HTML format and this should be send in email as attachment. This all will be made in a background job which will be scheduled daily.
    How can I achieve this? I know that the output of classical report can be attached as pdf in email.But I want in Block ALV.
    Thanks in Advance.
    Regards,
    Bharti Jain
    Edited by: Bharti Jain on Jun 28, 2011 10:20 AM

    Hi
    Not 100 percent sure what you want to do here.  I am confused by the .xls in html format.   If you want the output in html you can submit the program and export the list to memory,  Then retrieve the list and convert it to html.  i have done this with the program 1sdbf12l/rv14akzy . see code below.  This converts the output to html, you are left with a binary itab and size at the end of the routine and this can be attached to an email.
    Submit Program and export the list to Memory
    SUBMIT /1sdbf12l/rv14akzy USING SELECTION-SCREEN '1000'
      WITH SELECTION-TABLE lt_params_new EXPORTING LIST TO MEMORY AND RETURN.
      CALL FUNCTION 'LIST_FROM_MEMORY'
        TABLES
          listobject = lt_list
        EXCEPTIONS
          not_found  = 1
          OTHERS     = 2.
    Convert the List to html
      IF sy-subrc = 0.
        DATA: it_html TYPE TABLE OF bapihtml WITH HEADER LINE,
              it_html_out TYPE TABLE OF bapihtml WITH HEADER LINE,
              lt_html TYPE TABLE OF bapihtml WITH HEADER LINE,
              lv_html LIKE LINE OF it_html,
              lv_html_out TYPE string.
        DATA: lv_html_tab_wide(50000) TYPE c.
        DATA: lineno TYPE i, length TYPE i, size TYPE i.
        DATA: gui_codepage(4) TYPE n,        " added for message 500824
              is_unicode TYPE rststype-sel_ok.
        DATA: convert_output TYPE xstring,
              convert_buffer TYPE xstring.
        CALL FUNCTION 'LIST_FREE_MEMORY'
          TABLES
            listobject = lt_list.
        CALL FUNCTION 'WWW_HTML_FROM_LISTOBJECT'
             EXPORTING
                  REPORT_NAME   =
                  template_name = 'WEBREPORTING_REPORT'
             TABLES
                  html          =  it_html
                  listobject    =  lt_list.
        DESCRIBE TABLE it_html LINES lineno .
        DESCRIBE FIELD it_html LENGTH length IN BYTE MODE.
        size = length * lineno.
        CALL 'CUR_LCL' ID 'GUICP'  FIELD gui_codepage.
        CALL FUNCTION 'SCP_GET_CODEPAGE_PROPERTIES'
          EXPORTING
            codepage         = gui_codepage
          IMPORTING
            can_unicode      = is_unicode
          EXCEPTIONS
            codepage_unknown = 1.
        IF sy-subrc <> 0.
          CLEAR gui_codepage.
        ENDIF.
        IF is_unicode EQ 'X'.         "in case of unicode, always use utf-8
          gui_codepage = '4110'.
        ENDIF.
        CLEAR: convert_output, convert_buffer.
        LOOP AT it_html INTO lv_html.
          REPLACE ALL OCCURRENCES OF c_bg_def IN lv_html WITH c_bg_white.
          CALL FUNCTION 'SCP_TRANSLATE_CHARS'
            EXPORTING
              inbuff           = lv_html
              outcode          = gui_codepage
              csubst           = 'X'
              substc_space     = 'X'
            IMPORTING
              outbuff          = convert_output
            EXCEPTIONS
              invalid_codepage = 1
              internal_error   = 2
              cannot_convert   = 3
              fields_bad_type  = 4
              OTHERS           = 5.
          IF sy-subrc <> 0.
           message i020 raising download_error.
          ENDIF.
          CONCATENATE convert_buffer convert_output INTO convert_buffer IN
          BYTE MODE.
          CONCATENATE lv_html_out lv_html INTO lv_html_out.
        ENDLOOP.
        ev_html_string = lv_html_out.
        i = 0.
        DESCRIBE FIELD html_tab_converted LENGTH tablength IN BYTE MODE.
        WHILE i < XSTRLEN( convert_buffer ).
          dummy = XSTRLEN( convert_buffer ) - i.
          IF tablength > dummy.
            html_tab_converted-line = convert_buffer+i(dummy).
          ELSE.
            html_tab_converted-line = convert_buffer+i(tablength).
          ENDIF.
          i = i + tablength.
          APPEND html_tab_converted.
        ENDWHILE.
        et_bin[] = html_tab_converted[].
        ev_bin_size = size.

  • How can I convert a report/ ALV in PDF format?

    Can you tell me how can I convert a report or ALV in PDF format?
    Regards,
    Subhasish

    hi ,
    check this..
    *& Report  ZSPOOLTOPDF                                                 *
    *& Converts spool request into PDF document and emails it to           *
    *& recipicant.                                                         *
    *& Execution                                                           *
    *& This program must be run as a background job in-order for the write *
    *& commands to create a Spool request rather than be displayed on      *
    *& screen                                                              *
    REPORT  zspooltopdf.
    PARAMETER: p_email1 LIKE somlreci1-receiver
                                        DEFAULT '[email protected]',
               p_sender LIKE somlreci1-receiver
                                        DEFAULT '[email protected]',
               p_delspl  AS CHECKBOX.
    *DATA DECLARATION
    DATA: gd_recsize TYPE i.
    Spool IDs
    TYPES: BEGIN OF t_tbtcp.
            INCLUDE STRUCTURE tbtcp.
    TYPES: END OF t_tbtcp.
    DATA: it_tbtcp TYPE STANDARD TABLE OF t_tbtcp INITIAL SIZE 0,
          wa_tbtcp TYPE t_tbtcp.
    Job Runtime Parameters
    DATA: gd_eventid LIKE tbtcm-eventid,
          gd_eventparm LIKE tbtcm-eventparm,
          gd_external_program_active LIKE tbtcm-xpgactive,
          gd_jobcount LIKE tbtcm-jobcount,
          gd_jobname LIKE tbtcm-jobname,
          gd_stepcount LIKE tbtcm-stepcount,
          gd_error    TYPE sy-subrc,
          gd_reciever TYPE sy-subrc.
    DATA:  w_recsize TYPE i.
    DATA: gd_subject   LIKE sodocchgi1-obj_descr,
          it_mess_bod LIKE solisti1 OCCURS 0 WITH HEADER LINE,
          it_mess_att LIKE solisti1 OCCURS 0 WITH HEADER LINE,
          gd_sender_type     LIKE soextreci1-adr_typ,
          gd_attachment_desc TYPE so_obj_nam,
          gd_attachment_name TYPE so_obj_des.
    Spool to PDF conversions
    DATA: gd_spool_nr LIKE tsp01-rqident,
          gd_destination LIKE rlgrap-filename,
          gd_bytecount LIKE tst01-dsize,
          gd_buffer TYPE string.
    Binary store for PDF
    DATA: BEGIN OF it_pdf_output OCCURS 0.
            INCLUDE STRUCTURE tline.
    DATA: END OF it_pdf_output.
    CONSTANTS: c_dev LIKE  sy-sysid VALUE 'DEV',
               c_no(1)     TYPE c   VALUE ' ',
               c_device(4) TYPE c   VALUE 'LOCL'.
    *START-OF-SELECTION.
    START-OF-SELECTION.
    Write statement to represent report output. Spool request is created
    if write statement is executed in background. This could also be an
    ALV grid which would be converted to PDF without any extra effort
      WRITE 'Hello World'.
      new-page.
      commit work.
      new-page print off.
      IF sy-batch EQ 'X'.
        PERFORM get_job_details.
        PERFORM obtain_spool_id.
    Alternative way could be to submit another program and store spool
    id into memory, will be stored in sy-spono.
    *submit ZSPOOLTOPDF2
           to sap-spool
           spool parameters   %_print
           archive parameters %_print
           without spool dynpro
           and return.
    Get spool id from program called above
    IMPORT w_spool_nr FROM MEMORY ID 'SPOOLTOPDF'.
        PERFORM convert_spool_to_pdf.
        PERFORM process_email.
        if p_delspl EQ 'X'.
          PERFORM delete_spool.
        endif.
        IF sy-sysid = c_dev.
          wait up to 5 seconds.
          SUBMIT rsconn01 WITH mode   = 'INT'
                          WITH output = 'X'
                          AND RETURN.
        ENDIF.
      ELSE.
        SKIP.
        WRITE:/ 'Program must be executed in background in-order for spool',
                'request to be created.'.
      ENDIF.
          FORM obtain_spool_id                                          *
    FORM obtain_spool_id.
      CHECK NOT ( gd_jobname IS INITIAL ).
      CHECK NOT ( gd_jobcount IS INITIAL ).
      SELECT * FROM  tbtcp
                     INTO TABLE it_tbtcp
                     WHERE      jobname     = gd_jobname
                     AND        jobcount    = gd_jobcount
                     AND        stepcount   = gd_stepcount
                     AND        listident   <> '0000000000'
                     ORDER BY   jobname
                                jobcount
                                stepcount.
      READ TABLE it_tbtcp INTO wa_tbtcp INDEX 1.
      IF sy-subrc = 0.
        message s004(zdd) with gd_spool_nr.
        gd_spool_nr = wa_tbtcp-listident.
        MESSAGE s004(zdd) WITH gd_spool_nr.
      ELSE.
        MESSAGE s005(zdd).
      ENDIF.
    ENDFORM.
          FORM get_job_details                                          *
    FORM get_job_details.
    Get current job details
      CALL FUNCTION 'GET_JOB_RUNTIME_INFO'
           IMPORTING
                eventid                 = gd_eventid
                eventparm               = gd_eventparm
                external_program_active = gd_external_program_active
                jobcount                = gd_jobcount
                jobname                 = gd_jobname
                stepcount               = gd_stepcount
           EXCEPTIONS
                no_runtime_info         = 1
                OTHERS                  = 2.
    ENDFORM.
          FORM convert_spool_to_pdf                                     *
    FORM convert_spool_to_pdf.
      CALL FUNCTION 'CONVERT_ABAPSPOOLJOB_2_PDF'
           EXPORTING
                src_spoolid              = gd_spool_nr
                no_dialog                = c_no
                dst_device               = c_device
           IMPORTING
                pdf_bytecount            = gd_bytecount
           TABLES
                pdf                      = it_pdf_output
           EXCEPTIONS
                err_no_abap_spooljob     = 1
                err_no_spooljob          = 2
                err_no_permission        = 3
                err_conv_not_possible    = 4
                err_bad_destdevice       = 5
                user_cancelled           = 6
                err_spoolerror           = 7
                err_temseerror           = 8
                err_btcjob_open_failed   = 9
                err_btcjob_submit_failed = 10
                err_btcjob_close_failed  = 11
                OTHERS                   = 12.
      CHECK sy-subrc = 0.
    Transfer the 132-long strings to 255-long strings
      LOOP AT it_pdf_output.
        TRANSLATE it_pdf_output USING ' ~'.
        CONCATENATE gd_buffer it_pdf_output INTO gd_buffer.
      ENDLOOP.
      TRANSLATE gd_buffer USING '~ '.
      DO.
        it_mess_att = gd_buffer.
        APPEND it_mess_att.
        SHIFT gd_buffer LEFT BY 255 PLACES.
        IF gd_buffer IS INITIAL.
          EXIT.
        ENDIF.
      ENDDO.
    ENDFORM.
          FORM process_email                                            *
    FORM process_email.
      DESCRIBE TABLE it_mess_att LINES gd_recsize.
      CHECK gd_recsize > 0.
      PERFORM send_email USING p_email1.
    perform send_email using p_email2.
    ENDFORM.
          FORM send_email                                               *
    -->  p_email                                                       *
    FORM send_email USING p_email.
      CHECK NOT ( p_email IS INITIAL ).
      REFRESH it_mess_bod.
    Default subject matter
      gd_subject         = 'Subject'.
      gd_attachment_desc = 'Attachname'.
    CONCATENATE 'attach_name' ' ' INTO gd_attachment_name.
      it_mess_bod        = 'Message Body text, line 1'.
      APPEND it_mess_bod.
      it_mess_bod        = 'Message Body text, line 2...'.
      APPEND it_mess_bod.
    If no sender specified - default blank
      IF p_sender EQ space.
        gd_sender_type  = space.
      ELSE.
        gd_sender_type  = 'INT'.
      ENDIF.
    Send file by email as .xls speadsheet
      PERFORM send_file_as_email_attachment
                                   tables it_mess_bod
                                          it_mess_att
                                    using p_email
                                          'Example .xls documnet attachment'
                                          'PDF'
                                          gd_attachment_name
                                          gd_attachment_desc
                                          p_sender
                                          gd_sender_type
                                 changing gd_error
                                          gd_reciever.
    ENDFORM.
          FORM delete_spool                                             *
    FORM delete_spool.
      DATA: ld_spool_nr TYPE tsp01_sp0r-rqid_char.
      ld_spool_nr = gd_spool_nr.
      CHECK p_delspl <> c_no.
      CALL FUNCTION 'RSPO_R_RDELETE_SPOOLREQ'
           EXPORTING
                spoolid = ld_spool_nr.
    ENDFORM.
    *&      Form  SEND_FILE_AS_EMAIL_ATTACHMENT
          Send email
    FORM send_file_as_email_attachment tables it_message
                                              it_attach
                                        using p_email
                                              p_mtitle
                                              p_format
                                              p_filename
                                              p_attdescription
                                              p_sender_address
                                              p_sender_addres_type
                                     changing p_error
                                              p_reciever.
      DATA: ld_error    TYPE sy-subrc,
            ld_reciever TYPE sy-subrc,
            ld_mtitle LIKE sodocchgi1-obj_descr,
            ld_email LIKE  somlreci1-receiver,
            ld_format TYPE  so_obj_tp ,
            ld_attdescription TYPE  so_obj_nam ,
            ld_attfilename TYPE  so_obj_des ,
            ld_sender_address LIKE  soextreci1-receiver,
            ld_sender_address_type LIKE  soextreci1-adr_typ,
            ld_receiver LIKE  sy-subrc.
    data:   t_packing_list like sopcklsti1 occurs 0 with header line,
            t_contents like solisti1 occurs 0 with header line,
            t_receivers like somlreci1 occurs 0 with header line,
            t_attachment like solisti1 occurs 0 with header line,
            t_object_header like solisti1 occurs 0 with header line,
            w_cnt type i,
            w_sent_all(1) type c,
            w_doc_data like sodocchgi1.
      ld_email   = p_email.
      ld_mtitle = p_mtitle.
      ld_format              = p_format.
      ld_attdescription      = p_attdescription.
      ld_attfilename         = p_filename.
      ld_sender_address      = p_sender_address.
      ld_sender_address_type = p_sender_addres_type.
    Fill the document data.
      w_doc_data-doc_size = 1.
    Populate the subject/generic message attributes
      w_doc_data-obj_langu = sy-langu.
      w_doc_data-obj_name  = 'SAPRPT'.
      w_doc_data-obj_descr = ld_mtitle .
      w_doc_data-sensitivty = 'F'.
    Fill the document data and get size of attachment
      CLEAR w_doc_data.
      READ TABLE it_attach INDEX w_cnt.
      w_doc_data-doc_size =
         ( w_cnt - 1 ) * 255 + STRLEN( it_attach ).
      w_doc_data-obj_langu  = sy-langu.
      w_doc_data-obj_name   = 'SAPRPT'.
      w_doc_data-obj_descr  = ld_mtitle.
      w_doc_data-sensitivty = 'F'.
      CLEAR t_attachment.
      REFRESH t_attachment.
      t_attachment[] = it_attach[].
    Describe the body of the message
      CLEAR t_packing_list.
      REFRESH t_packing_list.
      t_packing_list-transf_bin = space.
      t_packing_list-head_start = 1.
      t_packing_list-head_num = 0.
      t_packing_list-body_start = 1.
      DESCRIBE TABLE it_message LINES t_packing_list-body_num.
      t_packing_list-doc_type = 'RAW'.
      APPEND t_packing_list.
    Create attachment notification
      t_packing_list-transf_bin = 'X'.
      t_packing_list-head_start = 1.
      t_packing_list-head_num   = 1.
      t_packing_list-body_start = 1.
      DESCRIBE TABLE t_attachment LINES t_packing_list-body_num.
      t_packing_list-doc_type   =  ld_format.
      t_packing_list-obj_descr  =  ld_attdescription.
      t_packing_list-obj_name   =  ld_attfilename.
      t_packing_list-doc_size   =  t_packing_list-body_num * 255.
      APPEND t_packing_list.
    Add the recipients email address
      CLEAR t_receivers.
      REFRESH t_receivers.
      t_receivers-receiver = ld_email.
      t_receivers-rec_type = 'U'.
      t_receivers-com_type = 'INT'.
      t_receivers-notif_del = 'X'.
      t_receivers-notif_ndel = 'X'.
      APPEND t_receivers.
      CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
           EXPORTING
                document_data              = w_doc_data
                put_in_outbox              = 'X'
                sender_address             = ld_sender_address
                sender_address_type        = ld_sender_address_type
                commit_work                = 'X'
           IMPORTING
                sent_to_all                = w_sent_all
           TABLES
                packing_list               = t_packing_list
                contents_bin               = t_attachment
                contents_txt               = it_message
                receivers                  = t_receivers
           EXCEPTIONS
                too_many_receivers         = 1
                document_not_sent          = 2
                document_type_not_exist    = 3
                operation_no_authorization = 4
                parameter_error            = 5
                x_error                    = 6
                enqueue_error              = 7
                OTHERS                     = 8.
    Populate zerror return code
      ld_error = sy-subrc.
    Populate zreceiver return code
      LOOP AT t_receivers.
        ld_receiver = t_receivers-retrn_code.
      ENDLOOP.
    ENDFORM.
    regards,
    venkat.

  • Dynamic CRM 2013 Online how to execute Report, generate PDF and email

    Dear All,
    I am using Dynamic CRM 2013 online. For quote, I have workflow and Dialogue processes for review process. On approval, I want the system to generate a PDF of quote report, attach the PDF and email it to the Customer.
    Better I would like, When approver, clicks on the approve button, the system should auto generate a PDF of quote report, attach the PDF and email it to the Customer, without any further input from the user. If its not possible, I may have to put button on
    quote form.
    I am using the attached code, but facing various issues.
    1. Under prepare the SOAP Message coding part, I am not sure what should be the below URL for CRM 2013 Online?
    xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    2. What should be the emailid here? Is it Recepient Contact id(Guid) ?
    var emailid = resultXml.selectSingleNode("//CreateResult").nodeTypedValue;
    alert("emailid" + emailid.toString());
    3. Using this code, not able to create Entity for "ActivityMimeAttachment", I am getting newEntity as undefined.
    Below is the code I am using. Please check and help me out, where I am going wrong. Let me know if any better way to implement it. At present, I have put one button on quote form, on click event, below code will get executed.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript">
    var Xrm;
    if (window.opener) { Xrm = window.opener.Xrm; }
    else if (window.parent) { Xrm = window.parent.Xrm; }
    function getReportingSession() {
    var reportName = "Quotation_Report"; //set this to the report you are trying to download
    var reportId = "7C39D18F-1DC6-E311-8986-D89D6765B238"; //set this to the guid of the report you are trying to download
    var recordid = Xrm.Page.data.entity.getId();
    // recordid = recordid.substring(1, 37); //getting rid of curly brackets
    alert(recordid);
    var pth = Xrm.Page.context.getServerUrl() + "/CRMReports/rsviewer/reportviewer.aspx";
    var retrieveEntityReq = new XMLHttpRequest();
    retrieveEntityReq.open("POST", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    retrieveEntityReq.send("id=%7B" + reportId + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false");
    var x = retrieveEntityReq.responseText.indexOf("ReportSession=");
    var ret = new Array();
    ret[0] = retrieveEntityReq.responseText.substr(x + 14, retrieveEntityReq.responseText.indexOf("&", x) - x - 14); //the session id
    x = retrieveEntityReq.responseText.indexOf("ControlID=");
    ret[1] = retrieveEntityReq.responseText.substr(x + 10, retrieveEntityReq.responseText.indexOf("&", x) - x - 10); //the control id
    return ret;
    function createEntity(ent, entName, upd) {
    var jsonEntity = JSON.stringify(ent);
    var createEntityReq = new XMLHttpRequest();
    var ODataPath = Xrm.Page.context.getServerUrl() + "XRMServices/2011/OrganizationData.svc";
    createEntityReq.open("POST", ODataPath + "/" + entName + "Set" + upd, false);
    createEntityReq.setRequestHeader("Accept", "application/json");
    createEntityReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    createEntityReq.send(jsonEntity);
    var newEntity = JSON.parse(createEntityReq.responseText).d;
    alert("new entity" + newEntity);
    return newEntity;
    function createAttachment() {
    var params = getReportingSession();
    var recordid = Xrm.Page.data.entity.getId();
    alert("recordid " + recordid);
    var orgName = Xrm.Page.context.getOrgUniqueName();
    var userID = Xrm.Page.context.getUserId();
    //create email record
    // Prepare the SOAP message.
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    "<soap:Header>" +
    "</soap:Header>" +
    "<soap:Body>" +
    "<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entity xsi:type='email'>" +
    "<regardingobjectid type='quote'>" + recordid + "</regardingobjectid>" +
    "<subject>" + "Email with Attachment4" + "</subject>" +
    "</entity>" +
    "</Create>" +
    "</soap:Body>" +
    "</soap:Envelope>";
    // Prepare the xmlHttpObject and send the request.
    var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
    xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Create");
    xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xHReq.setRequestHeader("Content-Length", xml.length);
    xHReq.send(xml);
    // Capture the result
    var resultXml = xHReq.responseXML;
    // alert("resultXml " + resultXml);
    // Check for errors.
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
    alert("ERROR");
    var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
    alert(msg);
    var emailid = resultXml.selectSingleNode("//CreateResult").nodeTypedValue;
    alert("emailid" + emailid.toString());
    //var emailid = userID;
    var post = Object();
    post.Body = encodePdf(params);
    var email = new Array();
    email[0] =new Object();
    email[0].id = emailid;
    email[0].entityType ='email';
    post.Subject ="File Attachment";
    post.AttachmentNumber = 1;
    post.FileName ="Report.pdf";
    post.MimeType ="application/pdf";
    post.ObjectId = Object();
    post.ObjectId.LogicalName ="email";
    post.ObjectId.Id = email[0].id;
    post.ObjectTypeCode ="email";
    alert(post.ObjectId.Id);
    createEntity(post,"ActivityMimeAttachment", "");
    alert("created successfully");
    email.Subject = "Your Order";
    //Set The current order as the Regarding object
    email.RegardingObjectId = {
    Id: Xrm.Page.data.entity.getId(), //Get the current entity Id , here OrderId
    LogicalName: Xrm.Page.data.entity.getEntityName()//Get the current entity name, here it will be “salesOrder”
    //Create Email Activity
    SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });
    // Email Call Back function
    function EmailCallBack(result) {
    email = result; // Set the email to result to use it later in email attachment for retrieving activity Id
    var activityPartyFrom = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyFrom.PartyId = {
    Id: customerId, // id of entity you want to associate this activity with.
    LogicalName: "contact"
    // Set the "activity" of the ActivityParty
    activityPartyFrom.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity).
    activityPartyFrom.ParticipationTypeMask = { Value: 2 }; // 2 means ToRecipients
    // Create the from ActivityParty for the email
    SDK.JScriptRESTDataOperations.Create(activityPartyFrom, "ActivityParty", ActivityPartyFromCallBack, function (error) { alert(error.message); });
    var activityPartyTo = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyTo.PartyId = {
    Id: ownerId, // id of entity you want to associate this activity with.
    LogicalName: "systemuser"
    // Set the "activity" of the ActivityParty
    activityPartyTo.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity). activityPartyTo.ParticipationTypeMask = { Value: 1 }; // 1 means Sender
    // Create the from ActivityParty
    SDK.JScriptRESTDataOperations.Create(activityPartyTo, "ActivityParty", ActivityPartyToCallBack, function (error) { alert(error.message); });
    //ActivityParty From Callback
    function ActivityPartyFromCallBack(result) {
    //ActivityParty To Callback
    function ActivityPartyToCallBack(result) {
    var StringMaker = function () {
    this.parts = [];
    this.length = 0;
    this.append = function (s) {
    this.parts.push(s);
    this.length += s.length;
    this.prepend = function (s) {
    this.parts.unshift(s);
    this.length += s.length;
    this.toString = function () {
    return this.parts.join('');
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    function encode64(input) {
    var output = new StringMaker();
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    while (i < input.length) {
    chr1 = input[i++];
    chr2 = input[i++];
    chr3 = input[i++];
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
    enc3 = enc4 = 64;
    else if (isNaN(chr3)) {
    enc4 = 64;
    output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
    return output.toString();
    var bdy = new Array();
    var bdyLen = 0;
    function concat2Bdy(x) {
    bdy[bdyLen] = x;
    bdyLen++;
    function encodePdf(params) {
    bdy = new Array();
    bdyLen = 0;
    var retrieveEntityReq = new XMLHttpRequest();
    var pth = Xrm.Page.context.getServerUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
    retrieveEntityReq.open("GET", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.send();
    BinaryToArray(retrieveEntityReq.responseBody);
    return encode64(bdy);
    </SCRIPT>
    <SCRIPT type=text/vbscript>
    Function BinaryToArray(Binary)
    Dim i
    ReDim byteArray(LenB(Binary))
    For i = 1 To LenB(Binary)
    byteArray(i-1) = AscB(MidB(Binary, i, 1))
    concat2Bdy(AscB(MidB(Binary, i, 1)))
    Next
    BinaryToArray = byteArray
    End Function
    </SCRIPT>
    </head>
    <body>
    <input type="button" onclick="createAttachment();" value="Attach Report" />
    </body>
    </html>
    Thanks. and waiting for your valuable comments.
    - Mittal

    Hello,
    Yes, I was able to make my code working as below. Tested on CRM online 2013.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
    if (typeof (SDK) == "undefined")
    { SDK = { __namespace: true }; }
    SDK.JScriptRESTDataOperations = {
    _context: function () {
    if (typeof GetGlobalContext != "undefined")
    { return GetGlobalContext(); }
    else {
    if (typeof Xrm != "undefined") {
    return Xrm.Page.context;
    else { return new Error("Context is not available."); }
    _getServerUrl: function () {
    var serverUrl = this._context().getServerUrl()
    if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    return serverUrl;
    _ODataPath: function () {
    return this._getServerUrl() + "/XRMServices/2011/OrganizationData.svc/";
    _errorHandler: function (req) {
    return new Error("Error : " +
    req.status + ": " +
    req.statusText + ": " +
    JSON.parse(req.responseText).error.message.value);
    _dateReviver: function (key, value) {
    var a;
    if (typeof value === 'string') {
    a = /Date\(([-+]?\d+)\)/.exec(value);
    if (a) {
    return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
    return value;
    Create: function (object, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("POST", this._ODataPath() + type + "Set", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 201) {
    successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d);
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send(JSON.stringify(object));
    Retrieve: function (id, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("GET", this._ODataPath() + type + "Set(guid'" + id + "')", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 200) {
    successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d);
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send();
    Update: function (id, object, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("POST", this._ODataPath() + type + "Set(guid'" + id + "')", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("X-HTTP-Method", "MERGE");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 204 || this.status == 1223) {
    successCallback();
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send(JSON.stringify(object));
    Delete: function (id, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("POST", this._ODataPath() + type + "Set(guid'" + id + "')", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("X-HTTP-Method", "DELETE");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 204 || this.status == 1223) {
    successCallback();
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send();
    RetrieveMultiple: function (type, filter, successCallback, errorCallback) {
    if (filter != null) {
    filter = "?" + filter;
    else { filter = ""; }
    var req = new XMLHttpRequest();
    req.open("GET", this._ODataPath() + type + "Set" + filter, true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 200) {
    successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d.results);
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send();
    __namespace: true
    </script>
    <script type="text/javascript">
    //Create Email and link it with Order as Regarding field
    var Xrm;
    var email = new Object();
    var ownerID = "";
    var CustomerId = "";
    if (window.opener) { Xrm = window.opener.Xrm; }
    else if (window.parent) { Xrm = window.parent.Xrm; }
    //Get ownerid who send email of quotation to customer
    function GetOwnerID() {
    var owner = Xrm.Page.getAttribute("ownerid").getValue();
    ownerID = owner[0].id;
    var ownerName = owner[0].name;
    var entityType = owner[0].entityType;
    GetToEmailGUID();
    //Get customerid who receive email of quotation from owner
    function GetToEmailGUID() {
    var Customer = Xrm.Page.getAttribute('customerid').getValue();
    CustomerId = Customer[0].id;
    var CustomerName = Customer[0].name;
    var entityType = Customer[0].entityType;
    //if CustomerId is type of "Account" then get Primary Contact id of that account
    if (entityType == "account") {
    var contact = Xrm.Page.getAttribute("customerid").getValue();
    if (contact === null) return;
    var serverUrl = Xrm.Page.context.getClientUrl();
    var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/AccountSet(guid'" + contact[0].id + "')?$select=PrimaryContactId";
    var req = new XMLHttpRequest();
    req.open("GET", oDataSelect, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    req.onreadystatechange = function () {
    if (req.readyState === 4) {
    if (req.status === 200) {
    var retrieved = JSON.parse(req.responseText).d;
    CustomerId = retrieved.PrimaryContactId.Id;
    else {
    alert(this.statusText);
    req.send();
    function CreateEmail() {
    GetOwnerID();
    email.Subject = "Email with Report Attachment";
    //Set The current order as the Regarding object
    email.RegardingObjectId = {
    Id: Xrm.Page.data.entity.getId(), //Get the current entity Id , here OrderId
    LogicalName: Xrm.Page.data.entity.getEntityName()//Get the current entity name, here it will be “salesOrder”
    //Create Email Activity
    SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });
    // Email Call Back function
    function EmailCallBack(result) {
    email = result; // Set the email to result to use it later in email attachment for retrieving activity Id
    var activityPartyFrom = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyFrom.PartyId = {
    Id: CustomerId, //"79EBDD26-FDBE-E311-8986-D89D6765B238", // id of entity you want to associate this activity with.
    LogicalName: "contact"
    // Set the "activity" of the ActivityParty
    activityPartyFrom.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity).
    activityPartyFrom.ParticipationTypeMask = { Value: 2 }; // 2 means ToRecipients
    // Create the from ActivityParty for the email
    SDK.JScriptRESTDataOperations.Create(activityPartyFrom, "ActivityParty", ActivityPartyFromCallBack, function (error) { alert(error.message); });
    var activityPartyTo = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyTo.PartyId = {
    Id: ownerID, //"79EBDD26-FDBE-E311-8986-D89D6765B238", // id of entity you want to associate this activity with.
    LogicalName: "systemuser"
    // Set the "activity" of the ActivityParty
    activityPartyTo.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity).
    activityPartyTo.ParticipationTypeMask = { Value: 1 }; // 1 means Sender
    // Create the from ActivityParty
    SDK.JScriptRESTDataOperations.Create(activityPartyTo, "ActivityParty", ActivityPartyToCallBack, function (error) { alert(error.message); });
    //ActivityParty From Callback
    function ActivityPartyFromCallBack(result) {
    //ActivityParty To Callback
    function ActivityPartyToCallBack(result) {
    GetReportId('Quotation');
    //Create attachment for the created email
    function CreateEmailAttachment() {
    //get reporting session and use the params to convert a report in PDF
    var params = getReportingSession();
    //Email attachment parameters
    var activitymimeattachment = Object();
    activitymimeattachment.ObjectId = Object();
    activitymimeattachment.ObjectId.LogicalName = "email";
    activitymimeattachment.ObjectId.Id = email.ActivityId;
    activitymimeattachment.ObjectTypeCode = "email",
    activitymimeattachment.Subject = "File Attachment";
    activitymimeattachment.Body = encodePdf(params);
    activitymimeattachment.FileName = "Report.pdf";
    activitymimeattachment.MimeType = "application/pdf";
    //Attachment call
    SDK.JScriptRESTDataOperations.Create(activitymimeattachment, "ActivityMimeAttachment", ActivityMimeAttachmentCallBack, function (error) { alert(error.message); });
    //ActivityMimeAttachment CallBack function
    function ActivityMimeAttachmentCallBack(result) {
    var features = "location=no,menubar=no,status=no,toolbar=no,resizable=yes";
    var width = "800px";
    var height = "600px";
    window.open(Xrm.Page.context.getServerUrl() + "main.aspx?etc=" + 4202 + "&pagetype=entityrecord&id=" + email.ActivityId, "_blank", features);
    // To open window which works in outlook and IE both
    //openStdWin(Xrm.Page.context.getServerUrl() + "main.aspx?etc=" + 4202 + "&pagetype=entityrecord&id=" + email.ActivityId, "_blank", width, height, features);
    //This method will get the reportId based on a report name that will be used in getReportingSession() function
    function GetReportId(reportName) {
    var oDataSetName = "ReportSet";
    var columns = "ReportId";
    var filter = "Name eq '" + reportName + "'";
    retrieveMultiple(oDataSetName, columns, filter, onSuccess);
    function retrieveMultiple(odataSetName, select, filter, successCallback) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
    if (select) {
    odataUri += "$select=" + select + "&";
    if (filter) {
    odataUri += "$filter=" + filter;
    $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: odataUri,
    beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    success: function (data) {
    if (successCallback) {
    if (data && data.d && data.d.results) {
    successCallback(data.d.results);
    else if (data && data.d) {
    successCallback(data.d);
    else {
    successCallback(data);
    error: function (XmlHttpRequest, errorThrown) {
    if (XmlHttpRequest && XmlHttpRequest.responseText) {
    alert("Error while retrieval ; Error – " + XmlHttpRequest.responseText);
    function onSuccess(data) {
    reportId = data[0].ReportId.replace('{', ").replace('}', ");
    CreateEmailAttachment(); // Create Email Attachment
    //Gets the report contents
    function getReportingSession() {
    var pth = Xrm.Page.context.getServerUrl() + "/CRMReports/rsviewer/reportviewer.aspx";
    var retrieveEntityReq = new XMLHttpRequest();
    var Id = Xrm.Page.data.entity.getId();
    var quotationGUID = Id.replace('{', ""); //set this to selected quotation GUID
    quotationGUID = quotationGUID.replace('}', "");
    var reportName = "Quotation"; //set this to the report you are trying to download
    var reportID = "7C39D18F-1DC6-E311-8986-D89D6765B238"; //set this to the guid of the report you are trying to download
    var rptPathString = ""; //set this to the CRMF_Filtered parameter
    var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='quote'><all-attributes /><filter type='and'><condition attribute='quoteid' operator='eq' uitype='quote' value='" + quotationGUID + "' /> </filter></entity></fetch>";
    retrieveEntityReq.open("POST", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    rptPathString = "id=%7B" + reportID + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" +
    reportName + "&isScheduledReport=false&p:CRMAF_Filteredquote=" + strParameterXML;
    //remove the part starting from &p:salesorderid if your report has no parameters
    retrieveEntityReq.send(rptPathString);
    var x = retrieveEntityReq.responseText.indexOf("ReportSession=");
    var ret = new Array();
    ret[0] = retrieveEntityReq.responseText.substr(x + 14, retrieveEntityReq.responseText.indexOf("&", x) - x - 14); //the session id
    x = retrieveEntityReq.responseText.indexOf("ControlID=");
    ret[1] = retrieveEntityReq.responseText.substr(x + 10, retrieveEntityReq.responseText.indexOf("&", x) - x - 10); //the control id
    return ret;
    var bdy = new Array();
    var bdyLen = 0;
    function concat2Bdy(x) {
    bdy[bdyLen] = x;
    bdyLen++;
    function encodePdf(params) {
    bdy = new Array();
    bdyLen = 0;
    var retrieveEntityReq = new XMLHttpRequest();
    var pth = Xrm.Page.context.getServerUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] +
    "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] +
    "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
    retrieveEntityReq.open("GET", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.send();
    BinaryToArray(retrieveEntityReq.responseBody);
    return encode64(bdy);
    var StringMaker = function () {
    this.parts = [];
    this.length = 0;
    this.append = function (s) {
    this.parts.push(s);
    this.length += s.length;
    this.prepend = function (s) {
    this.parts.unshift(s);
    this.length += s.length;
    this.toString = function () {
    return this.parts.join('');
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    function encode64(input) {
    var output = new StringMaker();
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    while (i < input.length) {
    chr1 = input[i++];
    chr2 = input[i++];
    chr3 = input[i++];
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
    enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
    enc4 = 64;
    output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
    return output.toString();
    </script>
    <script type="text/vbscript">
    Function BinaryToArray(Binary)
    Dim i
    ReDim byteArray(LenB(Binary))
    For i = 1 To LenB(Binary)
    byteArray(i-1) = AscB(MidB(Binary, i, 1))
    concat2Bdy(AscB(MidB(Binary, i, 1)))
    Next
    BinaryToArray = byteArray
    End Function
    </script>
    </head>
    <body>
    <input type="button" onclick="CreateEmail();" value="Attach Report" />
    </body>
    </html>
    Thank you,
    Mittal.

  • Sending Invoice as PDF in email

    Hello,
    I have a requirement where I have to send Proforma Invoice as PDF in email.
    Now, the Proforma Invoice is already using output type to Print and when I see the routines in Tcode NACE
    It uses RVADAUS1 Program where it calls RV_EXPORT_DOCUMENT_PRINT function module to generate the Print document.
    This works fine.
    So, I created a new output type, copied the  RVADAUS1 to ZRVADAUS1 and modified the code where I am capturing the Spool generated through the original code and pass it to CONVERT_ABAPSPOOLJOB_2_PDF to convert it to PDF and then send it as an email.
    Now, the problem I am facing is that, I am not able to generate a Spool when I am using the medium ( '5' External Send ). So the further code of capturing Spool and convert to PDF and send as email fails.
    Any guidance is appreciated.
    Regards,
    DNP

    Hi Sudhanshu,
    Just before calling the function module RV_EXPORT_DOCUMENT_PRINT.
    I forced TNAPR-NACHA = '1'. and NAST-NACHA = '1'.
    which means I forced Transmission medium as 1(Print) instead of 5(External Send)
    This created a SPOOL.
    Regards,
    DNP
    Edited by: DNP on Aug 14, 2009 11:45 AM

  • Unable to attach PDF to email (Outlook for Mac 2011)

    We are pushing out software upgrades for CS5 and MS Office 2011 for Mac. We've discoverd that we can't use the Attach to email feature in Acrobat. The spinning rainbow wheel pops up for about a minute, and then Acrobat is non-responsive and we have to force quit. We can still drag and drop an attachment so we have a viable workaround but obviously we'd like to be able to use the automated feature.
    All software is up-to-date.
    In the preferences panel of Outlook, we have selected Outlook to be the default mail application.
    As a sidenote, this feature doesn't work with Acobat X beta either. However, in the beta version of Acrobat X, if we declare Apple's mail application to be the default, it works fine. Unfortunately we use the Office suite as part of our enterprise system, so that's what we need to work with.
    Has anyone else experienced this? I've logged a ticket with Adobe but I haven't heard back from them yet.
    Thanks for any advise.

    Take the bhama way
    figured out how to make it work.  I am using Adobe Acrobat X Pro (mac)
    and MS Outlook for Mac 2011.
    For those who are interested, this is what I did:
    1. Create a folder on desktop to save your pdf¹s files you want to email
    to.  Mine is named, "PDF to Email"
    2. Open Automator, create a "Folder Action"
    3. At the top, "Choose Folder", choose your newly created folder on the
    desktop
    4. Choose the "Rename Finder Items" action from the action list.  I chose,
    "Don¹t Add" on the add a Copy Finder Items Action menu.
    5. On the "Add Date or Time to Finder Item Names" I chose, "Name Single
    Item" from the first drop down menu.
    6. Click on "Options" at the bottom of that window to select the "Show
    this action when the workflow runs" so you can rename your         file
    something other than the Acrobat default.
    7. Choose the "Create New Outlook Mail Message" from the action list and
    add it below the "Name Single Item in Finder Item Names"
    8. Choose "File>Save As" and give your file a name.  Mine is, "PDF to
    Email".
    9. Close Automator
    10. Open Acrobat X Pro.
    11. Go to "File>Action Wizard>Create New Action"
    12. Here you choose, "Save to>A Folder on my computer"
    13. Choose the folder on the desktop that we saved earlier
    14. Save the file, with the action name you will remember.
    Now when you are in Acrobat X Pro and you want to send that .pdf file via
    Outlook for Mac 2011, follow the steps below.
    With the file you want to email open, go to "File>Action Wizard>(Action
    you created) Mine is "PDF to Email".  It will take a few seconds, but you
    will get an "Action Completed".  You will get a pop up that allows you to
    name/rename the file. Then it should open your Outlook with your .pdf
    attached and ready for sending.
    You might need to tweak the actions to suit your needs, but this should
    work for you.
    De:  DaveGrif <[email protected]>
    Responder a:  <[email protected]>
    Fecha:  Mon, 05 Dec 2011 15:56:02 -0700
    Para:  Eugenio Soberon <[email protected]>
    Asunto:  unable to attach PDF to email (Outlook for Mac
    2011)
    Re: unable to attach PDF to email (Outlook for Mac 2011)
    created by DaveGrif <http://forums.adobe.com/people/DaveGrif>  in Acrobat
    Macintosh - View the full discussion
    <http://forums.adobe.com/message/4065409#4065409>
    It's supposed to work now? I've made sure I'm on latest (check for update)
    and it says I am. Still get an error. It does bring Outlook to the
    forground, but same error when I hide Outlook - An error occurred while
    trying to create a mail document. Suggestions?
    Replies to this message go to everyone subscribed to this thread, not
    directly to the person who posted the message. To post a reply, either reply
    to this email or visit the message page:
    http://forums.adobe.com/message/4065409#4065409 To unsubscribe from this
    thread, please visit the message page at
    http://forums.adobe.com/message/4065409#4065409. In the Actions box on the
    right, click the Stop Email Notifications link. Start a new discussion in
    Acrobat Macintosh by email
    <mailto:[email protected].co
    m>  or at Adobe Forums
    <http://forums.adobe.com/choose-container!input.jspa?contentType=1&container
    Type=14&container=3399>  For more information about maintaining your forum
    email notifications please go to
    http://forums.adobe.com/message/2936746#2936746.

  • Unable to send PDFs as email attachments

    I have become unable to send PDFs as email attachments when using Firefox.
    Depending on the PDF, I either get the message “There was an error opening this document. The file is damaged and could not be repaired.” or it opens as a blank document. This occus when opening the file with both Adobe Reader and Acrobat Pro. The problem seems to be isolated to PDFs. (I am able to send Word files. If a PDF is zipped before attaching, it can be opened without problem.) This occurs on both an institutional email account and personal (Yahoo) email account. This problem is isolated to Firefox (does not happen in Chrome).
    I have reset Firefox to default settings, as well as reinstalling.
    Thank you.

    Update Adobe® Acrobat® Plug-in for Web Browsers, Version 10.1.13 to version 11.
    Also please update all of your plugins and try again.
    Does this happen when you open the pdf in pdf.js, it is possible to change the default viewer by:
    * [[How to disable the built-in PDF viewer and use another viewer]]

  • Sharing PDF via email in Pages 09

    This has not been a problem. However I just upgraded to Yosemite and now I cannot share as PDF via email; no problem with word or pages but this function seems to be lost

    Since Apple has retired all Pages applications prior to v5, they have no concern about backwards compatibility, or the effect of new operating systems, or newer applications on those retired applications. There is no guarantee that any point release to Yosemite, or subsequent OS X release would enable Pages ’09 functional continuity. It simply is not an Apple agenda item.
    For those who remain attached to Pages ’09, and do not have their documents duplicated in MS Word documents — and backed up — a sudden failure of Pages ’09 would mean opening those Pages ’09 documents in Pages v5, and risk loss of content due to unsupported features.

  • Send pdf as email

    hai gurus ,
    my problem is i am sending pdf as email its working fine
    but when i go and check the pdf file in  scot transaction the file is not getting  opened
    plz help me
    thanks in advance
    anji.
    Moderator message: please search for available information/documentation before asking, provide more technical details about errors when posting again.
    Edited by: Thomas Zloch on Oct 28, 2010 10:58 AM

    Hi,
    Check this link [http://wiki.sdn.sap.com/wiki/display/Snippets/ConvertsspoolrequestintoPDFdocumentand+emails]
    BR,
    Lokeswari.
    Moderator message: please do not post just links without any further explanations.
    Edited by: Thomas Zloch on Oct 28, 2010 10:58 AM

  • How to batch PDF multiple emails already saved to system

    Hi everyone,
    I would be very grateful for advice as to whether there is a way to PDF multiple saved emails at once using Abode? I have seen that it is possible to create multiple PDFs at once of emails in Outlook - but is there a way of batch creating multiple PDFs from emails which have already been saved to the system as 'Outlook Items'?
    Whilst I know how to batch PDF Word documents etc, this doesn't seem to be an option in Adobe (we use Adobe XI) for emails. Likewise, if I simply highlight all the emails and right-click 'Convert to Adobe PDF', this replaces the name of each email as 'Memo Style' (whereas it works for Word documents).
    We have many hundreds/thousands of emails saved on our work system as 'Outlook Items' (done before we upgraded systems and were able to save emails directly as PDFs from Outlook), and we need to convert them to PDF for upload to a new database programme, so it would be very helpful indeed if there were a way of avoiding having to convert them all one by one...
    Many thanks in advance,
    Zara

    What programming method are you using with the Acrobat SDK?

  • How do I save PDF from email to iBooks

    How do I save PDF from email to iBooks like I do on iPhone.

    touch and hold the attachment in mail.  a box will open that says 'open in' and i books, along with any other apps you have that read pdf files will be offered.  select i books, or the one you want.  once it is associated with an app, it will be stored within the app.

  • Goodreader will allow me to send a PDF via email but my notes wont go?

    I do apologize as I am very new to this. I did just download goodreader onto my iPad 2. It is very simple to use but I do have an issue. I was forwarding a PDF via email. I attached a note along with it, just above my signature. The email did go to a PC and the attachment was their, but the note and signature was attached as another attachment as a .txt file. The odd thing is, if I copy the email to myself it shows the note and signature? I hope i explained this situation so that it is understandable and thanks for any advise. Really am a big fan of the Apple products, even have a new iPhone 4 being delivered tomorrow.
    G

    Yes, but selecting the icon only gives me the option to print.

  • Sending PDF thru email with password protection in our SAP system

    Need solution for sending PDF thru email with password protection in our SAP ecc 6

    Or maybe you have found any other way? You can check here:
    Password protect PDF file:
    Re: Password protected PDF file 
    pdf with password encryption
    Regards Otto

  • Received a pdf by email, when i attempt to open it, I get the message "File Error-couldn't open the file", is there some way I can open it? Thanks, Graham

    Hi,
    Received a pdf by email. When I attempt to open it, I receive the message, "File Error- Couldn't open the file", is there any way I can open it?
    Thanks,
    Graham

    Are you using Adobe Reader or Preview to view the file? Can you get the sender to resend the file?
     Cheers, Tom

  • Error send a smartform PDF by Email to Vendor

    Hi Expert,
    Please help me.........................
    I want to send a PO (Smartform) as Email to Vendor.
    In SAPScript the PO send by Email is working fine, but in Smartforms it is not working.
    Normally, I will use via Smartforms the Program = YBAA_FM06P, FORM routine = ENTRY_NEU, PDF/Smartform Form = ZYBAA_MMPO1.
    A communication strategy has communication type as INT has been defined.
    This communication strategy has been set as default in the output type ZNEU. The transmission medium has been set to 5 (External Send) and the partner function as VN (Vendor).
    The e-mail address of the vendor has also been maintained.
    In transaction MN04, i have also made an entry for output type ZNEU and set the document type as NB.
    But message output do not create.
    How to send a smartform PDF by Email to vendor?
    Thanks,

    Hi,
    I can convert the PO output in to PDF from SOST I can sent it to external vendor using the Mail triggering configuration settings but meassage output do not create.
    Please tell me how can I do.
    Thank,

Maybe you are looking for

  • Connect Add-in Big Problem

    Hi everybody, I am trying the acrobat connect product. Some days ago I installed the acrobat connect add-in to share my screen and everything where ok. From today for some reasons (I don not why) I can not share my screen because acrobat connect plat

  • OfficeJet 8600 Pro Premium scan does not work since upgrading Mac to 10.10.1 (Yosemite)

    Since updating my MacBook Pro to Yosemite, I cannot get the scan to computer function to work. I have downloaded the softwear again & reinstalled; reset the printer, repaired disk permissions, etc. to no avail. Also i note that the HP utility icon no

  • Saving a delivery, does not create spool request

    Hi, I have a delivery and 2 output types. The print program of first output type already exists and I created one for the second one. When I save the delivery, spool request gets created for the first output type but doesn for the one I created. Can

  • I have a problem with my old macintosh lc ii

    I have an old macintosh LC II that I bought from a garage sale and whenever I try to use it, it turns on then shows and icon of a floppy disk with a question mark. I think I have downloaded the right thing to my floppy disk, but the person who told m

  • Time for Java

    Hey, I've been developing a Timing and Synchronisation package, I've just discovered that System.currentTimeMillis() is too inaccurate, so i've implemented something using jni and the windows libraries. On desktop machines it works perfect but on a D