Custom sapscript to PDF and email

Hi all,
I have a requirement to create a new sapscript that can be converted to PDF and emailed. I have done this for regular reports but have no idea about doing it for sapscript.
Does anybody know how I can do this?
I've search the forums here but I haven't found a definate solution.
Cheers,
      Tony

Here is a sample program.
REPORT ZRICH_0003.
DATA: ITCPO LIKE ITCPO,
      TAB_LINES LIKE SY-TABIX.
* Variables for EMAIL functionality
DATA: MAILDATA   LIKE SODOCCHGI1.
DATA: MAILPACK   LIKE SOPCKLSTI1 OCCURS 2 WITH HEADER LINE.
DATA: MAILHEAD   LIKE SOLISTI1 OCCURS 1 WITH HEADER LINE.
DATA: MAILBIN    LIKE SOLISTI1 OCCURS 10 WITH HEADER LINE.
DATA: MAILTXT    LIKE SOLISTI1 OCCURS 10 WITH HEADER LINE.
DATA: MAILREC    LIKE SOMLREC90 OCCURS 0  WITH HEADER LINE.
DATA: SOLISTI1   LIKE SOLISTI1 OCCURS 0 WITH HEADER LINE.
PERFORM SEND_FORM_VIA_EMAIL.
*       FORM  SEND_FORM_VIA_EMAIL                                      *
FORM  SEND_FORM_VIA_EMAIL.
  CLEAR:    MAILDATA, MAILTXT, MAILBIN, MAILPACK, MAILHEAD, MAILREC.
  REFRESH:  MAILTXT, MAILBIN, MAILPACK, MAILHEAD, MAILREC.
* Creation of the document to be sent File Name
  MAILDATA-OBJ_NAME = 'TEST'.
* Mail Subject
  MAILDATA-OBJ_DESCR = 'Subject'.
* Mail Contents
  MAILTXT-LINE = 'Here is your file'.
  APPEND MAILTXT.
* Prepare Packing List
  PERFORM PREPARE_PACKING_LIST.
* Set recipient - email address here!!!
  MAILREC-RECEIVER = '[email protected]'.
  MAILREC-REC_TYPE  = 'U'.
  APPEND MAILREC.
* Sending the document
  CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
       EXPORTING
            DOCUMENT_DATA              = MAILDATA
            PUT_IN_OUTBOX              = ' '
       TABLES
            PACKING_LIST               = MAILPACK
            OBJECT_HEADER              = MAILHEAD
            CONTENTS_BIN               = MAILBIN
            CONTENTS_TXT               = MAILTXT
            RECEIVERS                  = MAILREC
       EXCEPTIONS
            TOO_MANY_RECEIVERS         = 1
            DOCUMENT_NOT_SENT          = 2
            OPERATION_NO_AUTHORIZATION = 4
            OTHERS                     = 99.
ENDFORM.
*      Form  PREPARE_PACKING_LIST
FORM PREPARE_PACKING_LIST.
  CLEAR:    MAILPACK, MAILBIN, MAILHEAD.
  REFRESH:  MAILPACK, MAILBIN, MAILHEAD.
  DESCRIBE TABLE MAILTXT LINES TAB_LINES.
  READ TABLE MAILTXT INDEX TAB_LINES.
  MAILDATA-DOC_SIZE = ( TAB_LINES - 1 ) * 255 + STRLEN( MAILTXT ).
* Creation of the entry for the compressed document
  CLEAR MAILPACK-TRANSF_BIN.
  MAILPACK-HEAD_START = 1.
  MAILPACK-HEAD_NUM = 0.
  MAILPACK-BODY_START = 1.
  MAILPACK-BODY_NUM = TAB_LINES.
  MAILPACK-DOC_TYPE = 'RAW'.
  APPEND MAILPACK.
* Creation of the document attachment
* This form gets the OTF code from the SAPscript form.
* If you already have your OTF code, I believe that you may
* be able to skip this form.  just do the following code, looping thru
* your SOLISTI1 and updating MAILBIN.
<b>  PERFORM GET_OTF_CODE.
  LOOP AT SOLISTI1.
    MOVE-CORRESPONDING SOLISTI1 TO MAILBIN.
    APPEND MAILBIN.
  ENDLOOP.</b>
  DESCRIBE TABLE MAILBIN LINES TAB_LINES.
  MAILHEAD = 'TEST.OTF'.
  APPEND MAILHEAD.
** Creation of the entry for the compressed attachment
  MAILPACK-TRANSF_BIN = 'X'.
  MAILPACK-HEAD_START = 1.
  MAILPACK-HEAD_NUM = 1.
  MAILPACK-BODY_START = 1.
  MAILPACK-BODY_NUM = TAB_LINES.
  MAILPACK-DOC_TYPE = 'OTF'.
  MAILPACK-OBJ_NAME = 'TEST'.
  MAILPACK-OBJ_DESCR = 'Subject'.
  MAILPACK-DOC_SIZE = TAB_LINES * 255.
  APPEND MAILPACK.
ENDFORM.
*      Form  GET_OTF_CODE
FORM  GET_OTF_CODE.
  DATA: BEGIN OF OTF OCCURS 0.
          INCLUDE STRUCTURE ITCOO .
  DATA: END OF OTF.
  DATA: ITCPO LIKE ITCPO.
  DATA: ITCPP LIKE ITCPP.
<b>  CLEAR ITCPO.
  ITCPO-TDGETOTF = 'X'.</b>
