Print Google Spreadsheet cells to PDF file - javascript

I want to print cells from a sheet to a PDF file. This PDF file should not be created in Google Drive but downloadable to disk.
Here is my code:
function PrintPDF(LigneDebut, ColonneDebut, LigneFin, ColonneFin) {
SpreadsheetApp.flush();
feuilleImprimer = SpreadsheetApp.getActiveSpreadsheet();
var sheet = feuilleImprimer.getActiveSheet();
var gid = sheet.getSheetId();
var pdfOpts = '&size=A4&fzr=false&portrait=true&fitw=true&gridlines=false&printtitle=false&sheetnames=false&pagenum=UNDEFINED&attachment=false&gid='+gid;
var printRange = '&c1='+ColonneDebut + '&r1='+LigneDebut + '&c2='+ColonneFin + '&r2='+LigneFin; // B2:APn
var url = feuilleImprimer.getUrl().replace(/edit$/, '') + 'export?format=pdf' + pdfOpts + printRange;
var app = UiApp.createApplication().setWidth(200).setHeight(150);
app.setTitle('Printing ' + feuilleImprimer.getSheetName());
var link = app.createAnchor('Download PDF', url).setTarget('_new');
app.add(link);
feuilleImprimer.show(app);
}
Some APIs are out of date: UiApp, Anchor, and UiInstance.
This generates warning messages.
By what methods to replace these deprecated API?
Thanks for your help.

To address the deprecated issue, just go to the official Apps Script doc reference. For example, in the case Class UiApp, use the HTML Service instead.
For a working code of converting spreadsheet to pdf and download, check ixhd/gist:3660885 and Convert and Email Google Spreadsheets as PDF Files.

Related

Email specific sheet tab

