Creating pdf and attaching to email
Hello,
I am trying to write a script to help manual work and am stuck at below point:
When click save in SAP I get pdf document generated (nhremote). What I would like to do is to somehow automatically save it on my drive and attach it in the new email that is generated after each save.
Script end:
'session.findById("wnd[1]/usr/btnSPOP-VAROPTION1").press - SAVING the changes and pdf is generated at this point. takes some time to popup.
'Set MyApp = CreateObject("Outlook.Application")
'Set MyItem = MyApp.CreateItem(0) 'olMailItem
'With MyItem
'.To = "[email protected]"
'.Subject = "Subject"
'.ReadReceiptRequested = False
'.HTMLBody = RDD
'End With
'MyItem.Display
is there any way I can put action to save and attach saved file to the email? Also please keep in mind that the script is looped and it does this for many documents. Since NHREMOTE to generate pdf usually takes sometime and is a popup window I'm afraid it can be very complicated and mess up easily.
Hello Gediminas,
try this:
'-Begin-----------------------------------------------------------------
'-Directives----------------------------------------------------------
Option Explicit
'-Variables-----------------------------------------------------------
Dim application, SapGuiAuto, connection, session, RepName
Dim WScr, MyApp, MyItem, FileName
'-Main----------------------------------------------------------------
If Not IsObject(application) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
Set connection = application.Children(0)
End If
If Not IsObject(session) Then
Set session = connection.Children(1)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject application, "on"
End If
Set WScr = CreateObject("WScript.Shell")
If IsObject(WScr) Then
RepName = "PROGDELE"
FileName = "C:\Schnell\Dummy\" & RepName & ".pdf"
session.findById("wnd[0]/tbar[0]/okcd").text = "/nSE38"
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/ctxtRS38M-PROGRAMM").text = RepName
session.findById("wnd[0]/usr/btnSHOP").press
WScript.Sleep 500
WScr.AppActivate "ABAP Editor: Report " & RepName & " anzeigen"
WScript.Sleep 2000
session.findById("wnd[0]/usr/cntlEDITOR/shellcont/shell").SetFocus()
WScr.SendKeys "+{F5}" 'Customize Shift+F5 to File.ExportPDF
WScript.Sleep 250
wscr.SendKeys FileName
WScript.Sleep 250
wscr.SendKeys "{ENTER}"
WScript.Sleep 1000
Set MyApp = CreateObject("Outlook.Application")
If IsObject(MyApp) Then
Set MyItem = MyApp.CreateItem(0)
With MyItem
.To = "[email protected]"
.Subject = "Subject"
.ReadReceiptRequested = False
.Body = "Here comes the file"
.Attachments.Add FileName
End With
MyItem.Display
'MyItem.Send
Set MyItem = Nothing
Set MyApp = Nothing
End If
Set WScr = Nothing
End If
'-End-------------------------------------------------------------------
This script starts the TAC SE38 and loads the Report PROGDELE. It exports the report as PDF and sends the PDF file via e-mail to hugo.bambi.
All you have to do, to try this script, is to customize your SE38 view, that the shortcut Shift+F5 ist set to File.ExportPDF.
You see, it is possible to save a PDF from SAP and to send it as e-mail attachment . Also you see it is possible to handle SAP dialog windows. And it should be not a great problem to do this steps in loop for more than one document.
Let us know your result.
Cheers
Stefan
Similar Messages
-
Is it possible for me to script Illustrator to save as PDF and attach to email ?
Hi,
I am after a script to save my current working file as PDF (with some settings) and then bring up a blank outlook email with that file attached ?
I do a lot of artwork and have to get it approved, I am getting bored of manually saving to PDF then going to find the file and then clicking send to > mail recipient etc etc
You know the drill guys.
So would it be possible for me to just run a script that does all that for me ready to insert the persons name or even add the persons name within the script ?
thanks
LeeWell, as the kids' paper-crafts book I used to try to put together which frustrated the hell out of me, mockingly read on the bottom of the instructions: "ТЕРПЕНИЕ И ТРУД ВСЕ ПЕРЕТРУТ"
That is, patience and perseverance will overcome all.
To use the below, you've gotta get Autohotkey_L, I believe, and it's not that hard to use.. but it takes some time to learn the various things if you want to write your own ones like this:
{{YOUR_OWN_HOTKEY_HERE}}::
MyTempFile = C:\Users\{{YOUR_USER_NAME}}\last_proof_sent.txt
Run {{YOUR_JSX_SCRIPT}}.jsx ;Save the PDF proof - the script needs to write a temp text file in a place somewhere, which writes the full name of your saved PDF!
; I called my temp text file "last_proof_sent.txt"
CurrentDateTime := A_Now ;get current time
sleep, 500
FileGetTime, FileTime, %MyTempFile% ;get mod date of this temp file
TimeCounter = 0 ;initialize time counter for waiting for PDF to save
While(CurrentDateTime > FileTime and TimeCounter < 1000) ;waiting period to see if temp text file has updated since start of this script
sleep, 20
TimeCounter++
FileGetTime, FileTime, %MyTempFile% ; each time get the modification date of the temp text file
If(CurrentDateTime < FileTime){
FileRead, MyPDFFileName, %MyTempFile% ;read the contents of temp file for location of PDF file path (It was written there by your JSX script, hopefully)
If Not ErrorLevel{
m := ComObjActive("Outlook.Application").CreateItem(0)
m.Subject := "Greetings to all" ; <---- Subject -----
m.To := "address here" ; <---- Recipient -----
m.HTMLBody := "email body" ; <---- Email message body -----
m.Display
m.attachments.add(MyPDFFileName) ; This is the attachments!
} else {
MsgBox, Error Reading the temporary file %MyTempFile%
} else {
MsgBox, "Sorry, action timed-out."
return
*** I have tested this on one file where I had a test folder on my desktop. The ExtendScript likes to put the file path like "~Desktop/", but I used myFile.fsName to get the full "C:/Users/Me..." name in case it was gonna be confusing to AHK. -
Script to merge data from Numbers into Pages document, export as PDF and send via email
Hi,
I am wondering if it would be possible to achieve the following with an applescript:
1. Merge Names from Numbers into a multi-page Pages document.
2. Export each page of the resulting document as a PDF
3. Attach each of these PDFs to an email with specific text in the body of the email, setting the subject, the 'from' email address, as well as the 'to' email address from a field in the Numbers document.
4. Optionally send the emails automatically.
I would be glad to know if this is possible before I embark on trying to write such a script, and for any advice/script that would help me on my way.
Thanks,
NickThanks Bernard. Sorry if my original post wasn't that clear. I think you've pretty much got it in your paragraph starting "So, I think you're asking for", but will explain more in the hope that it will be clearer:
I have a Numbers table with 2 columns: Name and Email. I have say 50 people in this table and I need to email each person a version of a one page Pages document which would be identical except for their name.
The Name field is the only field that needs to be merged into the Pages document (one time only).
Once the merging has taken place the versions of the one page Pages document need to be exported as a PDF and attached to emails, one email from each person in the table in the Numbers document, with each email going to the email address corresponding to the name in the Numbers document.
The text in the email would be identical except for the name again. The text for the email body, subject as well as the 'from' field would be contained in the script (i.e. generated by the script).
It would also be good to have the option of sending the emails automatically or manually, so that I could check that the emails that are generated are correct before sending.
I hope that's clearer!
Nick -
Not Able to send pdf as attachment through email
Hi,
I am trying to send the generated pdf as attachment throught email and for the same i am referring to this blog
http://www.sdn.sap.com/irj/scn/weblogs;jsessionid=(J2EE3417100)ID1409662650DB01562818410448928630End?blog=/pub/wlg/8551
but when i am trying to send the mail using the method given in this blog , i am getting this error
com.sap.tc.adobe.pdfobject.core.PDFObjectRuntimeException: Processing exception during a "MergeData" operation. Request start time: Fri Dec 11 18:05:24 IST 2009 com.adobe.ProcessingException: PDF is not interactive. Data can only be imported into interactive forms. Exception Stack Trace: com.adobe.ProcessingException: PDF is not interactive
and at the backend i am getting the error as
#com.sun.mail.smtp.SMTPSendFailedException: 501 Bad address syntax
Can any one please help me out with a solution ?? Any suggestions are welcomed
Thanks a lot in advanceHi,
Thanks for your reply , but i cannot set the enabled property of the form as true as we are not using the licensed version of the live cycle designer . But if i try the example step by step then even by setting the enabled property as false , the pdf is generated and sent through the email and when i am trying to do the same thing in one of my applications its not working . The pdf is generated but as soon as i click on the button send mail the above told error is displayed .
There needs to be some other explaination for the error -
How to convert binary data to PDF and attach to the particular po
our client wants to attach the pdf coming from portal as attachment to that particular PO. From portal the pdf will come in binary format. Find how will we convert that binary data back to pdf and attach to the PO in R/3?
Hi,
You can downlaod Binary data into PDF using GUI_DOWNLOAD...pass the binary data and the BINSIZE...
santhosh -
Error message an error occurred while signing in " when I worked with Create PDF and at the signed
Error message "an error occurred while signing in " when I worked with Create PDF and at the signed in status. Please help so that I can continu my work.
Hi Stacy,
Thank you for your attention.
I have been working with Create PFD under normal procedures including
sign-in and several documents had been finished. However, when continued
creating another document the computer took a long time to pprocess and
finally a mesage appeared: "An error occurred while signing in" and stopped
there. I clicked the OK button and start creating again and the same
message appeared once more. I tried to log off and log in again in no
avail. So I went to the help site and called for help.
Later, I decided to reboot the computer and tried once more. This time it
worked and I continued creating. Thanks.
laozhao39 -
Is a update going to be added, which will allow me to attach documents to emails via yahoo (i.e. reply and attachment to emails)
Is a update going to be added, which will allow me to attach documents to emails via yahoo (i.e. reply and attachment to emails)
-
Create PDF and run action does not actually run the action after producing the pdf from word
When I select "Create PDF and Run Action" in word it does not actually run the action in Acrobat it just sets the tool, why?
Hi Amerispec,
Thank you for posting on the forums, Please explain the workflow steps along with the version of the Adobe Acrobat and OS you are working on.
thanks,
Vikrantt Singh -
Submit button to create PDF and XML attachment in a single email message
All,
We have to submit both an XML file and a PDF file in a single email as the user expects both formats. They do not want to extract the XML from the PDF file. (The PDF file contains some information that is not in the XML but is used for documentation purposes.) We are using Livecycle Designer 8.
I currently have Javascript code in a button to attach an XML file but would also like to attach a PDF version in the same email:
event.target.submitForm({cURL
:"mailto:" + vSubmitTo +"?subject="+LEASEIMPORT.ValidationCheck.Subform55.EmailSubject.rawValue+"&body=Please find the 2 files file to be imported ",cSubmitAs:"XML",cCharset:"utf-8"});
Thanks in advance
LesterBill, thanks for replying. I thought I should explain our scenario:
We have designed a PDF form for data input. This form is distributed as a "stand-alone" PDF - not residing on a server. The user fills in the form which produces a legal document. The user then hits a submit button which produces an XML document which is emailed to a person in the organisation who uses the XML for import into another application. However they also require the PDF document to be emailed as this contains supplementary information which is not contained in the XML file. (i.e. some fields are not exported with the XML file). -
Hi,
I am using CRM ONLINE 2013.
How to automate below process?
1. On Approval Of Quotation, Run Report.
2. Generate PDF.
3. Send an Email With PDF as attachment.
As i have gone through many forums for this topic, but creating a plugin code for generating Report PDF is not possible in CRM ONLINE.
So, What is the alternate way to do this..?
Thanks.This is my entire code mentioned below:-
<!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" 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('ABM_Infotech_SalesQuote');
//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 = "Report1.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 = "ABM_Infotech_SalesQuote"; //set this to the report you are trying to download
var reportID = "751089AA-74B8-E211-B52F-D8D3855B253B"; //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:ABMFilteredQuote=" + 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> -
Exporting a crystal report as PDF and Attaching to an email via code - Filename Issuses?
Post Author: alynch
CA Forum: .NET
I need to export a crystal report as a pdf and send it out via email. I have created a subroutine that works but the attached filename come up as "untitled.txt" so the receiving machine believes it is a text file. If I rename it on the recipients machine to a ".pdf" I can open it with acrobat and it looks OK. Does anyone know how to rename the file as a pdf prior to sending it out?
Thank You.
al
I have included a copy of the subroutine:
Dim repdoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument()
Dim diskOpts As New CrystalDecisions.Shared.DiskFileDestinationOptions()
Dim ExpOpts As CrystalDecisions.Shared.ExportOptions
Dim MailOpts As New CrystalDecisions.Shared.MicrosoftMailDestinationOptions()
repdoc = Me.CrystalReport11
repdoc.Load("C:\Documents and Settings\User\My Documents\Visual Studio 2005\Projects\WindowsApplication3\WindowsApplication3\CrystalReport1.rpt")
ExpOpts = repdoc.ExportOptions
With ExpOpts
.ExportDestinationType = CrystalDecisions.[Shared].ExportDestinationType.MicrosoftMail
.ExportFormatType = CrystalDecisions.[Shared].ExportFormatType.PortableDocFormat
End With
With MailOpts
.MailMessage = "Message"
.MailToList = "enter email adress here"
.MailSubject = "Attached is a PDF file - .net Export test "
End With
ExpOpts.DestinationOptions = MailOpts
Try
repdoc.Export()
Catch err As Exception
MessageBox.Show(err.ToString())
End Try
End SubPost Author: Knight
CA Forum: .NET
I had this same problem today, here's what I used. Its built in 2 parts. Step one loops throught and exports PDF copies of a traking report. Step 2 builds an email list from a SQl query and sends it.STEP ONE:Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'Declare the some variables Dim row1 As DataRow Dim brokerID As String Dim brokername As String Dim brokerEmail As String Dim shipdate As String Dim crParameterFieldDefinitions As ParameterFieldDefinitions Dim crParameterFieldDefinition As ParameterFieldDefinition Dim crParameterValues As New ParameterValues() Dim crParameterDiscreteValue As New ParameterDiscreteValue() Dim crParameterFieldDefinitions1 As ParameterFieldDefinitions Dim crParameterFieldDefinition1 As ParameterFieldDefinition Dim crParameterValues1 As New ParameterValues() Dim crParameterDiscreteValue1 As New ParameterDiscreteValue() Dim CrReport As New CrystalReport1() ' Report Name Dim report As ReportDocument = "O:KNIFormats_ReportPrivateSMStageShipmentInfo" Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions() Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions() Dim SHIPDATE123 As String SHIPDATE123 = _month & "/" & _day & "/" & year Dim db As String db = System.Configuration.ConfigurationSettings.AppSettings("Datalogin") Dim sqlCon As New SqlConnection sqlCon.ConnectionString = db Dim strsql1 As String strsql1 = "SELECT tblSOOrd_Hdr.BrokerCd, tblSO_Ord_Hdr.BrokerName, tblSM_Ship_Hdr.ShipDate " strsql1 &= "FROM tblSO_Ord_Hdr INNER JOIN tblSM_Ship_Hdr ON tblSO_Ord_Hdr.Locale = tblSM_Ship_Hdr.Locale AND tblSO_Ord_Hdr.OrdNo = tblSM_Ship_Hdr.OrdNo AND " strsql1 &= " tblSO_Ord_Hdr.RlsNo = tblSM_Ship_Hdr.RlsNo INNER JOIN tblSys_Cust_Broker ON tblSO_Ord_Hdr.BrokerCd = tblSys_Cust_Broker.BrokerCd " strsql1 &= "GROUP BY tblSO_Ord_Hdr.BrokerCd, tblSM_Ship_Hdr.ShipDate, tblSO_Ord_Hdr.BrokerName " strsql1 &= "HAVING (tblSM_Ship_Hdr.ShipDate = '" & SHIPDATE123 & "') " Dim da1 As New SqlDataAdapter(strsql1, sqlCon) Dim worktbl1 As DataTable worktbl1 = New DataTable("tblEmail") da1.Fill(worktbl1) da1.FillSchema(worktbl1, SchemaType.Source) If worktbl1.Rows.Count > 0 Then For Each row1 In worktbl1.Rows brokerID = CStr(row1("BrokerCd")).Trim brokername = CStr(row1("BrokerName")).Trim shipdate = CStr(row1("ShipDate")).Trim CrReport.Load() crParameterDiscreteValue.Value = shipdate crParameterFieldDefinitions = CrReport.DataDefinition.ParameterFields crParameterFieldDefinition = crParameterFieldDefinitions.Item("ShipDate") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) crParameterDiscreteValue1.Value = brokerID crParameterFieldDefinitions1 = CrReport.DataDefinition.ParameterFields crParameterFieldDefinition1 = crParameterFieldDefinitions1.Item("Broker") crParameterValues1 = crParameterFieldDefinition1.CurrentValues crParameterValues1.Clear() crParameterValues1.Add(crParameterDiscreteValue1) crParameterFieldDefinition1.ApplyCurrentValues(crParameterValues1) CrDiskFileDestinationOptions.DiskFileName = "c:Test_Folder20" & _year & "-" & _month & "-" & day & "" & brokername & ".pdf" CrFormatTypeOptions.FirstPageNumber = 1 ' Start Page in the Report CrFormatTypeOptions.LastPageNumber = 1000 ' End Page in the Report CrFormatTypeOptions.UsePageRange = True CrExportOptions = CrReport.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.PortableDocFormat .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With Try CrReport.Export() Catch err As Exception MessageBox.Show("DID NOT EXPORT") End Try Next MessageBox.Show("All PDF's exported succesfully") End If End SubSTEP 2: Private Sub Button3Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim row2 As DataRow Dim SHIPDATE123 As String SHIPDATE123 = _month & "/" & _day & "/" & year Dim db1 As String db1 = System.Configuration.ConfigurationSettings.AppSettings("Datalogin") Dim sqlCon As New SqlConnection sqlCon.ConnectionString = db1 Dim strsql2 As String strsql2 = "SELECT tblSOOrd_Hdr.BrokerCd, tblSys_Cust_Broker.BrokerName, tblSM_Ship_Hdr.ShipDate, tblSys_Cust_Broker.ContactEmail " strsql2 &= "FROM tblSO_Ord_Hdr INNER JOIN tblSM_Ship_Hdr ON tblSO_Ord_Hdr.Locale = tblSM_Ship_Hdr.Locale AND tblSO_Ord_Hdr.OrdNo = tblSM_Ship_Hdr.OrdNo AND " strsql2 &= " tblSO_Ord_Hdr.RlsNo = tblSM_Ship_Hdr.RlsNo INNER JOIN tblSys_Cust_Broker ON tblSO_Ord_Hdr.BrokerCd = tblSys_Cust_Broker.BrokerCd " strsql2 &= "GROUP BY tblSO_Ord_Hdr.BrokerCd, tblSM_Ship_Hdr.ShipDate, tblSys_Cust_Broker.ContactEmail, tblSys_Cust_Broker.BrokerName, tblSys_Cust_Broker.Email_ASN " strsql2 &= "HAVING (tblSM_Ship_Hdr.ShipDate = '" & SHIPDATE123 & "') AND (tblSys_Cust_Broker.Email_ASN = 1) AND (tblSys_Cust_Broker.ContactEmail <> '') " Dim da1 As New SqlDataAdapter(strsql2, sqlCon) Dim worktbl2 As DataTable worktbl2 = New DataTable("tblEmail12") da1.Fill(worktbl2) da1.FillSchema(worktbl2, SchemaType.Source) Dim brokerID As String Dim brokername As String Dim brokerEmail As String Dim shipdate As String If worktbl2.Rows.Count > 0 Then For Each row2 In worktbl2.Rows brokerID = CStr(row2("BrokerCd")).Trim brokername = CStr(row2("BrokerName")).Trim brokerEmail = CStr(row2("ContactEmail")).Trim shipdate = CStr(row2("ShipDate")).Trim Dim mail As New MailMessage Dim att As String att = "c:Test_Folder20" & _year & "-" & _month & "-" & _day & "" & brokername & ".pdf" 'set the addresses mail.From = New MailAddress("[email protected]") mail.To.Add(brokerEmail) mail.Attachments.Add(New Attachment(att)) 'set the content mail.Subject = "Shipment Tracking report from Knox Nursery for " & SHIPDATE123 mail.IsBodyHtml = True mail.Body = "
" mail.Body &= "This shipment update has been requested by:
" 'send the message Dim smtp As New SmtpClient smtp.Send(mail) ' MessageBox.Show("No Records Found", "Failed to send", MessageBoxButtons.OK, MessageBoxIcon.Stop Next Else MessageBox.Show("No broker have opted in", "No Emails Sent", MessageBoxButtons.OK, MessageBoxIcon.Information) End If MessageBox.Show("Emails sent... ", "Emails Sent", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub -
Convert spool to pdf and send in email sometimes attachment duplicated.
Hi all, I have a process that creates a spool, converts it to a pdf and then attaches it to an email. My problem is that sometimes, the same attachment is duplicated.
The process seems to work fine in debug mode (the attachment changes for each loop) but when I run it in the background, every few emails, it will duplicate an attachment.
I have noticed that the size of the pdf seems to change properly but that the content of the pdf does not match. So, it is like it gets the correct size of the pdf but not the body.
This is code that a consultant wrote and I am pretty new to abap/sap. I have changed some of the code because it was trying to handle an endless loop (I figured it should not have to handle (be in) an endless loop). I changed that code and it is working but this previous issue still exists. Thanks for your help.
*& Form PROCESS_EMPLOYEE
FORM process_employee .
* process appraisal only
IF it_final[] IS NOT INITIAL .
* READ DISTRIBUTION LIST *
REFRESH : it_email, it_idlient.
*Sort by supervisor
SORT it_final[] BY supervisor.
LOOP AT it_final INTO wa_final .
APPEND wa_final TO it_final1 .
AT END OF supervisor .
* Perform to create the PDF from the Output
report = 'zhr_pm_appemail'.
PERFORM create_pdf using report.
** Perform to email the PDF attachment
** to the supervisor and the Mailing list
subject = 'Performance Appraisals'.
PERFORM process_email using subject.
REFRESH it_final1 .
CLEAR it_final1 .
CLEAR wa_final .
FREE MEMORY ID 'MEM'.
ENDAT .
ENDLOOP.
ENDIF.
ENDFORM. " PROCESS_EMPLOYEE
*& Form CREATE_PDF
FORM create_pdf using report.
DATA: spoolno TYPE tsp01-rqident.
DATA : p_repid TYPE sy-repid .
DATA: v_len TYPE i , v_len1 TYPE i .
DATA: v_temp(8) TYPE c .
DATA: p_uname TYPE sy-uname .
DATA: it_tsp01 TYPE STANDARD TABLE OF tsp01 WITH HEADER LINE .
* DATA: it_pdf TYPE tline OCCURS 0 WITH HEADER LINE .
TABLES: tsp01.
DATA: var TYPE c .
*-- STRUCTURES
DATA:
lc_rq2name TYPE tsp01-rq2name.
DATA:
mstr_print_parms TYPE pri_params,
mc_valid(1) TYPE c,
mi_bytecount TYPE i,
mi_length TYPE i,
mi_rqident TYPE tsp01-rqident.
*-- INTERNAL TABLES
DATA:
mtab_pdf TYPE tline OCCURS 0 WITH HEADER LINE,
mc_filename TYPE rlgrap-filename.
*-- SELECTION SCREEN
DATA:
p_linsz TYPE sy-linsz VALUE 80, " Line size
p_paart TYPE sy-paart VALUE 'X_65_80'. " Paper Format
p_uname = sy-uname .
var = var + 1.
p_repid = report.
* START-OF-SELECTION .
concatenate p_repid+0(9)
p_uname+0(3)
into mc_filename
separated by '_'.
translate mc_filename to upper case.
*-- Setup the Print Parmaters
CALL FUNCTION 'GET_PRINT_PARAMETERS'
EXPORTING
authority = space
copies = '1'
cover_page = space
data_set = space
department = space
destination = space
expiration = '1'
immediately = space
new_list_id = 'X'
no_dialog = 'X'
user = sy-uname
IMPORTING
out_parameters = mstr_print_parms
valid = mc_valid
EXCEPTIONS
archive_info_not_found = 1
invalid_print_params = 2
invalid_archive_params = 3
OTHERS = 4.
IF sy-subrc = 0 .
*--Make sure that a printer destination has been set up. If this is not done the PDF module abends.
*-- Explicitly set line width, and output format so that
*-- the PDF conversion comes out OK
mstr_print_parms-linsz = p_linsz.
mstr_print_parms-paart = p_paart.
EXPORT it_final1 it_email p_email1 p_sender p_date vl_nmth
TO MEMORY ID 'MEM' .
IF report = 'zhr_pm_appandprogemail'.
SUBMIT zhr_pm_appandprogemail TO SAP-SPOOL WITHOUT SPOOL DYNPRO
SPOOL PARAMETERS mstr_print_parms
VIA SELECTION-SCREEN AND RETURN.
ENDIF.
IF report = 'zhr_pm_appemail'.
SUBMIT zhr_pm_appemail TO SAP-SPOOL WITHOUT SPOOL DYNPRO
SPOOL PARAMETERS mstr_print_parms
VIA SELECTION-SCREEN AND RETURN.
ENDIF.
ENDIF.
*Find out what the spool number is that was just created
perform get_spool_number using p_repid p_uname changing mi_rqident.
*converting the spool request into pdf
CALL FUNCTION 'CONVERT_ABAPSPOOLJOB_2_PDF'
EXPORTING
src_spoolid = mi_rqident
no_dialog = space
dst_device = mstr_print_parms-pdest
IMPORTING
pdf_bytecount = mi_bytecount
TABLES
pdf = it_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.
* call function 'DOWNLOAD'
* exporting
* bin_filesize = mi_bytecount
* filename = mc_filename
* filetype = 'BIN'
* importing
* act_filename = mc_filename
* tables
* data_tab = it_mess_att.
CHECK sy-subrc = 0.
* Transfer the 132-long strings to 255-long strings
LOOP AT it_pdf INTO wa_pdf.
TRANSLATE wa_pdf USING ' ~'.
CONCATENATE v_gd_buffer wa_pdf INTO v_gd_buffer.
CLEAR wa_pdf .
ENDLOOP.
TRANSLATE v_gd_buffer USING '~ '.
DO.
it_mess_att = v_gd_buffer.
APPEND it_mess_att.
SHIFT v_gd_buffer LEFT BY 255 PLACES.
IF v_gd_buffer IS INITIAL.
EXIT.
ENDIF.
ENDDO.
ENDFORM. " CREATE_PDF
* FORM get_spool_nunber *
* Get the most recent spool created by user/report *
form get_spool_number using f_repid
f_uname changing f_rqident.
data:
lc_rq2name TYPE rlgrap-filename.
concatenate f_repid+0(6)
f_repid+7(3)
f_uname+0(3)
into lc_rq2name.
* separated by '_'.
translate lc_rq2name to upper case.
select * from tsp01 where rq2name = lc_rq2name
order by rqcretime descending.
f_rqident = tsp01-rqident.
exit.
endselect.
if sy-subrc ne 0.
clear f_rqident.
endif.
endform. " get spool number
*& Form SEND_MAIL
FORM send_email USING p_email subject.
REFRESH it_mess_bod.
* Default subject matter
gd_subject = text-019 ."'Subject'.
gd_attachment_desc = text-020 ."'Performance Appraisal'.
IF subject = 'Performance Appraisals and Progression I'.
gd_attachment_desc = 'PerfAppAndProg'.
ENDIF.
IF subject = 'Performance Appraisals'.
gd_attachment_desc = 'PerfAppraisal'.
ENDIF.
* 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 .pdf
PERFORM send_file_as_email_attachment
TABLES it_mess_bod
it_mess_att
USING p_email
subject
'PDF'
gd_attachment_desc
gd_attachment_desc
p_sender
gd_sender_type
CHANGING gd_error
gd_reciever.
ENDFORM. " SEND_MAIL
* FORM process_email *
FORM process_email using subject.
DESCRIBE TABLE it_mess_att LINES gd_recsize.
CHECK gd_recsize > 0.
PERFORM send_email USING p_email1 subject.
* perform send_email using p_email2.
ENDFORM. "process_email
*& 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.
CLEAR : ld_email , ld_mtitle , ld_format , ld_attdescription ,
ld_attfilename , ld_sender_address , ld_sender_address_type ,
w_doc_data.
REFRESH: t_packing_list.
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.
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.
LOOP AT it_email.
* Add the recipients email address
t_receivers-receiver = it_email.
t_receivers-rec_type = 'U'.
t_receivers-com_type = 'INT'.
t_receivers-notif_del = 'X'.
t_receivers-notif_ndel = 'X'.
APPEND t_receivers.
ENDLOOP.
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_HEX = 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.
IF sy-subrc = 0.
PERFORM update_infotype_0019 .
ENDIF.
* Populate zerror return code
* ld_error = sy-subrc.
** stop .
* READ TABLE t_receivers WITH KEY retrn_code = '0' .
* IF sy-subrc = 0 .
* v_update_flag = '1' .
* EXPORT v_update_flag TO MEMORY ID 'MEM2' .
* ENDIF .
** Populate zreceiver return code
* LOOP AT t_receivers.
* ld_receiver = t_receivers-retrn_code.
* ENDLOOP.
ENDFORM. "send_file_as_email_attachment
*& Form GET_NEXT_MONTH
FORM get_next_month .
CLEAR v_month .
v_month = vl_nmth+4(2).
REFRESH it_t247 .
CLEAR it_t247 .
CALL FUNCTION 'IDWT_READ_MONTH_TEXT'
EXPORTING
langu = 'E'
month = v_month
IMPORTING
t247 = it_t247.
CLEAR v_mon_text .
v_mon_text = it_t247-ltx .
ENDFORM. " GET_NEXT_MONTH
Edited by: Katie Doody on Feb 24, 2010 12:30 AMThank you for your response, this has allowed me to identify the problem. It is when I create the spool by using the code below. If I add a wait after this, the program works successfully. Is there another way to write the data to create a spool within my initial program rather than doing the submit? Could it be that it is putting data in memory?
SUBMIT zhr_pm_appandprogemail TO SAP-SPOOL WITHOUT SPOOL DYNPRO
SPOOL PARAMETERS mstr_print_parms
VIA SELECTION-SCREEN AND RETURN.
*& Report ZHR_PM_APPANDPROGEMAIL
REPORT ZHR_PM_APPANDPROGEMAIL
NO STANDARD PAGE HEADING
LINE-SIZE 80
LINE-COUNT 65(8).
* MESSAGE-ID zhr.
* INTERNAL TABLES DECLARATION
DATA: it_pdf TYPE tline OCCURS 0 ." WITH HEADER LINE .
* WORK AEA DECLARATION
DATA: wa_pdf TYPE tline .
* Spool to PDF conversions
*DATA: "gd_spool_nr TYPE tsp01-rqident,
* gd_destination TYPE rlgrap-filename,
* gd_bytecount TYPE tst01-dsize,
DATA:v_update_flag TYPE c . "flag for updating infotype 41 last appraisal date
DATA: v_gd_buffer TYPE string.
DATA: BEGIN OF it_final1 OCCURS 0 ,
supervisor TYPE persno ,
pernr TYPE persno ,
ename TYPE pa0001-ename ,
subgroup TYPE persk ,
stext TYPE t503t-ptext ,
lastapp TYPE dats ,
lastjob TYPE dats ,
email TYPE ztype,
darxx(5) TYPE c,
progression(1) TYPE c,
supervisor_desc(50) TYPE c,
END OF it_final1 .
DATA: t_packing_list TYPE sopcklsti1 OCCURS 0 WITH HEADER LINE,
t_contents TYPE solisti1 OCCURS 0 WITH HEADER LINE,
t_receivers TYPE somlreci1 OCCURS 0 WITH HEADER LINE,
t_attachment TYPE solisti1 OCCURS 0 WITH HEADER LINE,
t_object_header TYPE solisti1 OCCURS 0 WITH HEADER LINE,
w_cnt TYPE i,
w_sent_all(1) TYPE c,
w_doc_data TYPE sodocchgi1 .
DATA: gd_error TYPE sy-subrc,
gd_reciever TYPE sy-subrc.
DATA: v_flag TYPE c VALUE '1' .
DATA: BEGIN OF it_final OCCURS 0 ,
subgroup TYPE persk ,
supervisor TYPE persno ,
pernr TYPE persno ,
ename TYPE pa0001-ename ,
stext TYPE t503t-ptext ,
lastapp TYPE dats ,
lastjob TYPE dats ,
email TYPE ztype,
progression(1) TYPE c,
supervisor_desc(50) TYPE c,
END OF it_final .
DATA:it_t247 TYPE STANDARD TABLE OF t247 WITH HEADER LINE .
DATA: it_email TYPE STANDARD TABLE OF zemail WITH HEADER LINE.
*VARIABLE DECLARATION
DATA: p_date TYPE sy-datum , "excution date
vl_date TYPE sy-datum ,
p_email1 TYPE somlreci1-receiver , "receiver
p_sender TYPE somlreci1-receiver . "sender
DATA: w_recsize TYPE i.
DATA: gd_recsize TYPE i.
DATA : vl_nmth TYPE sy-datum.
DATA: v_month(2) TYPE n .
DATA: v_mon_text TYPE t247-ltx .
*START OF SELECTION
START-OF-SELECTION .
REFRESH t_receivers.
IMPORT it_final1 it_email p_email1 p_sender p_date vl_nmth FROM MEMORY ID 'MEM'.
PERFORM get_next_month .
LOOP AT it_final1 .
IF it_final1-progression IS NOT INITIAL.
MOVE-CORRESPONDING it_final1 TO it_final .
APPEND it_final .
CLEAR it_final .
* Add the recipients email address
t_receivers-receiver = it_final1-email.
t_receivers-rec_type = 'U'.
t_receivers-com_type = 'INT'.
t_receivers-notif_del = 'X'.
t_receivers-notif_ndel = 'X'.
APPEND t_receivers.
ENDIF.
ENDLOOP .
PERFORM write_output .
*END OF SELECTION
END-OF-SELECTION .
*& Form WRITE_OUTPUT
FORM write_output .
DATA: l_date(14) TYPE c ,
l_date_temp(14) TYPE c ,
v_date(10) TYPE c ,
v_date1(20) TYPE c ,
v_date1_temp(20) TYPE c ,
f_date(10) TYPE c.
DATA: lv_stext TYPE t503t-ptext .
CLEAR : v_date, v_date1.
CONCATENATE p_date+4(02) p_date+6(02) p_date+0(04)'.' INTO v_date.
CONCATENATE v_mon_text p_date+0(4) INTO l_date_temp SEPARATED BY space.
CONCATENATE l_date_temp '.' INTO l_date.
CONCATENATE v_mon_text vl_nmth+6(2) INTO v_date1_temp SEPARATED BY space.
CONCATENATE v_date1_temp ',' INTO v_date1_temp.
CONCATENATE v_date1_temp vl_nmth(4) INTO v_date1_temp SEPARATED BY space.
CONCATENATE v_date1_temp '.' INTO v_date1.
CONDENSE l_date .
FORMAT INTENSIFIED ON.
SKIP 4.
WRITE:/(80) text-001 CENTERED . "'METROPOLITAN UTILITIES DISTRICT'.
WRITE:/(80) text-002 CENTERED . "'OMAHA NEBR.'.
SKIP 2.
WRITE:/(80) text-003 CENTERED . "'Inter-Departmental Communication'.
FORMAT INTENSIFIED OFF.
WRITE :/(80) v_date CENTERED using edit mask '__/__/____'. " v_date.
SKIP 2.
WRITE: /10 text-004. "'SUBJECT: Performance Appraisals and Progression Increase'.
SKIP 1.
WRITE: /10 text-005, it_final1-supervisor_desc. "'TO: Supervisor'.
SKIP 1.
WRITE: /10 text-006. "'FROM: Anne M. Undajon, Director of Compensation and Benefits'.
SKIP 2.
WRITE:/10 text-007 . "'Listed below are the employees in your area who are due a '.
WRITE:/10 text-008 ,l_date. "'Performance Appraisal during the month of ',l_date.'. "v_mon_text , P_date+0(4)
WRITE:/10 text-009 . "'These employees are also eligible for a progression increase.
WRITE:/10 text-010 . "' A performance appraisal form can be found on-line in the MUD '.
WRITE:/10 text-011 . "'template section. The Performance Appraisal is to be completed '
WRITE:/10 text-012 . "'and discussed with the employee by the immediate supervisor.'
SKIP 2.
WRITE:/10 text-013. "Signed forms should be returned to the Human Resource Department by '.
WRITE:/10 v_date1.
SKIP 2 .
SORT it_final[] BY subgroup .
LOOP AT it_final .
CLEAR: lv_stext .
lv_stext = it_final-stext.
AT NEW subgroup .
TRANSLATE lv_stext TO UPPER CASE .
WRITE:/(80) lv_stext CENTERED .
SKIP 2 .
WRITE: 10 text-014 . "'Employee name' .
WRITE: 32 text-015 . "'Job Date' .
WRITE :44 text-016 . "'Last Appraisal' .
WRITE :59 text-021 . "'Employee' .
WRITE :/10 '--------------------' , 32'----------', 44 '--------------', 59 '--------'.
ENDAT .
WRITE:/10 it_final-ename .
WRITE: 32 it_final-lastjob using edit mask '__/__/____'.
CONCATENATE it_final-lastapp+4(02) it_final-lastapp+6(02) it_final-lastapp+0(04) INTO f_date.
WRITE :44 f_date using edit mask '__/__/____'.
SHIFT it_final-pernr left deleting leading '0'.
WRITE : 59 it_final-pernr.
SKIP 2 .
ENDLOOP.
SKIP 4.
WRITE :10 text-017. "'Anne M. Undajon'.
FORMAT INTENSIFIED ON.
WRITE:/10 text-018. "'Director of Compensation & Benefits'.
FORMAT INTENSIFIED OFF.
ENDFORM. " WRITE_OUTPUT
*& Form GET_NEXT_MONTH
FORM get_next_month .
CLEAR v_month .
v_month = vl_nmth+4(2).
REFRESH it_t247 .
CLEAR it_t247 .
CALL FUNCTION 'IDWT_READ_MONTH_TEXT'
EXPORTING
langu = 'E'
month = v_month
IMPORTING
t247 = it_t247.
CLEAR v_mon_text .
v_mon_text = it_t247-ltx .
ENDFORM. " GET_NEXT_MONTH
Edited by: Katie Doody on Feb 24, 2010 4:07 PM -
Convert spool to PDF and send as email attachment
When i try to convert SAP spool to PDF and send it as email attachment, size of PDF document becomes large as compared to size of the PDF cocument i download using the same spool.
I am using following FMs.
CONVERT_ABAPSPOOLJOB_2_PDF to convert spool to PDF
and
SO_NEW_DOCUMENT_ATT_SEND_API1 to send email with attchment.
some times size of attchment exceeds 2MB and email results in error in SAP connect (SOST).
Any idea on how to compress the PDF attchment??
ThanksHi Venkat,
Can you plesae assist me.
I have a requirement to convert spool to pdf
send an email to users
issue is that attachement is big cant go through
I have used compress, but when I open the pdf file error that file was not correclty decoded
please assist, anyone -
Is it possible to create a standard form that can be emailed to anyone and once filled out by the receiver, have a button that the receiver clicks and the form is encrypted and attached to an email back to the sender and a preset admin password would open it?
Hello Graphicsguy123,
You would need to first create the form ( or Widget in EchoSign) first to generate a url which you can paste it in the email being sent to customers. You would need to make sure you have a Document Cloud Enterprise Premium account in order to create a Widget. If you don't have the account, you can use the trial version to test it. Here is the link:
Global Trial Registration | eSign services from Adobe
-Rijul -
Smartform (otf) as pdf and sending as email-attachment
Hello everybody,
when trying to convert a smartform to pdf and sending it with the FM 'SO_NEW_DOCUMENT_ATT_SEND_API1' i get an error when opening the pdf-file. It says ' a non identified Token w62.10 was found' and the pdf is all empty.
The problem seems to be somewhere between getting the pdf output data from the FM 'convert_otf' and trying to create a bin-object for the attachment.
Here is the code:
call function 'CONVERT_OTF'
EXPORTING
format = 'PDF'
* max_linewidth = 132
IMPORTING
bin_filesize = v_len_in
TABLES
otf = i_otf
lines = i_tline
EXCEPTIONS
err_max_linewidth = 1
err_format = 2
err_conv_not_possible = 3
others = 4.
* Fehlerhandling
if sy-subrc <> 0.
endif.
loop at i_tline.
translate i_tline using '~'.
concatenate wa_buffer i_tline into wa_buffer.
endloop.
translate wa_buffer using '~'.
do.
i_record = wa_buffer.
append i_record.
shift wa_buffer left by 255 places.
if wa_buffer is initial.
exit.
endif.
enddo.
* Attachment
refresh:
i_reclist,
i_objtxt,
i_objbin,
i_objpack.
clear wa_objhead.
i_objbin[] = i_record[].
******* Create Message Body
**** Title and Description
wa_doc_chng-obj_name = 'smartform'.
wa_doc_chng-expiry_dat = sy-datum + 10.
wa_doc_chng-obj_descr = 'smartform'.
wa_doc_chng-sensitivty = 'F'.
* wa_doc_chng-doc_size = v_lines_txt * 255.
**** Main Text
i_objtxt = 'test with pdf-Attachment!'.
append i_objtxt.
describe table i_objtxt lines v_lines_txt.
read table i_objtxt index v_lines_txt.
wa_doc_chng-doc_size = ( v_lines_txt - 1 ) * 255 + strlen( i_objtxt ).
clear i_objpack-transf_bin.
i_objpack-head_start = 1.
i_objpack-head_num = 0.
i_objpack-body_start = 1.
i_objpack-body_num = v_lines_txt.
i_objpack-doc_type = 'RAW'.
append i_objpack.
**** Attachment
* (pdf-Attachment)
i_objpack-transf_bin = 'X'.
i_objpack-head_start = 1.
i_objpack-head_num = 0.
i_objpack-body_start = 1.
* Länge des Attachment ermitteln
describe table i_objbin lines v_lines_bin.
read table i_objbin index v_lines_bin.
i_objpack-doc_size = ( v_lines_bin - 1 ) * 255 + strlen( i_objbin ).
i_objpack-body_num = v_lines_bin.
i_objpack-doc_type = 'PDF'.
i_objpack-obj_name = 'smart'.
i_objpack-obj_descr = 'test'.
append i_objpack.
clear i_reclist.
i_reclist-receiver = receiver.
i_reclist-rec_type = RECEIVER_TYPE.
append i_reclist.
if not receiver is initial.
call function 'SO_NEW_DOCUMENT_ATT_SEND_API1'
EXPORTING
document_data = wa_doc_chng
put_in_outbox = 'X'
TABLES
packing_list = i_objpack
object_header = wa_objhead
CONTENTS_BIN = i_objbin
contents_txt = i_objtxt
receivers = i_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.Hi,
I just observed the following.
call function 'CONVERT_OTF'
EXPORTING
format = 'PDF'
max_linewidth = 132 IMPORTING
bin_filesize = v_len_in
TABLES
otf = i_otf
lines = i_tline
EXCEPTIONS
err_max_linewidth = 1
err_format = 2
err_conv_not_possible = 3
others = 4.
i_objtxt = 'test with pdf-Attachment!'.
append i_objtxt.
describe table i_objtxt lines v_lines_txt.
read table i_objtxt index v_lines_txt.
wa_doc_chng-obj_name = 'smartform'.
wa_doc_chng-expiry_dat = sy-datum + 10.
wa_doc_chng-obj_descr = 'smartform'.
wa_doc_chng-sensitivty = 'F'.
wa_doc_chng-doc_size = v_lines_txt * 255.
clear i_objpack-transf_bin.
i_objpack-head_start = 1.
i_objpack-head_num = 0.
i_objpack-body_start = 1.
i_objpack-body_num = v_lines_txt.
i_objpack-doc_type = 'RAW'.
append i_objpack.
Attachment
(pdf-Attachment)
i_objpack-transf_bin = 'X'.
i_objpack-head_start = 1.
i_objpack-head_num = 0.
i_objpack-body_start = 1.
Länge des Attachment ermitteln
describe table i_objbin lines v_lines_bin.
read table i_objbin index v_lines_bin.
i_objpack-doc_size = v_lines_bin * 255 .
I just tried with your coding and then changed to the below coding.Now I am able to open the PDF in mail.
* Internal Table declarations
DATA: i_otf TYPE itcoo OCCURS 0 WITH HEADER LINE,
i_tline TYPE TABLE OF tline WITH HEADER LINE,
i_receivers TYPE TABLE OF somlreci1 WITH HEADER LINE,
i_record LIKE solisti1 OCCURS 0 WITH HEADER LINE,
* Objects to send mail.
i_objpack LIKE sopcklsti1 OCCURS 0 WITH HEADER LINE,
i_objtxt LIKE solisti1 OCCURS 0 WITH HEADER LINE,
i_objbin LIKE solisti1 OCCURS 0 WITH HEADER LINE,
i_reclist LIKE somlreci1 OCCURS 0 WITH HEADER LINE,
* Work Area declarations
wa_objhead TYPE soli_tab,
w_ctrlop TYPE ssfctrlop,
w_compop TYPE ssfcompop,
w_return TYPE ssfcrescl,
wa_doc_chng typE sodocchgi1,
w_data TYPE sodocchgi1,
wa_buffer TYPE string,"To convert from 132 to 255
* Variables declarations
v_form_name TYPE rs38l_fnam,
v_len_in LIKE sood-objlen,
v_len_out LIKE sood-objlen,
v_len_outn TYPE i,
v_lines_txt TYPE i,
v_lines_bin TYPE i.
call function 'SSF_FUNCTION_MODULE_NAME'
exporting
formname = 'ZZZ_TEST1'
importing
fm_name = v_form_name
exceptions
no_form = 1
no_function_module = 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.
w_ctrlop-getotf = 'X'.
w_ctrlop-no_dialog = 'X'.
w_compop-tdnoprev = 'X'.
CALL FUNCTION v_form_name
EXPORTING
control_parameters = w_ctrlop
output_options = w_compop
user_settings = 'X'
IMPORTING
job_output_info = w_return
EXCEPTIONS
formatting_error = 1
internal_error = 2
send_error = 3
user_canceled = 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.
i_otf[] = w_return-otfdata[].
call function 'CONVERT_OTF'
EXPORTING
format = 'PDF'
max_linewidth = 132
IMPORTING
bin_filesize = v_len_in
TABLES
otf = i_otf
lines = i_tline
EXCEPTIONS
err_max_linewidth = 1
err_format = 2
err_conv_not_possible = 3
others = 4.
* Fehlerhandling
if sy-subrc <> 0.
endif.
loop at i_tline.
translate i_tline using '~'.
concatenate wa_buffer i_tline into wa_buffer.
endloop.
translate wa_buffer using '~'.
do.
i_record = wa_buffer.
append i_record.
shift wa_buffer left by 255 places.
if wa_buffer is initial.
exit.
endif.
enddo.
* Attachment
refresh:
i_reclist,
i_objtxt,
i_objbin,
i_objpack.
clear wa_objhead.
i_objbin[] = i_record[].
******* Create Message Body
**** Title and Description
i_objtxt = 'test with pdf-Attachment!'.
append i_objtxt.
describe table i_objtxt lines v_lines_txt.
read table i_objtxt index v_lines_txt.
wa_doc_chng-obj_name = 'smartform'.
wa_doc_chng-expiry_dat = sy-datum + 10.
wa_doc_chng-obj_descr = 'smartform'.
wa_doc_chng-sensitivty = 'F'.
wa_doc_chng-doc_size = v_lines_txt * 255.
**** Main Text
* wa_doc_chng-doc_size = ( v_lines_txt - 1 ) * 255 + strlen( i_objtxt )
clear i_objpack-transf_bin.
i_objpack-head_start = 1.
i_objpack-head_num = 0.
i_objpack-body_start = 1.
i_objpack-body_num = v_lines_txt.
i_objpack-doc_type = 'RAW'.
append i_objpack.
**** Attachment
* (pdf-Attachment)
i_objpack-transf_bin = 'X'.
i_objpack-head_start = 1.
i_objpack-head_num = 0.
i_objpack-body_start = 1.
* Länge des Attachment ermitteln
describe table i_objbin lines v_lines_bin.
read table i_objbin index v_lines_bin.
i_objpack-doc_size = v_lines_bin * 255 .
i_objpack-body_num = v_lines_bin.
i_objpack-doc_type = 'PDF'.
i_objpack-obj_name = 'smart'.
i_objpack-obj_descr = 'test'.
append i_objpack.
clear i_reclist.
i_reclist-receiver = '[email protected]'.
i_reclist-rec_type = 'U'.
append i_reclist.
call function 'SO_NEW_DOCUMENT_ATT_SEND_API1'
EXPORTING
document_data = wa_doc_chng
put_in_outbox = 'X'
TABLES
packing_list = i_objpack
object_header = wa_objhead
CONTENTS_BIN = i_objbin
contents_txt = i_objtxt
receivers = i_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 your problem is solved,kindly close the thread and reward points.If you need clarifications,get back.
Maybe you are looking for
-
Used of Sap text variable with replacement path in Bo designer
Dear experts, I created a univers based on a SAp BW query. In this query I used a text variable in order to get dynamic header columns. The text variable is done by using "replacement path" that is the text is derived automatically from the user inpu
-
ERROR IN LISTENER CONFIGURATION
hi, i am trying to configure a listener in my computer,having database name as kali and while starting the listener i m getting these errors and i have configured listener1 for my database and port no is 1522. so please give me the solution.. OS- RHE
-
Viewing calendars of multiple accounts on iPhone
I succeed in seeing all MY calendars (i.e. those from my account [email protected]) However there are some other calendars i would like to take with me on my iphone. iCal let's you delegate other calendars, so the same should be true for the iphone-c
-
In the properties of our AP1131 under the advanced tab there are poe settings. I have up on this. Most of our AP1131 are powered by Cisco 3750 switches. A few are power by Cisco poe injectors. What are the purpose of those poe settings for the AP? Ho
-
Import XML... vs .importXML [JS CS4]
I'm looking to programmatically import an XML file, but the results are not what I expected. For example, take this file, sample.xml <persons> <person pid="0"> <name>John Q. Public</name> <age>54</age> <date string="birthday">