* Start writing OTF code
  CALL FUNCTION 'OPEN_FORM'
       EXPORTING
            FORM     = 'ZTEST_FORM'
            LANGUAGE = SY-LANGU
            OPTIONS  = ITCPO
            DIALOG   = ' '
       EXCEPTIONS
            OTHERS   = 1.
  CALL FUNCTION 'START_FORM'
       EXCEPTIONS
            ERROR_MESSAGE = 01
            OTHERS        = 02.
  CALL FUNCTION 'WRITE_FORM'
       EXPORTING
            WINDOW        = 'MAIN'
       EXCEPTIONS
            ERROR_MESSAGE = 01
            OTHERS        = 02.
* Close up Form and get OTF code
  CALL FUNCTION 'END_FORM'
       EXCEPTIONS
            ERROR_MESSAGE = 01
            OTHERS        = 02.
  MOVE-CORRESPONDING ITCPO TO ITCPP.
  CALL FUNCTION 'CLOSE_FORM'
       IMPORTING
            RESULT  = ITCPP
<b>       TABLES
            OTFDATA = OTF</b>
       EXCEPTIONS
            OTHERS  = 1.
* Move OTF code to structure SOLI form email
<b>  CLEAR SOLISTI1. REFRESH SOLISTI1.
  LOOP AT OTF.
    SOLISTI1-LINE = OTF.
    APPEND SOLISTI1.
  ENDLOOP.</b>
ENDFORM.
Please make sure to award points for helpful answers and Welcome to SDN!!!
Regards,
Rich Heilman