I want to e-mail an individual sheet tab as a PDF using script. This script below will send the entire workbook/sheet as a PDF file (which is a great start, but not ideal). However, I am only interested in e-mailing the specific sheet tab named "Alpha".
function sendpdf() {
var originalSpreadsheet = SpreadsheetApp.getActive();
var message = 'Hello, \n\n' + 'Attached is the priority list for today.';
var subject = "Priority List for - " + new Date().toString();
var emailTo = "first#example.com,second#example.com";
var pdf = DriveApp.getFileById(originalSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'PRIORITY.pdf',content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
}

File attachment is not opening-Not Allowed Error

This is my first attempt to prepare a dynamic pdf form in livecycle designer es4. In this form, there is an option to add and view attachment. As I have little experience in javascript coding, I went to the adobe forum and found a very good example here. I have done some changes in original code to run in my form. I can attach file successfully with this code. But my problem is that when I want to open file attachment in Acrobat Pro XI, it is showing below error instead of opening the file. This error is showing independent of file attachment type (e.g. .doc, .jpg, .txt and .pdf file).error image. Here is screenshot of security of Acrobat Pro XIscreenshot 1 screenshot 2 and file linkhere.
Below code is written in the form-
//Code for add button
// Get Import Name
var cName = AttachName.rawValue;
// Test for empty value
if(!/^\s*$/.test(cName))
{// Do Import
try{
var bRtn = event.target.importDataObject(cName);
if(bRtn)
{
var cDesc = AttachDesc.rawValue;
if(!/^\s*$/.test(cName))
{
var oAtt = event.target.getDataObject(cName);
oAtt.description = cDesc;
}
app.alert("File Attachment Successfully Imported",3);
}
else
app.alert("Unable to import File Attachment",0);
}catch(e){
app.alert("An Error Occured while Importing the File Attachment:\n\n" + e);
}
}
else
app.alert("Attachment name must be non-empty");
//code for populating dropdown list
this.rawValue = null;
this.clearItems();
var a = event.target.dataObjects;
if (a !== null) {
for (var i = 0; i < a.length; i++) {
this.addItem(a[i].name);
}
}
//code for open attachment button
var cName = AttachNameSel.rawValue;
//var nAction = ExportAction.rawValue;
try{
event.target.exportDataObject({cName:cName, nLaunch:2});
} catch(e) {
app.alert("An Error Occured while Exporting the File Attachment: " + cName + "\n\n" + e);
}
Any help from anyone in the community would be greatly appreciated.
Thanks
Tony

Line chart generated image that will be sent through email

I want to create a line chart similar below:
I just wonder if there are available framework or API available in ASP.NET MVC that generates chart images since my goal is to send this via email. I'm thinking if I can just put something like <img src="http://imageapi.com?date1=20170101&date=20170130" /> then api will be handling the chart image generation.
On searching, I found a lot of chart framework using javascript but I doubt it will properly work on different email clients.
Thanks a lot!
Google Image Charts will do that. Pass data and display settings via the URL, and it will return an image.
eg.
<img src="https://chart.googleapis.com/chart?cht=lc&chd=t:30,10,45,38,25|10,20,10,20,10&chls=2.0,0.0,0.0&chs=200x125&chg=0,20,3,3,10,20&chxt=x,y&chxl=0:|Week1|Week2|Week3|Week4|Week5|1:|0|20|40|60|80|100&chs=800x300&chm=o,ff9900,0,-1,10.0|d,ff0000,1,-1,10.0&chco=FFC6A5,DEBDDE&chdl=Click|GRU" />
produces this chart:
They provide a playground for testing: https://developers.google.com/chart/image/docs/chart_playground
Note however that Google are not maintaining it further, but have no plans to remove this functionality:
While the dynamic and interactive Google Charts are actively maintained, we officially deprecated the static Google Image Charts way back in 2012. This gives us the right to turn it off without notice, although we have no plans to do so.
What is your design ?
Your chart must be generated in web page,then it must be having html generated.
If no html is generated and only image is generated then this is best.
now you can send same content in.
If image is not generated then again you have 2 option here
i) Send complete html in email body along with concern js/css
ii) you can convert those html into image using(say c#) then send mail.
Please mention your complete scenario.
There are different types of chart API available in market, both open source and licensed, you can use any one to generate your chart/diagram in page and you can send that page as an email attachment using following code.
[HttpPost]
public ActionResult SendWebPageAsAttachment()
{
var subject = Request.Form["subject"]; // You can provide subject from page or code
var mailContent = Request.Form["bodyInnerHTML"]; // get the body inner HTML by form name
var Body = "<div style='background-color:white;'>" + Request.Form["mailContent"] + "</div>"; // Email Body
var attachmentName = DateTime.Now.ToString("yyyy/MM/dd").Replace("/", "-") + "_" +
DateTime.Now.ToLongTimeString().Replace(" ", "_") + ".html"; // Attachment Name
var baseUrl = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority +
HttpContext.Request.ApplicationPath.TrimEnd('/') + '/'; // Base URL
string src = #"src=""";
mailContent = mailContent.Replace(src, src + baseUrl.Remove(baseUrl.Length - 1));
mailContent = "<html><head><link href='" + baseUrl + "Themes/styles.css' rel='stylesheet' type='text/css' /><link href='" +
baseUrl + "Themes/style.css' rel='stylesheet' type='text/css' /></head><body>" + WebUtility.HtmlDecode(mailContent) +
"</body></html>";
try
{
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info#MyWebsiteDomainName.com", "myIDPassword");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info#MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info#MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("MyEmailID#gmail.com"));
mail.IsBodyHtml = true;
mail.Subject = subject;
mail.Body = Body;
var mailDataBytes = ASCIIEncoding.Default.GetBytes(mailContent);
var mailStream = new MemoryStream(mailDataBytes);
mail.Attachments.Add(new Attachment(mailStream, attachmentName));
smtpClient.Send(mail);
}
catch (Exception ex)
{
//catch
}
ViewBag.IsHttpPost = true;
return View("SendWebPageAsAttachment");
}

upload file to google drive folder instead of user browser javascript/jsquery

My current script uses the code below to download a CSV file to local drive,
function table2CSV() {
var dataURL = '',
fieldSeparator = ',',
textField = '"',
lineSeparator = '\n',
regExpTesto = /(")/g,
regExp = /[";]/;
$('table tr').each(function() {
var dataRow = '';
if ($('input:checkbox', this).is(':checked') || $(this).is(':first- child'))
{
$('td', this).not(':last').each(function() {
var value = $(this).text();
if (dataRow !== '') dataRow += fieldSeparator;
if (regExp.test(value)) {
value = textField + value.replace(regExpTesto, '$1$1') + textField;
}
dataRow += value;
});
if (dataURL !== '') dataURL += lineSeparator;
dataURL += dataRow;
}
});
window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);
}
The download is done bye this line as far as I can tell :
window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);
I would like to be able to have it download(upload/saved) to a shared google drive folder instead.
I have seen similar questions on the forum but can't seem to see how to point the download to a shared google-drive folder.
What must code must be added/changed in order to achieve this ?
Thank you
EDIT: Nevermind, just realised they say it does not support data URIs:
Data URIs and file:// URLs are not supported
I will keep this answer in case anyone else searches for non-data URI uploading
Having a quick look, I came upon Save to Drive
While this might not be exactly what you want, it looks like an easy way to add the ability to save the contents of any URI (hopefully a data URI too) to Google Drive, like so:
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-savetodrive"
data-src="//example.com/path/to/myfile.pdf"
data-filename="My Statement.pdf"
data-sitename="My Company Name">
</div>

Printing PDF to folder in Google Drive

I am using a script to print a spreadsheet to PDF.I would like to print it to a location on the drive "PDF Folder". Anyone know how to do this?
Heres is my code :
function printpdf(){
var spreadsheet_id="0AkcI3cOVJXI3dHg3Nnk3Y2JUakViTkUzQzdXSUdLNEE";
var spreadsheetFile = DocsList.getFileById(spreadsheet_id);
var blob = spreadsheetFile.getAs('application/pdf');
DocsList.createFile(blob);
}
just add it to the folder like this :
(I reproduce the whole code)
function printpdf(){
var spreadsheet_id="0AkcI3cOVJXI3dHg3Nnk3Y2JUakViTkUzQzdXSUdLNEE";
var spreadsheetFile = DocsList.getFileById(spreadsheet_id);
var blob = spreadsheetFile.getAs('application/pdf');
var folder = DocsList.getFolder('PDF Folder'); //get the folder by its path
var pdf = DocsList.createFile(blob).addToFolder(folder);
}

Categories

Resources