Similar Messages

  • 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.

  • My form was created by FormsCentral.  I save as a PDF and emailed it to all of my club members.  When they complete the form, save it, and email it back to me, I get a blank form. Why?

    My form was created by FormsCentral.  I save as a PDF and emailed it to all of my club members.  When they complete the form, save it, and email it back to me, I get a blank form. Why?

    If you had iCloud backup turned on, and it made a backup - yes.  If you didn't have iCloud backup turned on - but were using iCloud for Contacts, calendars, etc.  You will get the contacts and calendars, etc back.
    Purchases made with your appleID can be redownloaded as long as they are still available in the iTunes store.
    If you connected your phone to a computer with iTunes, there may be a backup on there as well.

  • Convert to PDF and Email crashes

    Hi,
    Encountered this problem when I right click on a word file and select "Convert to PDF and Email". It will always crashes with the error "Adobe Elements had stopped working" and the message indicating something to do with ADIST.DLL.
    Had tried the followings but still the error persists.
    1. Uninstall/reinstall Acrobat Pro XI. Had deleted anything related to "Adobe" including Flash player and still no avail.
    2. Update the version to 11.0.07 and still the error is there.
    3. Only happens when converting Word 2010 documents. Excel, Outlook and others are fine.
    4. Valid licensed product from Adobe
    5. Tried renaming the "Adobe Elements" folder and does not work at all.
    6. Tried registering ADIST.DLL but encountered error.
    I am running on a Win 7 Pro 64 bit PC and due to this error, when i try using mail merge with a word doc, it also crashes. Anyone can assist on this? Many thanks in advance!
    Tan

    Crashes with distiller are pretty rare. Fonts can cause distiller to crash. A bad graphic in a file can cause distiller to crash. Maybe a corrupt job options file. Create a simple text file (one page), no graphics. Use the Times New Roman font. Print to Adobe PDF instance. Does the error still happen?

  • Logo not printing properly in Invoice converted to PDF and emailed

    Hello,
    I am having a problem with a programming issue and have searched lots of forums but have found no solutions.  We are on 4.7 and are not likely to upgrade any time soon.  Therefore, I don't think any of the newer solutions are gonna work for me.  I believe that I'm stuck using a couple of function modules to get t he job done.  I am attempting to modify our Invoice Print program (uses SAPscript, not SmartForms) to have the output converted into a PDF file and then attached to an email that is then sent to the customer.  Everything is working fine except for the company logo.  It has been uploaded via SE78.  It is a 24-bit bitmap file.  I have played around with the DPI to have it appear correctly on the form.  I added a FM GUI_DOWNLOAD step to verify that it is saved to my hard drive correctly.  The PDF file saved t o my hard drive appears normally in Adobe Acrobat and Adobe Reader.  So the problem occurs sometime after that.  I have a routine wherein I convert is from 132 to 255 bytes.  I then use FM SO_DOCUMENT_SEND_API1 to send it.  When I swap the customer's email address to my own personal external emal address, the resultant email has an attached PDF file but the company logo is garbage. The top portion of the logo looks good and then at some point in the lower portion is appears as squiggly lines.  This is not acceptable, of course.  I have included the relevent code below:
    DATA: ITAB_OTFDATA   TYPE TABLE OF ITCOO WITH HEADER LINE.
    DATA: ITAB_PDFDATA   TYPE TABLE OF TLINE WITH HEADER LINE.
    DATA: ITAB_DOCTAB_ARCHIVE TYPE STANDARD TABLE OF DOCS.
    DATA: ITAB_OBJPACK   LIKE SOPCKLSTI1 OCCURS 0 WITH HEADER LINE.
    DATA: ITAB_RECORD    LIKE SOLISTI1   OCCURS 0 WITH HEADER LINE.
    DATA: ITAB_OBJTXT    LIKE SOLISTI1   OCCURS 0 WITH HEADER LINE.
    DATA: ITAB_OBJBIN    LIKE SOLISTI1   OCCURS 0 WITH HEADER LINE.
    DATA: ITAB_RECLIST   LIKE SOMLRECI1  OCCURS 0 WITH HEADER LINE.
    DATA: BINFILESIZE    TYPE I,
          G_LINES_TXT    TYPE I,
          G_LINES_BIN    TYPE I,
          DOCDATA        TYPE SODOCCHGI1,
          WA_RESULT      TYPE ITCPP,
          WA_BUFFER      TYPE STRING,
          WA_OBJHEAD     TYPE SOLI_TAB,
          G_INVOICE(10)  TYPE C.
    CLEAR: BINFILESIZE.
      CALL FUNCTION 'CONVERT_OTF_2_PDF'
        EXPORTING
          USE_OTF_MC_CMD               = 'X'
    *     ARCHIVE_INDEX                =
        IMPORTING
          BIN_FILESIZE                 = BINFILESIZE
        TABLES
          OTF                          = ITAB_OTFDATA
          DOCTAB_ARCHIVE               = ITAB_DOCTAB_ARCHIVE
          LINES                        = ITAB_PDFDATA
        EXCEPTIONS
          ERR_CONV_NOT_POSSIBLE        = 1
          ERR_OTF_MC_NOENDMARKER       = 2
          OTHERS                       = 3
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION 'GUI_DOWNLOAD'
        EXPORTING
          filename                        = 'C:\TEMP\TEST.PDF'
          FILETYPE                        = 'BIN'
        tables
          data_tab                        = ITAB_PDFDATA.
      IF sy-subrc <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    *-- Convert PDF from 132 to 255
      LOOP AT ITAB_PDFDATA.
    *   Replacing space by ~
        TRANSLATE ITAB_PDFDATA USING ' ~'.
        CONCATENATE WA_BUFFER ITAB_PDFDATA INTO WA_BUFFER.
      ENDLOOP.
    * Replacing ~ by space
      TRANSLATE WA_BUFFER USING '~ '.
      DO.
        ITAB_RECORD = WA_BUFFER.
    *   Appending 155 characters as a record
        APPEND ITAB_RECORD.
        SHIFT WA_BUFFER LEFT BY 255 PLACES.
        IF WA_BUFFER IS INITIAL.
          EXIT.
        ENDIF.
      ENDDO.
      REFRESH: ITAB_RECLIST,
               ITAB_OBJTXT,
               ITAB_OBJBIN,
               ITAB_OBJPACK.
      CLEAR: WA_OBJHEAD.
      ITAB_OBJBIN[] = ITAB_RECORD[].
      G_INVOICE = VBRK-VBELN.
      SHIFT G_INVOICE LEFT DELETING LEADING '0'.
    *-- Create Message Body Title and Document
      CLEAR: ITAB_OBJTXT-LINE.
      CONCATENATE 'Invoice'
                 G_INVOICE
                  'for Purchase Order'
                  PO_NUM
                  'is attached to this email.'
          INTO ITAB_OBJTXT-LINE SEPARATED BY SPACE.
      APPEND ITAB_OBJTXT.
      CLEAR: ITAB_OBJTXT-LINE.
      APPEND ITAB_OBJTXT.
      CLEAR: ITAB_OBJTXT-LINE.
      CONCATENATE 'Please see attached invoice.'
                  'Thank you for your business!'
          INTO ITAB_OBJTXT-LINE SEPARATED BY SPACE.
      APPEND ITAB_OBJTXT.
      DESCRIBE TABLE ITAB_OBJTXT LINES G_LINES_TXT.
      READ TABLE ITAB_OBJTXT INDEX G_LINES_TXT.
      CONCATENATE 'Invoice' G_INVOICE
          INTO DOCDATA-OBJ_NAME SEPARATED BY SPACE.
      DOCDATA-EXPIRY_DAT = SY-DATUM + 10.
      CONCATENATE 'Invoice for P.O.'
                   PO_NUM
                   VBDKR-NAME1_WE
          INTO DOCDATA-OBJ_DESCR SEPARATED BY SPACE.
      DOCDATA-SENSITIVTY = 'F'.
      DOCDATA-DOC_SIZE = ( G_LINES_TXT - 1 ) * 255 + STRLEN( ITAB_OBJTXT ).
    *-- Main Text
      CLEAR: ITAB_OBJPACK-TRANSF_BIN.
      ITAB_OBJPACK-HEAD_START = 1.
      ITAB_OBJPACK-HEAD_NUM = 0.
      ITAB_OBJPACK-BODY_START = 1.
      ITAB_OBJPACK-BODY_NUM = G_LINES_TXT.
      ITAB_OBJPACK-DOC_TYPE = 'RAW'.
      APPEND ITAB_OBJPACK.
    *-- Attachment (pdf-Attachment)
      ITAB_OBJPACK-TRANSF_BIN = 'X'.
      ITAB_OBJPACK-HEAD_START = 1.
      ITAB_OBJPACK-HEAD_NUM = 0.
      ITAB_OBJPACK-BODY_START = 1.
      DESCRIBE TABLE ITAB_OBJBIN LINES G_LINES_BIN.
      READ TABLE ITAB_OBJBIN INDEX G_LINES_BIN.
      ITAB_OBJPACK-DOC_SIZE = ( G_LINES_BIN - 1 ) * 255 + STRLEN( ITAB_OBJBIN ).
      ITAB_OBJPACK-BODY_NUM = G_LINES_BIN.
      ITAB_OBJPACK-DOC_TYPE = 'PDF'.
      CONCATENATE 'Invoice' G_INVOICE
          INTO ITAB_OBJPACK-OBJ_NAME SEPARATED BY SPACE.
      CONCATENATE G_INVOICE '.pdf'
          INTO ITAB_OBJPACK-OBJ_DESCR.
      APPEND ITAB_OBJPACK.
    *-- Create Table of email recipients
      CLEAR ITAB_RECLIST.
      ITAB_RECLIST-RECEIVER = KNB1-INTAD.
      ITAB_RECLIST-REC_TYPE = 'U'.
      ITAB_RECLIST-COM_TYPE = 'INT'.
      APPEND ITAB_RECLIST.
      CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
        EXPORTING
          DOCUMENT_DATA                    = DOCDATA
          PUT_IN_OUTBOX                    = ' '
          SENDER_ADDRESS                   = 'arcredit @ companyname.com'  <-- modified to comply with forum rules
          SENDER_ADDRESS_TYPE              = 'SMTP'
          COMMIT_WORK                      = 'X'
    *   IMPORTING
    *     SENT_TO_ALL                      =
    *     NEW_OBJECT_ID                    =
    *     SENDER_ID                        =
        TABLES
          PACKING_LIST                     = ITAB_OBJPACK
          OBJECT_HEADER                    = WA_OBJHEAD
          CONTENTS_BIN                     = ITAB_OBJBIN
          CONTENTS_TXT                     = ITAB_OBJTXT
    *     CONTENTS_HEX                     =
    *     OBJECT_PARA                      =
    *     OBJECT_PARB                      =
          RECEIVERS                        = ITAB_RECLIST
        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.
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    *-- Send the email immediately
      WAIT UP TO 3 SECONDS.
      SUBMIT RSCONN01 WITH MODE = 'INT'
                      WITH OUTPUT = 'X'
                      AND RETURN.
    Thanks in advance for any and all advice.
    Best Regards,
    Nik von Ruden
    Edited by: Nik Von Ruden on Nov 3, 2009 6:48 PM
    Edited by: Nik Von Ruden on Nov 3, 2009 6:49 PM

    Hi Friend ,
    I hav gone through your code ...  I have one Question why you are  changing from 132 to 255.inside your program
    if there is a purpose then , please can you change your company logo Image size accordingly  and uploaded it into SAP mime repository using se78.then your program let it convert from 132 to 255. definely you will see some change's in the Logo,then keep on adjusting you can acheive you result.
    sometime the Image size also plays major role ,which we need to modify the sizes of image.
    I am giving you an link which is already there  but still from myside  , just compare the code  .
    Link: [http://www.scribd.com/doc/454814/SAPSCRIPT-to-PDF]
    Regards,

  • ZERS - Invoice as PDF and Email

    Hello,
    We have created a new Output Type ZERS copied from ERS. And created a new SAPScript ZERS_PRINT which is agained copied from MR_PRINT and Print Program ZMR_PRINT. Whenever MRRL is run, it's creating the invoice output Spool. Now, the users want to covert the Spool to PDF and then email. Can anybody please let me know if you have done that similar functionality or how can I do this?
    Where in the Print Program I can write my custom code?
    Thanks a lot for the help.

    Thanks Karthik,
    Like I mentioned, we have copied the standard print program into a Z-print program. And in FM "MRM_ENTRY_ERS", I do see FM "OPEN_FORM". And in the parameter structure "ITCPO" we have option for "TDGETOTF". My question is  how to set this flag?
    Do I need to go in Change mode for FM "MRM_ENTRY_ERS"? Please let me know.
    Or Should I copy this FM into a Z- FM? Can anybody please let me know.
    Thanks a lot for the help.
    Edited by: lope jie on Apr 30, 2010 8:30 PM

  • Convert SAPSCRIPT to PDF and send to FAX

    Hi All,
    Currently i am having customized sapscript.
    1.) I have to convert it to PDF. How to convert to PDF.
    2.) Then i need to send PDF to FAX. How.
    What are the code required to change and add.
    What is OTF output, which is easier to fax. PDF or OTF output.
    With Regards,
    Vinoth

    Hi Code,
    Refer this sample code.
    DATA: t_otf LIKE itcoo OCCURS 100 WITH HEADER LINE,
          t_pdf LIKE tline OCCURS 100 WITH HEADER LINE,
          t_opt like itcpo occurs 0 with header line.  
    data:
       w_flag     type i,                   " Temporary flag
      w_control  type ssfctrlop,           " Control parameters
      w_output   type ssfcompop,           " Output options
      w_return   type ssfcrescl,           " Job output info
      w_filesize type sood-objlen,         " Bin file size
      w_string   type string,              " To convert from 132 to 255
      w_msg      type i,                   " Message length
      w_docdata  type sodocchgi1,          " Document data
      w_objbin   type i,                   " Contents bin
      w_sender   type soextreci1-receiver. " Sender
    t_opt-TDGETOTF = 'X'.
    append t_opt.
    CALL FUNCTION 'OPEN_FORM'
    EXPORTING
       APPLICATION                       = 'TX'
       FORM                              = 'ZTEST_SCRIPT1'
       LANGUAGE                          = SY-LANGU
       OPTIONS                           = t_opt 
    EXCEPTIONS
       CANCELED                          = 1
       DEVICE                            = 2
       FORM                              = 3
       OPTIONS                           = 4
       UNCLOSED                          = 5
       MAIL_OPTIONS                      = 6
       ARCHIVE_ERROR                     = 7
       INVALID_FAX_NUMBER                = 8
       MORE_PARAMS_NEEDED_IN_BATCH       = 9
       SPOOL_ERROR                       = 10
       CODEPAGE                          = 11
       OTHERS                            = 12
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    CALL FUNCTION 'WRITE_FORM'
    EXPORTING
       ELEMENT                        = 'TEXT'
       FUNCTION                       = 'SET'
       TYPE                           = 'BODY'
       WINDOW                         = 'HEADER'
    * IMPORTING
    *   PENDING_LINES                  =
    * EXCEPTIONS
    *   ELEMENT                        = 1
    *   FUNCTION                       = 2
    *   TYPE                           = 3
    *   UNOPENED                       = 4
    *   UNSTARTED                      = 5
    *   WINDOW                         = 6
    *   BAD_PAGEFORMAT_FOR_PRINT       = 7
    *   SPOOL_ERROR                    = 8
    *   CODEPAGE                       = 9
    *   OTHERS                         = 10
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    CALL FUNCTION 'CLOSE_FORM'
    * IMPORTING
    *   RESULT                         =
    *   RDI_RESULT                     =
    TABLES
       OTFDATA                        = t_otf
    EXCEPTIONS
       UNOPENED                       = 1
       BAD_PAGEFORMAT_FOR_PRINT       = 2
       SEND_ERROR                     = 3
       SPOOL_ERROR                    = 4
       CODEPAGE                       = 5
       OTHERS                         = 6
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    CALL FUNCTION 'CONVERT_OTF'
    EXPORTING
       format                      = 'PDF'
    *   MAX_LINEWIDTH               = 132
    *   ARCHIVE_INDEX               = ' '
    *   COPYNUMBER                  = 0
    *   ASCII_BIDI_VIS2LOG          = ' '
    *   PDF_DELETE_OTFTAB           = ' '
    * IMPORTING
    *   BIN_FILESIZE                =
    *   BIN_FILE                    =
      TABLES
        otf                         = t_otf
        lines                       = t_line
    EXCEPTIONS
       ERR_MAX_LINEWIDTH           = 1
       ERR_FORMAT                  = 2
       ERR_CONV_NOT_POSSIBLE       = 3
       ERR_BAD_OTF                 = 4
       OTHERS                      = 5
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
        loop at t_line.
          concatenate w_string t_line into w_string.
        endloop.                           " LOOP AT T_LINE
    *" convert the 132 line character to 255 character ....................
        do.
          t_attach = w_string.
          append t_attach.
          shift w_string left by 255 places.
          if w_string is initial.
            exit.
          endif.                           " IF W_STRING IS INITIAL
        enddo.                             " DO
        t_objbin[] = t_attach[].
    *" Body of the mail..................................................
        clear t_message. refresh t_message.
        t_message = 'This is a mail from SAP ECC6'.
        append t_message.
        t_message = 'Thanks and Regards'.
        append t_message.
        t_message = 'Sravanthi'.
        append t_message.
        describe table t_message lines w_msg.
    *" Document data.......................................................
        w_docdata-obj_name = 'SAPRPT'.
        w_docdata-expiry_dat = sy-datum + 10.
        w_docdata-obj_descr = 'This mail from Sravanthi'.
        w_docdata-sensitivty = 'F'.
        w_docdata-doc_size = w_msg * 255.
        w_docdata-obj_langu = sy-langu .
    *" Fill the packing list...............................................
        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.
        t_packing_list-body_num = w_msg.
        t_packing_list-doc_type = 'RAW'.
        append t_packing_list.
        t_packing_list-transf_bin = 'X'.
        describe table t_objbin lines w_objbin.
    *" doc_size = (lines in pdf table) * 255...............................
        t_packing_list-doc_size = w_objbin * 255.
        t_packing_list-body_num = w_objbin.
        t_packing_list-doc_type = 'PDF'.
        t_packing_list-obj_name = 'smart'.
        t_packing_list-obj_descr = 'test'.
        append t_packing_list.
    *" Fill the receiver parameters........................................
        if p_mail eq 'X'.
          clear t_receivers.
          t_receivers-receiver = p_mailid.
          t_receivers-rec_type = 'U'.
          append t_receivers.
    *" Fax.................................................................
        elseif p_fax eq 'X'.
          clear t_receivers.
          t_receivers-receiver = p_faxno.
          t_receivers-rec_type = 'F'.
          t_receivers-com_type = 'FAX'.
          append t_receivers.
        endif.                             " IF P_MAIL EQ 'X'
        w_sender = 'SAPDEV02'.
    *  FUNCTION MODULE SO_DOCUMENT_SEND_API1                              *
    *  This function module enables you send a new document including any *
    *  existing attachments. The document and the attachments are         *
    *  transferred in the same table. They are created when sent and can  *
    *  also be placed in the sender's outbox.                             *
        call function 'SO_DOCUMENT_SEND_API1'
          exporting
            document_data              = w_docdata
            put_in_outbox              = 'X'
            sender_address             = w_sender
            commit_work                = 'X'
          tables
            packing_list               = t_packing_list
            contents_bin               = t_objbin
            contents_txt               = t_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.
        if sy-subrc ne 0.
          write:/ 'Error When Sending the File', sy-subrc.
        else.
          write:/ 'Mail sent'.
        endif.
      elseif p_fax eq 'X'.
      endif.
    Regards,
    Sravanthi

  • Function module to Print Customer Invoice as PDF and to Printer

    Hi,
    I am writing a program to create a document through FB01. After that I also need to a PRINT the customer invoice for Same document. I need to print Invoice as PDF and Report and print to a Printer. Which Function Modules can I use for these purposes.
    Thanks.
    FS
    Moderator Message: SDN is not here to do your job for you. There are plenty of good developers who work at CSC who can help you out. Thread locked.
    Edited by: Neil Gardiner on Oct 5, 2010 6:38 PM

    Hi,
    please see the given link,It may help you.
    Re: Regarding Print Problem in ALV
    Regards,
    Shamma

  • SAP forms to pdf and email

    I need to email sales orders as PDF files.  Is there a fairly easy way to do this?  I have the "SAP" email function working,  Just need to send the form as PDF instead of JPG.
    Thanx,
    Tim Pope

    Hi Tim,
    In the 2007A version, the PDF format will be available in the standard email function. I had heard a rumour that they would release the same functionality in the 2005A SP1 enhancement pack that has just been released but I cannot see it in the documentation.
    Other options are to use a third-party report writer or add-on (Third Wave make a Crystal-based add-on that should have the functionality you need). The ALD might also be capable of exporting and emailing in PDF format. Your final option is to write your own add-on and use the PrintEvent to capture the data from the sales order in XML format and convert it into PDF (search the forum as I'm sure I saw posts about available APIs that can do this).
    Kind Regards,
    Owen

  • PDF and email issue

    Not sure where to post this. My problem is this: my tax agent sent me a tax organizer in the PDF format where I enter all of our tax information. I completed the document and emailed it back. When he opens it, the only information that shows up are check marks that I put in certain boxes. No text, no figures. My tax guy is using a PC. I then sent it to another PC user friend and he had the same result.
    Is this an issue on my end or the PC end? Any ideas?

    He probably created the PDF fill-in form in Adobe Acrobat. These forms often don't work properly unless both parties have the same version of the full Acrobat product (Standard or Pro).
    It's also possible that you worked on the document in Preview rather than Acrobat, another case in which the form fields may or may not work.
    If you don't have Acrobat on your Mac, you could download the free Acrobat Reader and try this again. Version 8 and later are supposed to support filling in form fields. Version 9 is the current release.

  • PDF and Email Functionality

    Hi all
    Please guide me how to send smartform as an attachment through email.and the attachment should be PDF. I am new to this kind of thing. please guid me step wise.
    regards
    Pkumar

    Hi,
    Check this prog...
    *& 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.
    reward points if it is helpful..
    regards,
    Omkar.

  • Draw document saved as PDF and emailed is faulty when printed

    Each month I create 12 parish-magazine pages of advertisements in Draw, save the set as a PDF document and email it for printing. Consistently, when printed some pages are reproduced smaller than the rest.
    Can someone tell me why, please?

    First-base solution: the pages in question run into the printer's margins and the driver is set to shrink the pages rather than crop them. Check what the printer's margins are and ensure that the document's margins are the same or larger. This sort of problem can arise when you are printing on a printer not connected to the Mac where the document is created (so you don't get a warning).

  • Sending SAPSCRIPT in PDF through email

    Hi everybody,
    I'm trying to send via email a sapscript. I red more posts regarding this issue but nothing seems to run correctly.
    Some posts refers to a sample program ZRICH_0003.
    I've just copied the code and replaced the form's name with one of mine and run it.
    The function SO_NEW_DOCUMENT_ATT_SEND_API1 return with error code 2 (document not sent). I really don't know why. I've just run it in two different SAP (4.7 and 5.0)
    Both didn't work. Both systems are UNIX. Must I do something in customizing or some RFC definition?
    Is there anybody that have a simple program that uses this function? 
    Thanks in advance
    Fabrizio

    i have tried the same thing. first generating spool & then convering sppol to PDF.
    REPORT  ZPO_PDF NO STANDARD PAGE HEADING
      LINE-SIZE 254.
    converts list to PDF - send via mail as attachment
    TABLES: adrp,  "Persons (central address administration)
            bhdgd, "Common data area batch heading routine
            bsik,  "Accounting: Secondary Index for Vendors
            usr21. "Assign user name address key
    General data definition
    TYPE-POOLS: icon.
    TYPE-POOLS: slis.
    DATA: d_linsz            LIKE sy-linsz.
    Constants
    CONSTANTS: c_yes(1)        TYPE c VALUE 'X'.
    Structures
    DATA: e_variant  TYPE disvariant.
    Selection-screen
      DATA: le_parameters LIKE pri_params.
      DATA: l_valid(1) TYPE c.
      DATA: lt_pdf TYPE TABLE OF tline WITH HEADER LINE.
      DATA: l_spool_c LIKE tsp01_sp0r-rqid_char.
      DATA: l_spool_i LIKE tsp01-rqident,
            _RECEIVER LIKE bsik-xref3.
    Get the SPOOL number
    PARAMETERS:
      spoolno LIKE TSP01-RQIDENT.
      l_spool_i =  spoolno.
    DATA: NUMBYTES TYPE I,
          ARC_IDX LIKE TOA_DARA,
          pdfspoolid like tsp01-rqident,
          jobname like tbtcjob-jobname,
          jobcount like tbtcjob-jobcount,
          is_otf.
    DATA PDF LIKE TLINE OCCURS 100 WITH HEADER LINE.
      CALL FUNCTION 'CONVERT_OTFSPOOLJOB_2_PDF'
          EXPORTING
            SRC_SPOOLID                    = l_spool_i
            NO_DIALOG                      = ' '
          DST_DEVICE                     =
          PDF_DESTINATION                =
          IMPORTING
            PDF_BYTECOUNT                  = numbytes
            PDF_SPOOLID                    = pdfspoolid
          OTF_PAGECOUNT                  =
            BTC_JOBNAME                    = jobname
            BTC_JOBCOUNT                   = jobcount
          TABLES
            PDF                            = lt_pdf
          EXCEPTIONS
            ERR_NO_OTF_SPOOLJOB            = 1
            ERR_NO_SPOOLJOB                = 2
            ERR_NO_PERMISSION              = 3
            ERR_CONV_NOT_POSSIBLE          = 4
            ERR_BAD_DSTDEVICE              = 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.
      IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    Build the mail
      PERFORM build_mail
        TABLES lt_pdf
        USING _receiver.
    FORM prepare_print_format USING parameters LIKE priparams.
      DATA: BEGIN OF lt_report_source OCCURS 0,
              line(72) TYPE c,
            END OF lt_report_source.
      DATA: l_string_linsz TYPE string.
      DATA: l_tabix LIKE sy-tabix.
      DATA: BEGIN OF lt_sentencia OCCURS 0,
              line(72) TYPE c,
            END OF lt_sentencia.
      DATA: lt_tsp1d TYPE TABLE OF tsp1d WITH HEADER LINE.
      READ REPORT sy-repid INTO lt_report_source.
      CHECK sy-subrc = 0.
      CLEAR: l_tabix.
      WHILE NOT l_string_linsz CS '.'.
        ADD 1 TO l_tabix.
        READ TABLE lt_report_source
          INDEX l_tabix.
        TRANSLATE lt_report_source-line TO UPPER CASE.
        IF l_string_linsz CS 'REPORT'
          OR lt_report_source-line CS 'REPORT'.
          CONCATENATE l_string_linsz
                      lt_report_source-line
            INTO l_string_linsz
            SEPARATED BY space.
          CONDENSE l_string_linsz.
        ENDIF.
      ENDWHILE.
      TRANSLATE l_string_linsz USING '. '.
      CLEAR: lt_report_source.
      REFRESH: lt_report_source.
      FREE: lt_report_source.
      SPLIT l_string_linsz AT space INTO TABLE lt_sentencia.
      LOOP AT lt_sentencia
        WHERE line CS 'LINE-SIZE'.
        l_tabix = sy-tabix.
        EXIT.
      ENDLOOP.
      ADD 1 TO l_tabix.
      READ TABLE lt_sentencia
        INDEX l_tabix.
      SELECT *
        INTO CORRESPONDING FIELDS OF TABLE lt_tsp1d
        FROM tsp1d
        WHERE type = 'L'
          AND outcolumns >= lt_sentencia-line.
      SORT lt_tsp1d
        BY outcolumns.
      READ TABLE lt_tsp1d
        INDEX 1.
      parameters-linct = lttsp1d-outrows.
      parameters-linsz = ltsentencia-line.
      parameters-paart = lttsp1d-papart.
    ENDFORM.                    " prepare_print_format
    FORM build_mail     TABLES tpdf STRUCTURE tline
                        USING _receiver TYPE c.
      DATA: l_length_t_pdf TYPE i.
      DATA: l_string TYPE xstring.
      DATA: l_string_bck TYPE string.
      DATA: l_length_string TYPE i.
      DATA: l_length_objbin TYPE i.
      DATA: l_max_tabix TYPE i.
      DATA: l_dif TYPE i.
      DATA: l_hex_null TYPE x VALUE '00'.
      DATA: lt_objtxt           LIKE solisti1   OCCURS 10 WITH HEADER LINE.
      DATA: l_tab_lines         LIKE sy-tabix.
      DATA: le_doc_chng         LIKE sodocchgi1.
      DATA: lt_objpack          LIKE sopcklsti1 OCCURS 2 WITH HEADER LINE.
      DATA: lt_objhead          LIKE solisti1   OCCURS 1 WITH HEADER LINE.
      DATA: lt_reclist          LIKE somlreci1  OCCURS 5 WITH HEADER LINE.
      DATA: lt_contents_bin     LIKE solisti1   OCCURS 0 WITH HEADER LINE.
    Mail text
    (...here you should fill table lt_objtxt-line)
      lt_objtxt-line = 'First line of text'.
      append lt_objtxt.
      lt_objtxt-line = 'Second line'.
      append lt_objtxt.
      DESCRIBE TABLE lt_objtxt LINES l_tab_lines.
      READ TABLE lt_objtxt INDEX l_tab_lines.
      le_doc_chng-doc_size = ( l_tab_lines - 1 ) * 255
                             + STRLEN( lt_objtxt ).
      le_doc_chng-obj_descr = 'PO in PDF By mail'.
      CLEAR lt_objpack-transf_bin.
      lt_objpack-head_start = 1.
      lt_objpack-head_num   = 0.
      lt_objpack-body_start = 1.
      lt_objpack-body_num   = l_tab_lines.
      lt_objpack-doc_type   = 'RAW'.
      APPEND lt_objpack.
    Attached file, in PDF-format
      DESCRIBE FIELD tpdf LENGTH l_length_t_pdf.
      CLEAR: l_string_bck,
             l_string.
      LOOP AT tpdf.
        CONCATENATE l_string_bck tpdf INTO l_string_bck.
        l_dif = l_length_t_pdf - STRLEN( tpdf ).
        DO l_dif TIMES.
          CONCATENATE l_string_bck l_hex_null INTO l_string_bck.
        ENDDO.
        CONCATENATE l_string tpdf INTO l_string.
      ENDLOOP.
      sy-subrc = 0.
      WHILE sy-subrc = 0.
        REPLACE l_hex_null WITH space INTO l_string_bck.
      ENDWHILE.
      l_length_string = strlen( l_string_bck ).
      DESCRIBE FIELD lt_contents_bin LENGTH l_length_objbin.
      l_max_tabix = ceil( l_length_string / l_length_objbin * '1.0' ).
      DO l_max_tabix TIMES.
        lt_contents_bin = l_string_bck.
        APPEND lt_contents_bin.
        IF sy-tabix <> l_max_tabix.
          l_string_bck = l_string_bck+l_length_objbin.
        ENDIF.
      ENDDO.
      DESCRIBE TABLE lt_contents_bin LINES l_tab_lines.
      APPEND lt_objhead.
      lt_objpack-transf_bin = c_yes.
      lt_objpack-head_start = 1.
      lt_objpack-head_num   = 1.
      lt_objpack-body_start = 1.
      lt_objpack-body_num   = l_tab_lines.
      lt_objpack-doc_type   = 'PDF'.
      lt_objpack-doc_size   = ( l_tab_lines - 1 ) * 255.
      LOOP AT lt_contents_bin.
      ENDLOOP.
      lt_objpack-doc_size = lt_objpack-doc_size + STRLEN( lt_contents_bin ).
      APPEND lt_objpack.
    lt_reclist-receiver = 'testmailgmail.com'.
      lt_reclist-rec_type = 'U'.
      APPEND lt_reclist.
    Finally! we send the mail
      CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
        EXPORTING
          document_data                    = le_doc_chng
          put_in_outbox                    = c_yes
        TABLES
          packing_list                     = lt_objpack
          object_header                    = lt_objhead
          contents_bin                     = lt_contents_bin
         contents_hex                     =
          contents_txt                     = lt_objtxt
          receivers                        = lt_reclist
        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.
    ENDFORM.                    " build_mail

  • Conversion SAPSCRIPT to PDF and send per mail

    Hi all,
    I would like to send a sapscript per mail as PDF attachment. I checked on the forum and followed some threads for that, but I still have a problem :
    - I'm using the open_form function with ITCPO-TDGETOTF = 'X'
    - in the CLOSE_FORM i get the OTF data in the internal table it_otf
    CALL FUNCTION 'CLOSE_FORM'
    TABLES
       OTFDATA                        = it_otf
    - than I'm using the function: (it_otf as input it_pdf as output table): 
    CALL FUNCTION 'CONVERT_OTF'
    EXPORTING
       FORMAT                      = 'PDF'
       MAX_LINEWIDTH               = 132
        PDF_DELETE_OTFTAB           = 'X'
    IMPORTING
        BIN_FILESIZE                = W_bin_filesize
        BIN_FILE                    = g_binfile
      TABLES
        OTF                         = it_otf
        LINES                       = it_pdf
    this function dumps with the message : "*255" nicht als Zahl interpretierbar
    what' wrong ?
    thank you in advance for your help.

    Hi Fred,
    I'm with this issue and doing exactly what you said, but it is not working.
    Below my code. Is it missing something?
    1 - tb_otf is retrieving the correct values.
    CALL FUNCTION 'CLOSE_FORM'
           IMPORTING
             RESULT  = RESULT
           tables
             otfdata = tb_otf.
    2 - c_binfile is populated correctly but nothing happens with table lt_otf 
    CALL FUNCTION 'CONVERT_OTF'
         EXPORTING
           FORMAT                      = 'PDF'
           MAX_LINEWIDTH               = 132
           PDF_DELETE_OTFTAB           = ' '
         IMPORTING
           BIN_FILESIZE                = L_SIZE
           BIN_FILE                    = c_binfile
         TABLES
           OTF                         = tb_otf
           LINES                       = lt_otf.
    3 - lt_solix is populated correctly
    DATA : BEGIN OF lt_solix OCCURS 0,
             line TYPE x LENGTH 255,
             END OF lt_solix.
    CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
       EXPORTING
         buffer                = c_binfile
       TABLES
         binary_tab            = lt_solix.
    4 - data packing all right
    *   E-mail body
        CLEAR lt_packing_list.
        REFRESH lt_packing_list.
        lt_packing_list-transf_bin = ''.
        lt_packing_list-head_start = 1.
        lt_packing_list-head_num   = 0.
        lt_packing_list-body_start = 1.
        lt_packing_list-body_num   = l_numbytes.
        lt_packing_list-doc_type   = 'RAW'.
        lt_packing_list-obj_name   = 'BODY'.
        lt_packing_list-obj_descr  = 'CORPO'.
        lt_packing_list-doc_size   = l_numbytes.
        APPEND lt_packing_list.
    *   E-mail attachment
        lt_packing_list-transf_bin = 'X'.
        lt_packing_list-head_start = 1.
        lt_packing_list-head_num   = 0.
        lt_packing_list-body_start = 1.
        lt_packing_list-body_num   = l_numbytes.
        lt_packing_list-doc_type   = 'PDF'.
        lt_packing_list-obj_descr  = nast-objky.
        lt_packing_list-obj_name   = 'PICTURE'.
        lt_packing_list-doc_size   = l_numbytes.
        APPEND lt_packing_list.
    5 - send e-mail
    CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
           EXPORTING
             document_data              = wa_document_data
             put_in_outbox              = 'X'
            commit_work                = 'X'
          TABLES
            packing_list               = lt_packing_list
            object_header              = lt_object_header
    *        contents_bin               = lt_objbin
    contents_HEX = lt_solix
            contents_txt               = lt_contents_txt
            receivers                  = lt_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.
    When I check SOST transaction I see the e-mail but the body content I cant see and the attachment I cant open.
    The same logic was working in version 5.0 (now we're in 6.0). But it was using content_bin parameter which is obsolete now, from now we need to use to content_hex parameter.
    Please, could you help me?
    Thanks

  • Payslip to PDF and email

    Hi Friends,
    I have a requirement where we need to generate differerent PDF files for employee salary slips. These generated PDFs would then be emailed to individual employees (email id stored in IT 0105). In one of the threads ( Payslips to be converted into individual PDF file & sent to email of emp) it says that ESS implementation of Remuneration statement in PDF can be modified to get this done. I could only find a HR_ESS_PAYSLIP_TO_PDF form in the system and not sure of how I can achive it using this smart form.
    Any hints on this would be highly appreciated.

    Hi,
      You can try this function module to convert the payslip to PDF form
    IT_OUT[] = IT_OTF-OTFDATA.
      CALL FUNCTION 'SSFCOMP_PDF_PREVIEW'
        EXPORTING
          I_OTF                    = IT_OUT[]
        EXCEPTIONS
          CONVERT_OTF_TO_PDF_ERROR = 1
          CNTL_ERROR               = 2
          OTHERS                   = 3.
      IF SY-SUBRC <> 0.
    *Not Applicable
      ENDIF.
    Regards,
    Vani.

Maybe you are looking for